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