1 /*
2 * Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25 #include "classfile/classLoaderDataGraph.hpp"
26 #include "cppstdlib/new.hpp"
27 #include "gc/g1/g1CollectedHeap.hpp"
28 #include "gc/g1/g1FullCollector.inline.hpp"
29 #include "gc/g1/g1FullGCAdjustTask.hpp"
30 #include "gc/g1/g1FullGCCompactTask.hpp"
31 #include "gc/g1/g1FullGCMarker.inline.hpp"
32 #include "gc/g1/g1FullGCMarkTask.hpp"
33 #include "gc/g1/g1FullGCPrepareTask.inline.hpp"
34 #include "gc/g1/g1FullGCResetMetadataTask.hpp"
35 #include "gc/g1/g1FullGCScope.hpp"
36 #include "gc/g1/g1OopClosures.hpp"
37 #include "gc/g1/g1Policy.hpp"
38 #include "gc/g1/g1RegionMarkStatsCache.inline.hpp"
39 #include "gc/shared/classUnloadingContext.hpp"
40 #include "gc/shared/gcTraceTime.inline.hpp"
41 #include "gc/shared/preservedMarks.inline.hpp"
42 #include "gc/shared/referenceProcessor.hpp"
43 #include "gc/shared/verifyOption.hpp"
44 #include "gc/shared/weakProcessor.inline.hpp"
45 #include "gc/shared/workerPolicy.hpp"
46 #include "logging/log.hpp"
47 #include "runtime/handles.inline.hpp"
48 #include "utilities/debug.hpp"
49
50 static void clear_and_activate_derived_pointers() {
51 #if COMPILER2_OR_JVMCI
52 DerivedPointerTable::clear();
53 #endif
54 }
55
56 static void deactivate_derived_pointers() {
57 #if COMPILER2_OR_JVMCI
58 DerivedPointerTable::set_active(false);
59 #endif
60 }
61
62 static void update_derived_pointers() {
63 #if COMPILER2_OR_JVMCI
64 DerivedPointerTable::update_pointers();
65 #endif
66 }
67
68 G1CMBitMap* G1FullCollector::mark_bitmap() {
69 return _heap->concurrent_mark()->mark_bitmap();
70 }
71
72 ReferenceProcessor* G1FullCollector::reference_processor() {
73 return _heap->ref_processor_stw();
74 }
75
76 uint G1FullCollector::calc_active_workers() {
77 G1CollectedHeap* heap = G1CollectedHeap::heap();
78 uint max_worker_count = heap->workers()->max_workers();
79 // Only calculate number of workers if UseDynamicNumberOfGCThreads
80 // is enabled, otherwise use max.
81 if (!UseDynamicNumberOfGCThreads) {
82 return max_worker_count;
83 }
84
85 // Consider G1HeapWastePercent to decide max number of workers. Each worker
86 // will in average cause half a region waste.
87 uint max_wasted_regions_allowed = ((heap->num_committed_regions() * G1HeapWastePercent) / 100);
88 uint waste_worker_count = MAX2((max_wasted_regions_allowed * 2) , 1u);
89 uint heap_waste_worker_limit = MIN2(waste_worker_count, max_worker_count);
90
91 // Also consider HeapSizePerGCThread by calling WorkerPolicy to calculate
92 // the number of workers.
93 uint current_active_workers = heap->workers()->active_workers();
94 uint active_worker_limit = WorkerPolicy::calc_active_workers(max_worker_count, current_active_workers, 0);
95
96 // Finally consider the amount of used regions.
97 uint used_worker_limit = heap->num_used_regions();
98 assert(used_worker_limit > 0, "Should never have zero used regions.");
99
100 // Update active workers to the lower of the limits.
101 uint worker_count = MIN3(heap_waste_worker_limit, active_worker_limit, used_worker_limit);
102 log_debug(gc, task)("Requesting %u active workers for full compaction (waste limited workers: %u, "
103 "adaptive workers: %u, used limited workers: %u)",
104 worker_count, heap_waste_worker_limit, active_worker_limit, used_worker_limit);
105 worker_count = heap->workers()->set_active_workers(worker_count);
106 log_info(gc, task)("Using %u workers of %u for full compaction", worker_count, max_worker_count);
107
108 return worker_count;
109 }
110
111 G1FullCollector::G1FullCollector(G1CollectedHeap* heap,
112 bool clear_soft_refs,
113 bool do_maximal_compaction,
114 GCTracer* tracer) :
115 _heap(heap),
116 _scope(heap->monitoring_support(), clear_soft_refs, do_maximal_compaction, tracer),
117 _num_workers(calc_active_workers()),
118 _has_compaction_targets(false),
119 _has_humongous(false),
120 _marking_task_queues(_num_workers),
121 _partial_array_state_manager(nullptr),
122 _preserved_marks_set(true),
123 _serial_compaction_point(this, nullptr),
124 _humongous_compaction_point(this, nullptr),
125 _is_alive(this, heap->concurrent_mark()->mark_bitmap()),
126 _is_alive_mutator(heap->ref_processor_stw(), &_is_alive),
127 _humongous_compaction_regions(8),
128 _always_subject_to_discovery(),
129 _is_subject_mutator(heap->ref_processor_stw(), &_always_subject_to_discovery),
130 _region_attr_table() {
131 assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
132
133 _preserved_marks_set.init(_num_workers);
134 _markers = NEW_C_HEAP_ARRAY(G1FullGCMarker*, _num_workers, mtGC);
135 _compaction_points = NEW_C_HEAP_ARRAY(G1FullGCCompactionPoint*, _num_workers, mtGC);
136
137 _live_stats = NEW_C_HEAP_ARRAY(G1RegionMarkStats, _heap->max_num_regions(), mtGC);
138 for (uint j = 0; j < heap->max_num_regions(); j++) {
139 _live_stats[j].clear();
140 }
141
142 _compaction_tops = NEW_C_HEAP_ARRAY(Atomic<HeapWord*>, _heap->max_num_regions(), mtGC);
143 ::new (_compaction_tops) Atomic<HeapWord*>[heap->max_num_regions()]{};
144
145 _partial_array_state_manager = new PartialArrayStateManager(_num_workers);
146
147 for (uint i = 0; i < _num_workers; i++) {
148 _markers[i] = new G1FullGCMarker(this, i, _live_stats);
149 _compaction_points[i] = new G1FullGCCompactionPoint(this, _preserved_marks_set.get(i));
150 _marking_task_queues.register_queue(i, marker(i)->task_queue());
151 }
152
153 _serial_compaction_point.set_preserved_stack(_preserved_marks_set.get(0));
154 _humongous_compaction_point.set_preserved_stack(_preserved_marks_set.get(0));
155 _region_attr_table.initialize(heap->reserved(), G1HeapRegion::GrainBytes);
156 }
157
158 PartialArrayStateManager* G1FullCollector::partial_array_state_manager() const {
159 return _partial_array_state_manager;
160 }
161
162 G1FullCollector::~G1FullCollector() {
163 for (uint i = 0; i < _num_workers; i++) {
164 delete _markers[i];
165 delete _compaction_points[i];
166 }
167
168 delete _partial_array_state_manager;
169
170 FREE_C_HEAP_ARRAY(G1FullGCMarker*, _markers);
171 FREE_C_HEAP_ARRAY(G1FullGCCompactionPoint*, _compaction_points);
172 FREE_C_HEAP_ARRAY(Atomic<HeapWord*>, _compaction_tops);
173 FREE_C_HEAP_ARRAY(G1RegionMarkStats, _live_stats);
174 }
175
176 class PrepareRegionsClosure : public G1HeapRegionClosure {
177 G1FullCollector* _collector;
178
179 public:
180 PrepareRegionsClosure(G1FullCollector* collector) : _collector(collector) { }
181
182 bool do_heap_region(G1HeapRegion* hr) {
183 hr->prepare_for_full_gc();
184 G1CollectedHeap::heap()->prepare_region_for_full_compaction(hr);
185 _collector->before_marking_update_attribute_table(hr);
186 return false;
187 }
188 };
189
190 void G1FullCollector::prepare_collection() {
191 _heap->policy()->record_full_collection_start();
192
193 // Verification needs the bitmap, so we should clear the bitmap only later.
194 bool in_concurrent_cycle = _heap->abort_concurrent_cycle();
195 _heap->verify_before_full_collection();
196 if (in_concurrent_cycle) {
197 GCTraceTime(Debug, gc) debug("Clear Bitmap");
198 _heap->concurrent_mark()->clear_bitmap(_heap->workers());
199 }
200
201 _heap->gc_prologue(true);
202 _heap->retire_tlabs();
203 _heap->flush_region_pin_cache();
204 _heap->prepare_heap_for_full_collection();
205
206 PrepareRegionsClosure cl(this);
207 _heap->heap_region_iterate(&cl);
208
209 reference_processor()->start_discovery(scope()->should_clear_soft_refs());
210
211 // Clear and activate derived pointer collection.
212 clear_and_activate_derived_pointers();
213 }
214
215 void G1FullCollector::collect() {
216 G1CollectedHeap::start_codecache_marking_cycle_if_inactive(false /* concurrent_mark_start */);
217
218 phase1_mark_live_objects();
219 verify_after_marking();
220
221 // Don't add any more derived pointers during later phases
222 deactivate_derived_pointers();
223
224 FullGCForwarding::begin();
225
226 phase2_prepare_compaction();
227
228 if (has_compaction_targets()) {
229 phase3_adjust_pointers();
230
231 phase4_do_compaction();
232 } else {
233 // All regions have a high live ratio thus will not be compacted.
234 // The live ratio is only considered if do_maximal_compaction is false.
235 log_info(gc, phases) ("No Regions selected for compaction. Skipping Phase 3: Adjust pointers and Phase 4: Compact heap");
236 }
237
238 FullGCForwarding::end();
239
240 phase5_reset_metadata();
241 }
242
243 void G1FullCollector::complete_collection(size_t allocation_word_size) {
244 // Restore all marks.
245 restore_marks();
246
247 // When the pointers have been adjusted and moved, we can
248 // update the derived pointer table.
249 update_derived_pointers();
250
251 // Need completely cleared claim bits for the next concurrent marking or full gc.
252 ClassLoaderDataGraph::clear_claimed_marks();
253
254 // Prepare the bitmap for the next (potentially concurrent) marking.
255 _heap->concurrent_mark()->clear_bitmap(_heap->workers());
256
257 _heap->prepare_for_mutator_after_full_collection(allocation_word_size);
258
259 _heap->resize_all_tlabs();
260
261 _heap->policy()->record_full_collection_end(allocation_word_size);
262 _heap->gc_epilogue(true);
263
264 _heap->verify_after_full_collection();
265
266 _heap->print_heap_after_full_collection();
267 }
268
269 void G1FullCollector::before_marking_update_attribute_table(G1HeapRegion* hr) {
270 if (hr->is_free()) {
271 _region_attr_table.set_free(hr->hrm_index());
272 } else if (hr->is_humongous() || hr->has_pinned_objects()) {
273 // Humongous objects or pinned regions will never be moved in the "main"
274 // compaction phase, but non-pinned regions might afterwards in a special phase.
275 _region_attr_table.set_skip_compacting(hr->hrm_index());
276 } else {
277 // Everything else should be compacted.
278 _region_attr_table.set_compacting(hr->hrm_index());
279 }
280 }
281
282 class G1FullGCRefProcProxyTask : public RefProcProxyTask {
283 G1FullCollector& _collector;
284
285 // G1 Full GC specific closure for handling discovered fields. Do NOT need any
286 // barriers as Full GC discards all this information anyway.
287 class G1FullGCDiscoveredFieldClosure : public EnqueueDiscoveredFieldClosure {
288 G1CollectedHeap* _g1h;
289
290 public:
291 G1FullGCDiscoveredFieldClosure() : _g1h(G1CollectedHeap::heap()) { }
292
293 void enqueue(HeapWord* discovered_field_addr, oop value) override {
294 assert(_g1h->is_in(discovered_field_addr), PTR_FORMAT " is not in heap ", p2i(discovered_field_addr));
295 // Store the value and done.
296 RawAccess<>::oop_store(discovered_field_addr, value);
297 }
298 };
299
300 public:
301 G1FullGCRefProcProxyTask(G1FullCollector &collector, uint max_workers)
302 : RefProcProxyTask("G1FullGCRefProcProxyTask", max_workers),
303 _collector(collector) {}
304
305 void work(uint worker_id) override {
306 assert(worker_id < _max_workers, "sanity");
307 G1IsAliveClosure is_alive(&_collector);
308 uint index = (_tm == RefProcThreadModel::Single) ? 0 : worker_id;
309 G1FullKeepAliveClosure keep_alive(_collector.marker(index));
310 G1FullGCDiscoveredFieldClosure enqueue;
311 G1MarkStackClosure* complete_marking = _collector.marker(index)->stack_closure();
312 _rp_task->rp_work(worker_id, &is_alive, &keep_alive, &enqueue, complete_marking);
313 }
314 };
315
316 void G1FullCollector::phase1_mark_live_objects() {
317 // Recursively traverse all live objects and mark them.
318 GCTraceTime(Info, gc, phases) info("Phase 1: Mark live objects", scope()->timer());
319
320 {
321 // Do the actual marking.
322 G1FullGCMarkTask marking_task(this);
323 run_task(&marking_task);
324 }
325
326 {
327 GCTraceTime(Debug, gc, phases) debug("Phase 1: Reference Processing", scope()->timer());
328 // Process reference objects found during marking.
329 ReferenceProcessorPhaseTimes pt(scope()->timer(), reference_processor()->max_num_queues());
330 G1FullGCRefProcProxyTask task(*this, reference_processor()->max_num_queues());
331 const ReferenceProcessorStats& stats = reference_processor()->process_discovered_references(task, _heap->workers(), pt);
332 scope()->tracer()->report_gc_reference_stats(stats);
333 pt.print_all_references();
334 assert(marker(0)->task_queue()->is_empty(), "Should be no oops on the stack");
335 }
336
337 {
338 GCTraceTime(Debug, gc, phases) debug("Phase 1: Flush Mark Stats Cache", scope()->timer());
339 for (uint i = 0; i < workers(); i++) {
340 marker(i)->flush_mark_stats_cache();
341 }
342 }
343
344 // Weak oops cleanup.
345 {
346 GCTraceTime(Debug, gc, phases) debug("Phase 1: Weak Processing", scope()->timer());
347 WeakProcessor::weak_oops_do(_heap->workers(), &_is_alive, &do_nothing_cl, 1);
348 }
349
350 // Class unloading and cleanup.
351 if (ClassUnloading) {
352 _heap->unload_classes_and_code("Phase 1: Class Unloading and Cleanup", &_is_alive, scope()->timer());
353 }
354
355 {
356 GCTraceTime(Debug, gc, phases) debug("Report Object Count", scope()->timer());
357 scope()->tracer()->report_object_count_after_gc(&_is_alive, _heap->workers());
358 }
359 #if TASKQUEUE_STATS
360 marking_task_queues()->print_and_reset_taskqueue_stats("Full GC");
361
362 auto get_stats = [&](uint i) {
363 return marker(i)->partial_array_splitter().stats();
364 };
365 PartialArrayTaskStats::log_set(_num_workers, get_stats,
366 "Full GC Partial Array");
367 #endif
368 }
369
370 void G1FullCollector::phase2_prepare_compaction() {
371 GCTraceTime(Info, gc, phases) info("Phase 2: Prepare compaction", scope()->timer());
372
373 phase2a_determine_worklists();
374
375 if (!has_compaction_targets()) {
376 return;
377 }
378
379 bool has_free_compaction_targets = phase2b_forward_oops();
380
381 // Try to avoid OOM immediately after Full GC in case there are no free regions
382 // left after determining the result locations (i.e. this phase). Prepare to
383 // maximally compact the tail regions of the compaction queues serially.
384 if (scope()->do_maximal_compaction() || !has_free_compaction_targets) {
385 phase2c_prepare_serial_compaction();
386
387 if (scope()->do_maximal_compaction() &&
388 has_humongous() &&
389 serial_compaction_point()->has_regions()) {
390 phase2d_prepare_humongous_compaction();
391 }
392 }
393 }
394
395 void G1FullCollector::phase2a_determine_worklists() {
396 GCTraceTime(Debug, gc, phases) debug("Phase 2: Determine work lists", scope()->timer());
397
398 G1DetermineCompactionQueueClosure cl(this);
399 _heap->heap_region_iterate(&cl);
400 }
401
402 bool G1FullCollector::phase2b_forward_oops() {
403 GCTraceTime(Debug, gc, phases) debug("Phase 2: Prepare parallel compaction", scope()->timer());
404
405 G1FullGCPrepareTask task(this);
406 run_task(&task);
407
408 return task.has_free_compaction_targets();
409 }
410
411 uint G1FullCollector::truncate_parallel_cps() {
412 uint lowest_current = UINT_MAX;
413 for (uint i = 0; i < workers(); i++) {
414 G1FullGCCompactionPoint* cp = compaction_point(i);
415 if (cp->has_regions()) {
416 lowest_current = MIN2(lowest_current, cp->current_region()->hrm_index());
417 }
418 }
419
420 for (uint i = 0; i < workers(); i++) {
421 G1FullGCCompactionPoint* cp = compaction_point(i);
422 if (cp->has_regions()) {
423 cp->remove_at_or_above(lowest_current);
424 }
425 }
426 return lowest_current;
427 }
428
429 void G1FullCollector::phase2c_prepare_serial_compaction() {
430 GCTraceTime(Debug, gc, phases) debug("Phase 2: Prepare serial compaction", scope()->timer());
431 // At this point, we know that after parallel compaction there will be regions that
432 // are partially compacted into. Thus, the last compaction region of all
433 // compaction queues still have space in them. We try to re-compact these regions
434 // in serial to avoid a premature OOM when the mutator wants to allocate the first
435 // eden region after gc.
436
437 // For maximum compaction, we need to re-prepare all objects above the lowest
438 // region among the current regions for all thread compaction points. It may
439 // happen that due to the uneven distribution of objects to parallel threads, holes
440 // have been created as threads compact to different target regions between the
441 // lowest and the highest region in the tails of the compaction points.
442
443 uint start_serial = truncate_parallel_cps();
444 assert(start_serial < _heap->max_num_regions(), "Called on empty parallel compaction queues");
445
446 G1FullGCCompactionPoint* serial_cp = serial_compaction_point();
447 assert(!serial_cp->is_initialized(), "sanity!");
448
449 G1HeapRegion* start_hr = _heap->region_at(start_serial);
450 serial_cp->add(start_hr);
451 serial_cp->initialize(start_hr);
452
453 HeapWord* dense_prefix_top = compaction_top(start_hr);
454 G1SerialRePrepareClosure re_prepare(serial_cp, dense_prefix_top);
455
456 for (uint i = start_serial + 1; i < _heap->max_num_regions(); i++) {
457 if (is_compaction_target(i)) {
458 G1HeapRegion* current = _heap->region_at(i);
459 set_compaction_top(current, current->bottom());
460 serial_cp->add(current);
461 current->apply_to_marked_objects(mark_bitmap(), &re_prepare);
462 }
463 }
464 serial_cp->update();
465 }
466
467 void G1FullCollector::phase2d_prepare_humongous_compaction() {
468 GCTraceTime(Debug, gc, phases) debug("Phase 2: Prepare humongous compaction", scope()->timer());
469 G1FullGCCompactionPoint* serial_cp = serial_compaction_point();
470 assert(serial_cp->has_regions(), "Sanity!" );
471
472 uint last_serial_target = serial_cp->current_region()->hrm_index();
473 uint region_index = last_serial_target + 1;
474 uint max_num_regions = _heap->max_num_regions();
475
476 G1FullGCCompactionPoint* humongous_cp = humongous_compaction_point();
477
478 while (region_index < max_num_regions) {
479 G1HeapRegion* hr = _heap->region_at_or_null(region_index);
480
481 if (hr == nullptr) {
482 region_index++;
483 continue;
484 } else if (hr->is_starts_humongous()) {
485 size_t obj_size = cast_to_oop(hr->bottom())->size();
486 uint num_regions = (uint)G1CollectedHeap::humongous_obj_size_in_regions(obj_size);
487 // Even during last-ditch compaction we should not move pinned humongous objects.
488 if (!hr->has_pinned_objects()) {
489 humongous_cp->forward_humongous(hr);
490 }
491 region_index += num_regions; // Advance over all humongous regions.
492 continue;
493 } else if (is_compaction_target(region_index)) {
494 assert(!hr->has_pinned_objects(), "pinned regions should not be compaction targets");
495 // Add the region to the humongous compaction point.
496 humongous_cp->add(hr);
497 }
498 region_index++;
499 }
500 }
501
502 void G1FullCollector::phase3_adjust_pointers() {
503 // Adjust the pointers to reflect the new locations
504 GCTraceTime(Info, gc, phases) info("Phase 3: Adjust pointers", scope()->timer());
505
506 G1FullGCAdjustTask task(this);
507 run_task(&task);
508 }
509
510 void G1FullCollector::phase4_do_compaction() {
511 // Compact the heap using the compaction queues created in phase 2.
512 GCTraceTime(Info, gc, phases) info("Phase 4: Compact heap", scope()->timer());
513 G1FullGCCompactTask task(this);
514 run_task(&task);
515
516 // Serial compact to avoid OOM when very few free regions.
517 if (serial_compaction_point()->has_regions()) {
518 task.serial_compaction();
519 }
520
521 if (!_humongous_compaction_regions.is_empty()) {
522 assert(scope()->do_maximal_compaction(), "Only compact humongous during maximal compaction");
523 task.humongous_compaction();
524 }
525 }
526
527 void G1FullCollector::phase5_reset_metadata() {
528 // Clear region metadata that is invalid after GC for all regions.
529 GCTraceTime(Info, gc, phases) info("Phase 5: Reset Metadata", scope()->timer());
530 G1FullGCResetMetadataTask task(this);
531 run_task(&task);
532 }
533
534 void G1FullCollector::restore_marks() {
535 _preserved_marks_set.restore(_heap->workers());
536 _preserved_marks_set.reclaim();
537 }
538
539 void G1FullCollector::run_task(WorkerTask* task) {
540 _heap->workers()->run_task(task, _num_workers);
541 }
542
543 void G1FullCollector::verify_after_marking() {
544 if (!VerifyDuringGC || !_heap->verifier()->should_verify(G1HeapVerifier::G1VerifyFull)) {
545 // Only do verification if VerifyDuringGC and G1VerifyFull is set.
546 return;
547 }
548
549 #if COMPILER2_OR_JVMCI
550 DerivedPointerTableDeactivate dpt_deact;
551 #endif
552 _heap->prepare_for_verify();
553 // Note: we can verify only the heap here. When an object is
554 // marked, the previous value of the mark word (including
555 // identity hash values, ages, etc) is preserved, and the mark
556 // word is set to markWord::marked_value - effectively removing
557 // any hash values from the mark word. These hash values are
558 // used when verifying the dictionaries and so removing them
559 // from the mark word can make verification of the dictionaries
560 // fail. At the end of the GC, the original mark word values
561 // (including hash values) are restored to the appropriate
562 // objects.
563 GCTraceTime(Info, gc, verify) tm("Verifying During GC (full)");
564 _heap->verify(VerifyOption::G1UseFullMarking);
565 }