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