1 /*
2 * Copyright (c) 2014, 2021, Red Hat, Inc. All rights reserved.
3 * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
4 * Copyright (c) 2025, 2026, Oracle and/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
28 #include "compiler/oopMap.hpp"
29 #include "gc/shared/continuationGCSupport.hpp"
30 #include "gc/shared/fullGCForwarding.inline.hpp"
31 #include "gc/shared/gcTraceTime.inline.hpp"
32 #include "gc/shared/preservedMarks.inline.hpp"
33 #include "gc/shared/tlab_globals.hpp"
34 #include "gc/shared/workerThread.hpp"
35 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
36 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
37 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
38 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
39 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
40 #include "gc/shenandoah/shenandoahFreeSet.hpp"
41 #include "gc/shenandoah/shenandoahFullGC.hpp"
42 #include "gc/shenandoah/shenandoahGenerationalFullGC.hpp"
43 #include "gc/shenandoah/shenandoahGlobalGeneration.hpp"
44 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
45 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
46 #include "gc/shenandoah/shenandoahHeapRegionClosures.hpp"
47 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
48 #include "gc/shenandoah/shenandoahMark.inline.hpp"
49 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
50 #include "gc/shenandoah/shenandoahMetrics.hpp"
51 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
52 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
53 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
54 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
55 #include "gc/shenandoah/shenandoahStackWatermark.hpp"
56 #include "gc/shenandoah/shenandoahSTWMark.hpp"
57 #include "gc/shenandoah/shenandoahUtils.hpp"
58 #include "gc/shenandoah/shenandoahVerifier.hpp"
59 #include "gc/shenandoah/shenandoahVMOperations.hpp"
60 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
61 #include "memory/metaspaceUtils.hpp"
62 #include "memory/universe.hpp"
63 #include "oops/compressedOops.inline.hpp"
64 #include "oops/oop.inline.hpp"
65 #include "runtime/orderAccess.hpp"
66 #include "runtime/vmThread.hpp"
67 #include "utilities/copy.hpp"
68 #include "utilities/events.hpp"
69 #include "utilities/growableArray.hpp"
70
71 ShenandoahFullGC::ShenandoahFullGC() :
72 ShenandoahGC(ShenandoahHeap::heap()->global_generation()),
73 _gc_timer(ShenandoahHeap::heap()->gc_timer()),
74 _preserved_marks(new PreservedMarksSet(true)) {}
75
76 ShenandoahFullGC::~ShenandoahFullGC() {
77 delete _preserved_marks;
78 }
79
80 bool ShenandoahFullGC::collect(GCCause::Cause cause) {
81 vmop_entry_full(cause);
82 // Always success
83 return true;
84 }
85
86 void ShenandoahFullGC::vmop_entry_full(GCCause::Cause cause) {
87 ShenandoahHeap* const heap = ShenandoahHeap::heap();
88 TraceCollectorStats tcs(heap->monitoring_support()->full_stw_collection_counters());
89 ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_gross);
90
91 heap->try_inject_alloc_failure();
92 VM_ShenandoahFullGC op(cause, this);
93 VMThread::execute(&op);
94 }
95
96 void ShenandoahFullGC::entry_full(GCCause::Cause cause) {
97 static const char* msg = "Pause Full";
98 ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::full_gc, true /* log_heap_usage */);
99 EventMark em("%s", msg);
100
101 ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
102 ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
103 "full gc");
104
105 op_full(cause);
106 }
107
108 void ShenandoahFullGC::op_full(GCCause::Cause cause) {
109 ShenandoahHeap* const heap = ShenandoahHeap::heap();
110
111 ShenandoahMetricsSnapshot metrics(heap->free_set());
112
113 // Perform full GC
114 do_it(cause);
115
116 if (heap->mode()->is_generational()) {
117 ShenandoahGenerationalFullGC::handle_completion(heap);
118 }
119
120 if (metrics.is_good_progress()) {
121 heap->notify_gc_progress();
122 } else {
123 // Nothing to do. Tell the allocation path that we have failed to make
124 // progress, and it can finally fail.
125 heap->notify_gc_no_progress();
126 }
127
128 // Regardless if progress was made, we record that we completed a "successful" full GC.
129 _generation->heuristics()->record_success_full();
130 heap->shenandoah_policy()->record_success_full();
131
132 // Leaving full GC, we need to flip barriers back to idle.
133 ShenandoahCodeRoots::arm_nmethods();
134 ShenandoahStackWatermark::change_epoch_id();
135
136 {
137 ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_propagate_gc_state);
138 heap->propagate_gc_state_to_all_threads();
139 }
140 }
141
142 void ShenandoahFullGC::do_it(GCCause::Cause gc_cause) {
143 ShenandoahHeap* heap = ShenandoahHeap::heap();
144 heap->release_injected_pins();
145
146 // A full GC may be entered directly, or as an upgrade from a failed
147 // degenerated GC. In the latter case, self-forwarded objects may be
148 // present from the failed evacuation. Drain those marks before any phase
149 // (verify, update_roots, phase1_mark_heap) walks headers.
150 {
151 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_un_self_forward);
152 heap->un_self_forward_cset_regions();
153 }
154
155 if (heap->mode()->is_generational()) {
156 ShenandoahGenerationalFullGC::prepare();
157 }
158
159 if (ShenandoahVerify) {
160 heap->verifier()->verify_before_fullgc(_generation);
161 }
162
163 if (VerifyBeforeGC) {
164 Universe::verify();
165 }
166
167 // Degenerated GC may carry concurrent root flags when upgrading to
168 // full GC. We need to reset it before mutators resume.
169 heap->set_concurrent_strong_root_in_progress(false);
170 heap->set_concurrent_weak_root_in_progress(false);
171
172 heap->set_full_gc_in_progress(true);
173
174 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
175 assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
176
177 {
178 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_pre);
179 heap->pre_full_gc_dump(_gc_timer);
180 }
181
182 {
183 ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
184 // Full GC is supposed to recover from any GC state:
185
186 // a0. Remember if we have forwarded objects
187 bool has_forwarded_objects = heap->has_forwarded_objects();
188
189 // a1. Cancel evacuation, if in progress
190 if (heap->is_evacuation_in_progress()) {
191 heap->set_evacuation_in_progress(false);
192 }
193 assert(!heap->is_evacuation_in_progress(), "sanity");
194
195 // a2. Cancel update-refs, if in progress
196 if (heap->is_update_refs_in_progress()) {
197 heap->set_update_refs_in_progress(false);
198 }
199 assert(!heap->is_update_refs_in_progress(), "sanity");
200
201 // b. Cancel all concurrent marks, if in progress
202 if (heap->is_concurrent_mark_in_progress()) {
203 heap->cancel_concurrent_mark();
204 }
205 assert(!heap->is_concurrent_mark_in_progress(), "sanity");
206
207 // c. Update roots if this full GC is due to evac-oom, which may carry from-space pointers in roots.
208 if (has_forwarded_objects) {
209 update_roots(true /*full_gc*/);
210 }
211
212 // d. Abandon reference discovery and clear all discovered references.
213 ShenandoahReferenceProcessor* rp = _generation->ref_processor();
214 rp->abandon_partial_discovery();
215
216 // e. Sync pinned region status from the CP marks
217 heap->sync_pinned_region_status();
218
219 if (heap->mode()->is_generational()) {
220 ShenandoahGenerationalFullGC::restore_top_before_promote(heap);
221 }
222
223 // The rest of prologue:
224 _preserved_marks->init(heap->workers()->active_workers());
225
226 assert(heap->has_forwarded_objects() == has_forwarded_objects, "This should not change");
227 }
228
229 if (UseTLAB) {
230 // Note: PLABs are also retired with GCLABs in generational mode.
231 heap->gclabs_retire(ResizeTLAB);
232 heap->tlabs_retire(ResizeTLAB);
233 }
234
235 OrderAccess::fence();
236
237 phase1_mark_heap();
238
239 // Once marking is done, which may have fixed up forwarded objects, we can drop it.
240 // Coming out of Full GC, we would not have any forwarded objects.
241 // This also prevents resolves with fwdptr from kicking in while adjusting pointers in phase3.
242 heap->set_has_forwarded_objects(false);
243
244 heap->set_full_gc_move_in_progress(true);
245
246 // Setup workers for the rest
247 OrderAccess::fence();
248
249 // Initialize worker slices
250 ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);
251 for (uint i = 0; i < heap->max_workers(); i++) {
252 worker_slices[i] = new ShenandoahHeapRegionSet();
253 }
254
255 {
256 // The rest of code performs region moves, where region status is undefined
257 // until all phases run together.
258 ShenandoahHeapLocker lock(heap->lock());
259
260 phase2_calculate_target_addresses(worker_slices);
261
262 OrderAccess::fence();
263
264 phase3_update_references();
265
266 phase4_compact_objects(worker_slices);
267
268 phase5_epilog();
269 }
270 heap->start_idle_span();
271
272 // Resize metaspace
273 MetaspaceGC::compute_new_size();
274
275 // Free worker slices
276 for (uint i = 0; i < heap->max_workers(); i++) {
277 delete worker_slices[i];
278 }
279 FREE_C_HEAP_ARRAY(worker_slices);
280
281 heap->set_full_gc_move_in_progress(false);
282 heap->set_full_gc_in_progress(false);
283
284 DEBUG_ONLY(heap->assert_no_self_forwards());
285
286 if (ShenandoahVerify) {
287 heap->verifier()->verify_after_fullgc(_generation);
288 }
289
290 if (VerifyAfterGC) {
291 Universe::verify();
292 }
293
294 {
295 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_post);
296 heap->post_full_gc_dump(_gc_timer);
297 }
298 }
299
300 void ShenandoahFullGC::phase1_mark_heap() {
301 GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
302 ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
303
304 ShenandoahHeap* heap = ShenandoahHeap::heap();
305
306 _generation->reset_mark_bitmap<true, true>();
307 assert(heap->marking_context()->is_bitmap_clear(), "sanity");
308 assert(!_generation->is_mark_complete(), "sanity");
309
310 heap->set_unload_classes(_generation->heuristics()->can_unload_classes());
311
312 ShenandoahReferenceProcessor* rp = _generation->ref_processor();
313 // enable ("weak") refs discovery
314 rp->set_soft_reference_policy(true); // forcefully purge all soft references
315
316 ShenandoahSTWMark mark(_generation, true /*full_gc*/);
317 mark.mark();
318 heap->parallel_cleaning(_generation, true /* full_gc */);
319
320 if (ShenandoahHeap::heap()->mode()->is_generational()) {
321 ShenandoahGenerationalFullGC::log_live_in_old(heap);
322 }
323 }
324
325 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
326 private:
327 PreservedMarks* const _preserved_marks;
328 ShenandoahHeap* const _heap;
329 GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
330 int _empty_regions_pos;
331 ShenandoahHeapRegion* _to_region;
332 ShenandoahHeapRegion* _from_region;
333 HeapWord* _compact_point;
334
335 public:
336 ShenandoahPrepareForCompactionObjectClosure(PreservedMarks* preserved_marks,
337 GrowableArray<ShenandoahHeapRegion*>& empty_regions,
338 ShenandoahHeapRegion* to_region) :
339 _preserved_marks(preserved_marks),
340 _heap(ShenandoahHeap::heap()),
341 _empty_regions(empty_regions),
342 _empty_regions_pos(0),
343 _to_region(to_region),
344 _from_region(nullptr),
345 _compact_point(to_region->bottom()) {}
346
347 void set_from_region(ShenandoahHeapRegion* from_region) {
348 _from_region = from_region;
349 }
350
351 void finish() {
352 assert(_to_region != nullptr, "should not happen");
353 _to_region->set_new_top(_compact_point);
354 }
355
356 bool is_compact_same_region() {
357 return _from_region == _to_region;
358 }
359
360 int empty_regions_pos() {
361 return _empty_regions_pos;
362 }
363
364 void do_object(oop p) override {
365 shenandoah_assert_mark_complete(cast_from_oop<HeapWord*>(p));
366 assert(_from_region != nullptr, "must set before work");
367 assert(_heap->global_generation()->is_mark_complete(), "marking must be finished");
368 assert(_heap->marking_context()->is_marked(p), "must be marked");
369 assert(!_heap->marking_context()->allocated_after_mark_start(p), "must be truly marked");
370
371 size_t obj_size = p->size();
372 if (_compact_point + obj_size > _to_region->end()) {
373 finish();
374
375 // Object doesn't fit. Pick next empty region and start compacting there.
376 ShenandoahHeapRegion* new_to_region;
377 if (_empty_regions_pos < _empty_regions.length()) {
378 new_to_region = _empty_regions.at(_empty_regions_pos);
379 _empty_regions_pos++;
380 } else {
381 // Out of empty region? Compact within the same region.
382 new_to_region = _from_region;
383 }
384
385 assert(new_to_region != _to_region, "must not reuse same to-region");
386 assert(new_to_region != nullptr, "must not be null");
387 _to_region = new_to_region;
388 _compact_point = _to_region->bottom();
389 }
390
391 // Object fits into current region, record new location, if object does not move:
392 assert(_compact_point + obj_size <= _to_region->end(), "must fit");
393 shenandoah_assert_not_forwarded(nullptr, p);
394 if (_compact_point != cast_from_oop<HeapWord*>(p)) {
395 _preserved_marks->push_if_necessary(p, p->mark());
396 FullGCForwarding::forward_to(p, cast_to_oop(_compact_point));
397 }
398 _compact_point += obj_size;
399 }
400 };
401
402 class ShenandoahPrepareForCompactionTask : public WorkerTask {
403 private:
404 PreservedMarksSet* const _preserved_marks;
405 ShenandoahHeap* const _heap;
406 ShenandoahHeapRegionSet** const _worker_slices;
407
408 public:
409 ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks, ShenandoahHeapRegionSet **worker_slices) :
410 WorkerTask("Shenandoah Prepare For Compaction"),
411 _preserved_marks(preserved_marks),
412 _heap(ShenandoahHeap::heap()), _worker_slices(worker_slices) {
413 }
414
415 static bool is_candidate_region(ShenandoahHeapRegion* r) {
416 // Empty region: get it into the slice to defragment the slice itself.
417 // We could have skipped this without violating correctness, but we really
418 // want to compact all live regions to the start of the heap, which sometimes
419 // means moving them into the fully empty regions.
420 if (r->is_empty()) return true;
421
422 // Can move the region, and this is not the humongous region. Humongous
423 // moves are special cased here, because their moves are handled separately.
424 return r->is_stw_move_allowed() && !r->is_humongous();
425 }
426
427 void work(uint worker_id) override;
428 private:
429 template<typename ClosureType>
430 void prepare_for_compaction(ClosureType& cl,
431 GrowableArray<ShenandoahHeapRegion*>& empty_regions,
432 ShenandoahHeapRegionSetIterator& it,
433 ShenandoahHeapRegion* from_region);
434 };
435
436 void ShenandoahPrepareForCompactionTask::work(uint worker_id) {
437 ShenandoahParallelWorkerSession worker_session(worker_id);
438 ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
439 ShenandoahHeapRegionSetIterator it(slice);
440 ShenandoahHeapRegion* from_region = it.next();
441 // No work?
442 if (from_region == nullptr) {
443 return;
444 }
445
446 // Sliding compaction. Walk all regions in the slice, and compact them.
447 // Remember empty regions and reuse them as needed.
448 ResourceMark rm;
449
450 GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());
451
452 if (_heap->mode()->is_generational()) {
453 ShenandoahPrepareForGenerationalCompactionObjectClosure cl(_preserved_marks->get(worker_id),
454 empty_regions, from_region, worker_id);
455 prepare_for_compaction(cl, empty_regions, it, from_region);
456 } else {
457 ShenandoahPrepareForCompactionObjectClosure cl(_preserved_marks->get(worker_id), empty_regions, from_region);
458 prepare_for_compaction(cl, empty_regions, it, from_region);
459 }
460 }
461
462 template<typename ClosureType>
463 void ShenandoahPrepareForCompactionTask::prepare_for_compaction(ClosureType& cl,
464 GrowableArray<ShenandoahHeapRegion*>& empty_regions,
465 ShenandoahHeapRegionSetIterator& it,
466 ShenandoahHeapRegion* from_region) {
467 while (from_region != nullptr) {
468 assert(is_candidate_region(from_region), "Sanity");
469 cl.set_from_region(from_region);
470 if (from_region->has_live()) {
471 _heap->marked_object_iterate(from_region, &cl);
472 }
473
474 // Compacted the region to somewhere else? From-region is empty then.
475 if (!cl.is_compact_same_region()) {
476 empty_regions.append(from_region);
477 }
478 from_region = it.next();
479 }
480 cl.finish();
481
482 // Mark all remaining regions as empty
483 for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
484 ShenandoahHeapRegion* r = empty_regions.at(pos);
485 r->set_new_top(r->bottom());
486 }
487 }
488
489 void ShenandoahFullGC::calculate_target_humongous_objects() {
490 ShenandoahHeap* heap = ShenandoahHeap::heap();
491
492 // Compute the new addresses for humongous objects. We need to do this after addresses
493 // for regular objects are calculated, and we know what regions in heap suffix are
494 // available for humongous moves.
495 //
496 // Scan the heap backwards, because we are compacting humongous regions towards the end.
497 // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
498 // humongous start there.
499 //
500 // The complication is potential non-movable regions during the scan. If such region is
501 // detected, then sliding restarts towards that non-movable region.
502
503 size_t to_begin = heap->num_regions();
504 size_t to_end = heap->num_regions();
505
506 log_debug(gc)("Full GC calculating target humongous objects from end %zu", to_end);
507 for (size_t c = heap->num_regions(); c > 0; c--) {
508 ShenandoahHeapRegion *r = heap->get_region(c - 1);
509 if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
510 // To-region candidate: record this, and continue scan
511 to_begin = r->index();
512 continue;
513 }
514
515 if (r->is_humongous_start() && r->is_stw_move_allowed()) {
516 // From-region candidate: movable humongous region
517 oop old_obj = cast_to_oop(r->bottom());
518 size_t words_size = old_obj->size();
519 size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
520
521 size_t start = to_end - num_regions;
522
523 if (start >= to_begin && start != r->index()) {
524 // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
525 _preserved_marks->get(0)->push_if_necessary(old_obj, old_obj->mark());
526 FullGCForwarding::forward_to(old_obj, cast_to_oop(heap->get_region(start)->bottom()));
527 to_end = start;
528 continue;
529 }
530 }
531
532 // Failed to fit. Scan starting from current region.
533 to_begin = r->index();
534 to_end = r->index();
535 }
536 }
537
538 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
539 public:
540 void heap_region_do(ShenandoahHeapRegion* r) override {
541 if (r->is_trash()) {
542 r->try_recycle_under_lock();
543 // No need to adjust_interval_for_recycled_old_region. That will be taken care of during freeset rebuild.
544 }
545 if (r->is_cset()) {
546 // Leave affiliation unchanged
547 r->make_regular_bypass();
548 }
549 if (r->is_empty_uncommitted()) {
550 r->make_committed_bypass();
551 }
552 assert (r->is_committed(), "only committed regions in heap now, see region %zu", r->index());
553
554 // Record current region occupancy: this communicates empty regions are free
555 // to the rest of Full GC code.
556 r->set_new_top(r->top());
557 }
558 };
559
560 class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {
561 private:
562 ShenandoahHeap* const _heap;
563 ShenandoahMarkingContext* const _ctx;
564
565 public:
566 ShenandoahTrashImmediateGarbageClosure() :
567 _heap(ShenandoahHeap::heap()),
568 _ctx(ShenandoahHeap::heap()->global_generation()->complete_marking_context()) {}
569
570 void heap_region_do(ShenandoahHeapRegion* r) override {
571 if (r->is_humongous_start()) {
572 oop humongous_obj = cast_to_oop(r->bottom());
573 if (!_ctx->is_marked(humongous_obj)) {
574 assert(!r->has_live(), "Region %zu is not marked, should not have live", r->index());
575 _heap->trash_humongous_region_at(r);
576 } else {
577 assert(r->has_live(), "Region %zu should have live", r->index());
578 }
579 } else if (r->is_humongous_continuation()) {
580 // If we hit continuation, the non-live humongous starts should have been trashed already
581 assert(r->humongous_start_region()->has_live(), "Region %zu should have live", r->index());
582 } else if (r->is_regular()) {
583 if (!r->has_live()) {
584 r->make_trash_immediate();
585 }
586 }
587 }
588 };
589
590 void ShenandoahFullGC::distribute_slices(ShenandoahHeapRegionSet** worker_slices) {
591 ShenandoahHeap* heap = ShenandoahHeap::heap();
592
593 uint n_workers = heap->workers()->active_workers();
594 size_t n_regions = heap->num_regions();
595
596 // What we want to accomplish: have the dense prefix of data, while still balancing
597 // out the parallel work.
598 //
599 // Assuming the amount of work is driven by the live data that needs moving, we can slice
600 // the entire heap into equal-live-sized prefix slices, and compact into them. So, each
601 // thread takes all regions in its prefix subset, and then it takes some regions from
602 // the tail.
603 //
604 // Tail region selection becomes interesting.
605 //
606 // First, we want to distribute the regions fairly between the workers, and those regions
607 // might have different amount of live data. So, until we sure no workers need live data,
608 // we need to only take what the worker needs.
609 //
610 // Second, since we slide everything to the left in each slice, the most busy regions
611 // would be the ones on the left. Which means we want to have all workers have their after-tail
612 // regions as close to the left as possible.
613 //
614 // The easiest way to do this is to distribute after-tail regions in round-robin between
615 // workers that still need live data.
616 //
617 // Consider parallel workers A, B, C, then the target slice layout would be:
618 //
619 // AAAAAAAABBBBBBBBCCCCCCCC|ABCABCABCABCABCABCABCABABABABABABABABABABAAAAA
620 //
621 // (.....dense-prefix.....) (.....................tail...................)
622 // [all regions fully live] [left-most regions are fuller that right-most]
623 //
624
625 // Compute how much live data is there. This would approximate the size of dense prefix
626 // we target to create.
627 size_t total_live = 0;
628 for (size_t idx = 0; idx < n_regions; idx++) {
629 ShenandoahHeapRegion *r = heap->get_region(idx);
630 if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
631 total_live += r->get_live_data_words();
632 }
633 }
634
635 // Estimate the size for the dense prefix. Note that we specifically count only the
636 // "full" regions, so there would be some non-full regions in the slice tail.
637 size_t live_per_worker = total_live / n_workers;
638 size_t prefix_regions_per_worker = live_per_worker / ShenandoahHeapRegion::region_size_words();
639 size_t prefix_regions_total = prefix_regions_per_worker * n_workers;
640 prefix_regions_total = MIN2(prefix_regions_total, n_regions);
641 assert(prefix_regions_total <= n_regions, "Sanity");
642
643 // There might be non-candidate regions in the prefix. To compute where the tail actually
644 // ends up being, we need to account those as well.
645 size_t prefix_end = prefix_regions_total;
646 for (size_t idx = 0; idx < prefix_regions_total; idx++) {
647 ShenandoahHeapRegion *r = heap->get_region(idx);
648 if (!ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
649 prefix_end++;
650 }
651 }
652 prefix_end = MIN2(prefix_end, n_regions);
653 assert(prefix_end <= n_regions, "Sanity");
654
655 // Distribute prefix regions per worker: each thread definitely gets its own same-sized
656 // subset of dense prefix.
657 size_t prefix_idx = 0;
658
659 size_t* live = NEW_C_HEAP_ARRAY(size_t, n_workers, mtGC);
660
661 for (size_t wid = 0; wid < n_workers; wid++) {
662 ShenandoahHeapRegionSet* slice = worker_slices[wid];
663
664 live[wid] = 0;
665 size_t regs = 0;
666
667 // Add all prefix regions for this worker
668 while (prefix_idx < prefix_end && regs < prefix_regions_per_worker) {
669 ShenandoahHeapRegion *r = heap->get_region(prefix_idx);
670 if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
671 slice->add_region(r);
672 live[wid] += r->get_live_data_words();
673 regs++;
674 }
675 prefix_idx++;
676 }
677 }
678
679 // Distribute the tail among workers in round-robin fashion.
680 size_t wid = n_workers - 1;
681
682 for (size_t tail_idx = prefix_end; tail_idx < n_regions; tail_idx++) {
683 ShenandoahHeapRegion *r = heap->get_region(tail_idx);
684 if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
685 assert(wid < n_workers, "Sanity");
686
687 size_t live_region = r->get_live_data_words();
688
689 // Select next worker that still needs live data.
690 size_t old_wid = wid;
691 do {
692 wid++;
693 if (wid == n_workers) wid = 0;
694 } while (live[wid] + live_region >= live_per_worker && old_wid != wid);
695
696 if (old_wid == wid) {
697 // Circled back to the same worker? This means liveness data was
698 // miscalculated. Bump the live_per_worker limit so that
699 // everyone gets a piece of the leftover work.
700 live_per_worker += ShenandoahHeapRegion::region_size_words();
701 }
702
703 worker_slices[wid]->add_region(r);
704 live[wid] += live_region;
705 }
706 }
707
708 FREE_C_HEAP_ARRAY(live);
709
710 #ifdef ASSERT
711 ResourceBitMap map(n_regions);
712 for (size_t wid = 0; wid < n_workers; wid++) {
713 ShenandoahHeapRegionSetIterator it(worker_slices[wid]);
714 ShenandoahHeapRegion* r = it.next();
715 while (r != nullptr) {
716 size_t idx = r->index();
717 assert(ShenandoahPrepareForCompactionTask::is_candidate_region(r), "Sanity: %zu", idx);
718 assert(!map.at(idx), "No region distributed twice: %zu", idx);
719 map.at_put(idx, true);
720 r = it.next();
721 }
722 }
723
724 for (size_t rid = 0; rid < n_regions; rid++) {
725 bool is_candidate = ShenandoahPrepareForCompactionTask::is_candidate_region(heap->get_region(rid));
726 bool is_distributed = map.at(rid);
727 assert(is_distributed || !is_candidate, "All candidates are distributed: %zu", rid);
728 }
729 #endif
730 }
731
732 void ShenandoahFullGC::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {
733 GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
734 ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
735
736 ShenandoahHeap* heap = ShenandoahHeap::heap();
737
738 // About to figure out which regions can be compacted, make sure pinning status
739 // had been updated in GC prologue.
740 heap->assert_pinned_region_status();
741
742 {
743 // Trash the immediately collectible regions before computing addresses
744 ShenandoahTrashImmediateGarbageClosure trash_immediate_garbage;
745 ShenandoahExcludeRegionClosure<FREE> cl(&trash_immediate_garbage);
746 heap->heap_region_iterate(&cl);
747
748 // Make sure regions are in good state: committed, active, clean.
749 // This is needed because we are potentially sliding the data through them.
750 ShenandoahEnsureHeapActiveClosure ecl;
751 heap->heap_region_iterate(&ecl);
752 }
753
754 // Compute the new addresses for regular objects
755 {
756 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
757
758 distribute_slices(worker_slices);
759
760 ShenandoahPrepareForCompactionTask task(_preserved_marks, worker_slices);
761 heap->workers()->run_task(&task);
762 }
763
764 // Compute the new addresses for humongous objects
765 {
766 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
767 calculate_target_humongous_objects();
768 }
769 }
770
771 class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {
772 private:
773 ShenandoahMarkingContext* const _ctx;
774
775 template <class T>
776 inline void do_oop_work(T* p) {
777 T o = RawAccess<>::oop_load(p);
778 if (!CompressedOops::is_null(o)) {
779 oop obj = CompressedOops::decode_not_null(o);
780 assert(_ctx->is_marked(obj), "must be marked");
781 if (FullGCForwarding::is_forwarded(obj)) {
782 oop forw = FullGCForwarding::forwardee(obj);
783 RawAccess<IS_NOT_NULL>::oop_store(p, forw);
784 }
785 }
786 }
787
788 public:
789 ShenandoahAdjustPointersClosure() :
790 _ctx(ShenandoahHeap::heap()->global_generation()->complete_marking_context()) {}
791
792 void do_oop(oop* p) { do_oop_work(p); }
793 void do_oop(narrowOop* p) { do_oop_work(p); }
794 void do_method(Method* m) {}
795 void do_nmethod(nmethod* nm) {}
796 };
797
798 class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {
799 private:
800 ShenandoahAdjustPointersClosure _cl;
801
802 public:
803 void do_object(oop p) override {
804 assert(ShenandoahHeap::heap()->global_generation()->is_mark_complete(), "marking must be complete");
805 assert(ShenandoahHeap::heap()->marking_context()->is_marked(p), "must be marked");
806 p->oop_iterate(&_cl);
807 }
808 };
809
810 class ShenandoahAdjustPointersTask : public WorkerTask {
811 private:
812 ShenandoahHeap* const _heap;
813 ShenandoahRegionIterator _regions;
814
815 public:
816 ShenandoahAdjustPointersTask() :
817 WorkerTask("Shenandoah Adjust Pointers"),
818 _heap(ShenandoahHeap::heap()) {
819 }
820
821 void work(uint worker_id) override {
822 ShenandoahParallelWorkerSession worker_session(worker_id);
823 ShenandoahAdjustPointersObjectClosure obj_cl;
824 ShenandoahHeapRegion* r = _regions.next();
825 while (r != nullptr) {
826 if (!r->is_humongous_continuation() && r->has_live()) {
827 _heap->marked_object_iterate(r, &obj_cl);
828 }
829 if (_heap->mode()->is_generational()) {
830 ShenandoahGenerationalFullGC::maybe_coalesce_and_fill_region(r);
831 }
832 r = _regions.next();
833 }
834 }
835 };
836
837 class ShenandoahAdjustRootPointersTask : public WorkerTask {
838 private:
839 ShenandoahRootAdjuster* _rp;
840 PreservedMarksSet* _preserved_marks;
841 public:
842 ShenandoahAdjustRootPointersTask(ShenandoahRootAdjuster* rp, PreservedMarksSet* preserved_marks) :
843 WorkerTask("Shenandoah Adjust Root Pointers"),
844 _rp(rp),
845 _preserved_marks(preserved_marks) {}
846
847 void work(uint worker_id) override {
848 ShenandoahParallelWorkerSession worker_session(worker_id);
849 ShenandoahAdjustPointersClosure cl;
850 _rp->roots_do(worker_id, &cl);
851 _preserved_marks->get(worker_id)->adjust_during_full_gc();
852 }
853 };
854
855 void ShenandoahFullGC::phase3_update_references() {
856 GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);
857 ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);
858
859 ShenandoahHeap* heap = ShenandoahHeap::heap();
860
861 WorkerThreads* workers = heap->workers();
862 uint nworkers = workers->active_workers();
863 {
864 #ifdef COMPILER2
865 DerivedPointerTable::clear();
866 #endif // COMPILER2
867 ShenandoahRootAdjuster rp(nworkers, ShenandoahPhaseTimings::full_gc_adjust_roots);
868 ShenandoahAdjustRootPointersTask task(&rp, _preserved_marks);
869 workers->run_task(&task);
870 #ifdef COMPILER2
871 DerivedPointerTable::update_pointers();
872 #endif // COMPILER2
873 }
874
875 ShenandoahAdjustPointersTask adjust_pointers_task;
876 workers->run_task(&adjust_pointers_task);
877 }
878
879 class ShenandoahCompactObjectsClosure : public ObjectClosure {
880 private:
881 uint const _worker_id;
882
883 public:
884 explicit ShenandoahCompactObjectsClosure(uint worker_id) :
885 _worker_id(worker_id) {}
886
887 void do_object(oop p) override {
888 assert(ShenandoahHeap::heap()->global_generation()->is_mark_complete(), "marking must be finished");
889 assert(ShenandoahHeap::heap()->marking_context()->is_marked(p), "must be marked");
890 size_t size = p->size();
891 if (FullGCForwarding::is_forwarded(p)) {
892 HeapWord* compact_from = cast_from_oop<HeapWord*>(p);
893 HeapWord* compact_to = cast_from_oop<HeapWord*>(FullGCForwarding::forwardee(p));
894 assert(compact_from != compact_to, "Forwarded object should move");
895 Copy::aligned_conjoint_words(compact_from, compact_to, size);
896 oop new_obj = cast_to_oop(compact_to);
897
898 // Restore the mark word before relativizing the stack chunk. The copy's
899 // mark word contains the full GC forwarding encoding, which would cause
900 // is_stackChunk() to read garbage (especially with compact headers).
901 new_obj->init_mark();
902 ContinuationGCSupport::relativize_stack_chunk(new_obj);
903 }
904 }
905 };
906
907 class ShenandoahCompactObjectsTask : public WorkerTask {
908 private:
909 ShenandoahHeap* const _heap;
910 ShenandoahHeapRegionSet** const _worker_slices;
911
912 public:
913 ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :
914 WorkerTask("Shenandoah Compact Objects"),
915 _heap(ShenandoahHeap::heap()),
916 _worker_slices(worker_slices) {
917 }
918
919 void work(uint worker_id) override {
920 ShenandoahParallelWorkerSession worker_session(worker_id);
921 ShenandoahHeapRegionSetIterator slice(_worker_slices[worker_id]);
922
923 ShenandoahCompactObjectsClosure cl(worker_id);
924 ShenandoahHeapRegion* r = slice.next();
925 while (r != nullptr) {
926 assert(!r->is_humongous(), "must not get humongous regions here");
927 if (r->has_live()) {
928 _heap->marked_object_iterate(r, &cl);
929 }
930 r->set_top(r->new_top());
931 r = slice.next();
932 }
933 }
934 };
935
936 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
937 private:
938 ShenandoahHeap* const _heap;
939 bool _is_generational;
940 size_t _young_regions, _young_usage, _young_humongous_waste;
941 size_t _old_regions, _old_usage, _old_humongous_waste;
942
943 public:
944 ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()),
945 _is_generational(_heap->mode()->is_generational()),
946 _young_regions(0),
947 _young_usage(0),
948 _young_humongous_waste(0),
949 _old_regions(0),
950 _old_usage(0),
951 _old_humongous_waste(0)
952 {
953 _heap->free_set()->clear();
954 }
955
956 void heap_region_do(ShenandoahHeapRegion* r) override {
957 assert (!r->is_cset(), "cset regions should have been demoted already");
958
959 // Need to reset the complete-top-at-mark-start pointer here because
960 // the complete marking bitmap is no longer valid. This ensures
961 // size-based iteration in marked_object_iterate().
962 // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
963 // pinned regions.
964 if (!r->is_pinned()) {
965 _heap->marking_context()->reset_top_at_mark_start(r);
966 }
967
968 size_t live = r->used();
969
970 // Make empty regions that have been allocated into regular
971 if (r->is_empty() && live > 0) {
972 if (!_is_generational) {
973 r->make_affiliated_maybe();
974 }
975 // else, generational mode compaction has already established affiliation.
976 r->make_regular_bypass();
977 if (ZapUnusedHeapArea) {
978 SpaceMangler::mangle_region(MemRegion(r->top(), r->end()));
979 }
980 }
981
982 // Reclaim regular regions that became empty
983 if (r->is_regular() && live == 0) {
984 r->make_trash();
985 }
986
987 // Recycle all trash regions
988 if (r->is_trash()) {
989 live = 0;
990 r->try_recycle_under_lock();
991 // No need to adjust_interval_for_recycled_old_region. That will be taken care of during freeset rebuild.
992 } else {
993 if (r->is_old()) {
994 ShenandoahGenerationalFullGC::account_for_region(r, _old_regions, _old_usage, _old_humongous_waste);
995 } else if (r->is_young()) {
996 ShenandoahGenerationalFullGC::account_for_region(r, _young_regions, _young_usage, _young_humongous_waste);
997 }
998 }
999 r->set_live_data(live);
1000 r->reset_alloc_metadata();
1001 }
1002 };
1003
1004 void ShenandoahFullGC::compact_humongous_objects() {
1005 // Compact humongous regions, based on their fwdptr objects.
1006 //
1007 // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
1008 // humongous regions are already compacted, and do not require further moves, which alleviates
1009 // sliding costs. We may consider doing this in parallel in the future.
1010
1011 ShenandoahHeap* heap = ShenandoahHeap::heap();
1012
1013 for (size_t c = heap->num_regions(); c > 0; c--) {
1014 ShenandoahHeapRegion* r = heap->get_region(c - 1);
1015 if (r->is_humongous_start()) {
1016 oop old_obj = cast_to_oop(r->bottom());
1017 if (!FullGCForwarding::is_forwarded(old_obj)) {
1018 // No need to move the object, it stays at the same slot
1019 continue;
1020 }
1021 size_t words_size = old_obj->size();
1022 size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
1023
1024 size_t old_start = r->index();
1025 size_t old_end = old_start + num_regions - 1;
1026 size_t new_start = heap->heap_region_index_containing(FullGCForwarding::forwardee(old_obj));
1027 size_t new_end = new_start + num_regions - 1;
1028 assert(old_start != new_start, "must be real move");
1029 assert(r->is_stw_move_allowed(), "Region %zu should be movable", r->index());
1030
1031 log_debug(gc)("Full GC compaction moves humongous object from region %zu to region %zu", old_start, new_start);
1032 Copy::aligned_conjoint_words(r->bottom(), heap->get_region(new_start)->bottom(), words_size);
1033 ContinuationGCSupport::relativize_stack_chunk(cast_to_oop<HeapWord*>(r->bottom()));
1034
1035 oop new_obj = cast_to_oop(heap->get_region(new_start)->bottom());
1036 new_obj->init_mark();
1037
1038 {
1039 ShenandoahAffiliation original_affiliation = r->affiliation();
1040 for (size_t c = old_start; c <= old_end; c++) {
1041 ShenandoahHeapRegion* r = heap->get_region(c);
1042 // Leave humongous region affiliation unchanged.
1043 r->make_regular_bypass();
1044 r->set_top(r->bottom());
1045 }
1046
1047 for (size_t c = new_start; c <= new_end; c++) {
1048 ShenandoahHeapRegion* r = heap->get_region(c);
1049 if (c == new_start) {
1050 r->make_humongous_start_bypass(original_affiliation);
1051 } else {
1052 r->make_humongous_cont_bypass(original_affiliation);
1053 }
1054
1055 // Trailing region may be non-full, record the remainder there
1056 size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
1057 if ((c == new_end) && (remainder != 0)) {
1058 r->set_top(r->bottom() + remainder);
1059 } else {
1060 r->set_top(r->end());
1061 }
1062
1063 r->reset_alloc_metadata();
1064 }
1065 }
1066 }
1067 }
1068 }
1069
1070 // This is slightly different to ShHeap::reset_next_mark_bitmap:
1071 // we need to remain able to walk pinned regions.
1072 // Since pinned region do not move and don't get compacted, we will get holes with
1073 // unreachable objects in them (which may have pointers to unloaded Klasses and thus
1074 // cannot be iterated over using oop->size()). The only way to safely iterate over those is using
1075 // a valid marking bitmap and valid TAMS pointer. This class only resets marking
1076 // bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.
1077 class ShenandoahMCResetCompleteBitmapTask : public WorkerTask {
1078 private:
1079 ShenandoahRegionIterator _regions;
1080
1081 public:
1082 ShenandoahMCResetCompleteBitmapTask() :
1083 WorkerTask("Shenandoah Reset Bitmap") {
1084 }
1085
1086 void work(uint worker_id) override {
1087 ShenandoahParallelWorkerSession worker_session(worker_id);
1088 ShenandoahHeapRegion* region = _regions.next();
1089 ShenandoahHeap* heap = ShenandoahHeap::heap();
1090 ShenandoahMarkingContext* const ctx = heap->marking_context();
1091 assert(heap->global_generation()->is_mark_complete(), "Marking must be complete");
1092 while (region != nullptr) {
1093 if (heap->is_bitmap_slice_committed(region) && !region->is_pinned() && region->has_live()) {
1094 ctx->clear_bitmap(region);
1095 }
1096 region = _regions.next();
1097 }
1098 }
1099 };
1100
1101 void ShenandoahFullGC::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {
1102 GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);
1103 ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);
1104
1105 ShenandoahHeap* heap = ShenandoahHeap::heap();
1106
1107 // Compact regular objects first
1108 {
1109 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);
1110 ShenandoahCompactObjectsTask compact_task(worker_slices);
1111 heap->workers()->run_task(&compact_task);
1112 }
1113
1114 // Compact humongous objects after regular object moves
1115 {
1116 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
1117 compact_humongous_objects();
1118 }
1119 }
1120
1121 void ShenandoahFullGC::phase5_epilog() {
1122 GCTraceTime(Info, gc, phases) time("Phase 5: Full GC epilog", _gc_timer);
1123 ShenandoahHeap* heap = ShenandoahHeap::heap();
1124
1125 // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
1126 // and must ensure the bitmap is in sync.
1127 {
1128 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);
1129 ShenandoahMCResetCompleteBitmapTask task;
1130 heap->workers()->run_task(&task);
1131 }
1132
1133 // Bring regions in proper states after the collection, and set heap properties.
1134 {
1135 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);
1136 ShenandoahPostCompactClosure post_compact;
1137 heap->heap_region_iterate(&post_compact);
1138 heap->collection_set()->clear();
1139 {
1140 ShenandoahFreeSet* free_set = heap->free_set();
1141 size_t young_trashed_regions, old_trashed_regions, first_old, last_old, num_old;
1142 free_set->prepare_to_rebuild(young_trashed_regions, old_trashed_regions, first_old, last_old, num_old);
1143 // We also do not expand old generation size following Full GC because we have scrambled age populations and
1144 // no longer have objects separated by age into distinct regions.
1145 if (heap->mode()->is_generational()) {
1146 ShenandoahGenerationalFullGC::compute_balances();
1147 }
1148 heap->free_set()->finish_rebuild(young_trashed_regions, old_trashed_regions, num_old);
1149 }
1150
1151 // Set mark incomplete because the marking bitmaps have been reset except pinned regions.
1152 _generation->set_mark_incomplete();
1153
1154 heap->clear_cancelled_gc();
1155 }
1156
1157 _preserved_marks->restore(heap->workers());
1158 _preserved_marks->reclaim();
1159
1160 if (heap->mode()->is_generational()) {
1161 ShenandoahGenerationalFullGC::rebuild_remembered_set(heap);
1162 }
1163 }