1 /*
  2  * Copyright (c) 2001, 2023, 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 "precompiled.hpp"
 26 #include "classfile/classLoaderDataGraph.hpp"
 27 #include "classfile/javaClasses.hpp"
 28 #include "classfile/stringTable.hpp"
 29 #include "classfile/symbolTable.hpp"
 30 #include "classfile/systemDictionary.hpp"
 31 #include "classfile/vmSymbols.hpp"
 32 #include "code/codeCache.hpp"
 33 #include "code/icBuffer.hpp"
 34 #include "compiler/oopMap.hpp"
 35 #include "gc/serial/cardTableRS.hpp"
 36 #include "gc/serial/genMarkSweep.hpp"
 37 #include "gc/serial/serialGcRefProcProxyTask.hpp"
 38 #include "gc/shared/collectedHeap.inline.hpp"
 39 #include "gc/shared/gcHeapSummary.hpp"
 40 #include "gc/shared/gcTimer.hpp"
 41 #include "gc/shared/gcTrace.hpp"
 42 #include "gc/shared/gcTraceTime.inline.hpp"
 43 #include "gc/shared/genCollectedHeap.hpp"
 44 #include "gc/shared/generation.hpp"
 45 #include "gc/shared/modRefBarrierSet.hpp"
 46 #include "gc/shared/referencePolicy.hpp"
 47 #include "gc/shared/referenceProcessorPhaseTimes.hpp"
 48 #include "gc/shared/space.hpp"
 49 #include "gc/shared/strongRootsScope.hpp"
 50 #include "gc/shared/weakProcessor.hpp"
 51 #include "memory/universe.hpp"
 52 #include "oops/instanceRefKlass.hpp"
 53 #include "oops/oop.inline.hpp"
 54 #include "prims/jvmtiExport.hpp"
 55 #include "runtime/handles.inline.hpp"
 56 #include "runtime/javaThread.hpp"
 57 #include "runtime/synchronizer.hpp"
 58 #include "runtime/vmThread.hpp"
 59 #include "utilities/copy.hpp"
 60 #include "utilities/events.hpp"
 61 #include "utilities/stack.inline.hpp"
 62 #if INCLUDE_JVMCI
 63 #include "jvmci/jvmci.hpp"
 64 #endif
 65 
 66 void GenMarkSweep::invoke_at_safepoint(bool clear_all_softrefs) {
 67   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
 68 
 69   GenCollectedHeap* gch = GenCollectedHeap::heap();
 70 #ifdef ASSERT
 71   if (gch->soft_ref_policy()->should_clear_all_soft_refs()) {
 72     assert(clear_all_softrefs, "Policy should have been checked earlier");
 73   }
 74 #endif
 75 
 76   gch->trace_heap_before_gc(_gc_tracer);
 77 
 78   // Increment the invocation count
 79   _total_invocations++;
 80 
 81   // Capture used regions for each generation that will be
 82   // subject to collection, so that card table adjustments can
 83   // be made intelligently (see clear / invalidate further below).
 84   gch->save_used_regions();
 85 
 86   allocate_stacks();
 87 
 88   mark_sweep_phase1(clear_all_softrefs);
 89 
 90   mark_sweep_phase2();
 91 
 92   // Don't add any more derived pointers during phase3
 93 #if COMPILER2_OR_JVMCI
 94   assert(DerivedPointerTable::is_active(), "Sanity");
 95   DerivedPointerTable::set_active(false);
 96 #endif
 97 
 98   mark_sweep_phase3();
 99 
100   mark_sweep_phase4();
101 
102   restore_marks();
103 
104   // Set saved marks for allocation profiler (and other things? -- dld)
105   // (Should this be in general part?)
106   gch->save_marks();
107 
108   deallocate_stacks();
109 
110   MarkSweep::_string_dedup_requests->flush();
111 
112   bool is_young_gen_empty = (gch->young_gen()->used() == 0);
113   gch->rem_set()->maintain_old_to_young_invariant(gch->old_gen(), is_young_gen_empty);
114 
115   gch->prune_scavengable_nmethods();
116 
117   // Update heap occupancy information which is used as
118   // input to soft ref clearing policy at the next gc.
119   Universe::heap()->update_capacity_and_used_at_gc();
120 
121   // Signal that we have completed a visit to all live objects.
122   Universe::heap()->record_whole_heap_examined_timestamp();
123 
124   gch->trace_heap_after_gc(_gc_tracer);
125 }
126 
127 void GenMarkSweep::allocate_stacks() {
128   GenCollectedHeap* gch = GenCollectedHeap::heap();
129   // Scratch request on behalf of old generation; will do no allocation.
130   ScratchBlock* scratch = gch->gather_scratch(gch->old_gen(), 0);
131 
132   // $$$ To cut a corner, we'll only use the first scratch block, and then
133   // revert to malloc.
134   if (scratch != nullptr) {
135     _preserved_count_max =
136       scratch->num_words * HeapWordSize / sizeof(PreservedMark);
137   } else {
138     _preserved_count_max = 0;
139   }
140 
141   _preserved_marks = (PreservedMark*)scratch;
142   _preserved_count = 0;
143 }
144 
145 
146 void GenMarkSweep::deallocate_stacks() {
147   GenCollectedHeap* gch = GenCollectedHeap::heap();
148   gch->release_scratch();
149 
150   _preserved_overflow_stack.clear(true);
151   _marking_stack.clear();
152   _objarray_stack.clear(true);
153 }
154 
155 void GenMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
156   // Recursively traverse all live objects and mark them
157   GCTraceTime(Info, gc, phases) tm("Phase 1: Mark live objects", _gc_timer);
158 
159   GenCollectedHeap* gch = GenCollectedHeap::heap();
160 
161   ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_mark);
162 
163   ref_processor()->start_discovery(clear_all_softrefs);
164 
165   {
166     StrongRootsScope srs(0);
167 
168     CLDClosure* weak_cld_closure = ClassUnloading ? nullptr : &follow_cld_closure;
169     MarkingCodeBlobClosure mark_code_closure(&follow_root_closure, !CodeBlobToOopClosure::FixRelocations, true);
170     gch->process_roots(GenCollectedHeap::SO_None,
171                        &follow_root_closure,
172                        &follow_cld_closure,
173                        weak_cld_closure,
174                        &mark_code_closure);
175   }
176 
177   // Process reference objects found during marking
178   {
179     GCTraceTime(Debug, gc, phases) tm_m("Reference Processing", gc_timer());
180 
181     ReferenceProcessorPhaseTimes pt(_gc_timer, ref_processor()->max_num_queues());
182     SerialGCRefProcProxyTask task(is_alive, keep_alive, follow_stack_closure);
183     const ReferenceProcessorStats& stats = ref_processor()->process_discovered_references(task, pt);
184     pt.print_all_references();
185     gc_tracer()->report_gc_reference_stats(stats);
186   }
187 
188   // This is the point where the entire marking should have completed.
189   assert(_marking_stack.is_empty(), "Marking should have completed");
190 
191   {
192     GCTraceTime(Debug, gc, phases) tm_m("Weak Processing", gc_timer());
193     WeakProcessor::weak_oops_do(&is_alive, &do_nothing_cl);
194   }
195 
196   {
197     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", gc_timer());
198     CodeCache::UnloadingScope scope(&is_alive);
199 
200     // Unload classes and purge the SystemDictionary.
201     bool purged_class = SystemDictionary::do_unloading(gc_timer());
202 
203     // Unload nmethods.
204     CodeCache::do_unloading(purged_class);
205 
206     // Prune dead klasses from subklass/sibling/implementor lists.
207     Klass::clean_weak_klass_links(purged_class);
208 
209     // Clean JVMCI metadata handles.
210     JVMCI_ONLY(JVMCI::do_unloading(purged_class));
211   }
212 
213   {
214     GCTraceTime(Debug, gc, phases) tm_m("Report Object Count", gc_timer());
215     gc_tracer()->report_object_count_after_gc(&is_alive, nullptr);
216   }
217 }
218 
219 
220 void GenMarkSweep::mark_sweep_phase2() {
221   // Now all live objects are marked, compute the new object addresses.
222   GCTraceTime(Info, gc, phases) tm("Phase 2: Compute new object addresses", _gc_timer);
223 
224   GenCollectedHeap::heap()->prepare_for_compaction();
225 }
226 
227 class GenAdjustPointersClosure: public GenCollectedHeap::GenClosure {
228 public:
229   void do_generation(Generation* gen) {
230     gen->adjust_pointers();
231   }
232 };
233 
234 void GenMarkSweep::mark_sweep_phase3() {
235   GenCollectedHeap* gch = GenCollectedHeap::heap();
236 
237   // Adjust the pointers to reflect the new locations
238   GCTraceTime(Info, gc, phases) tm("Phase 3: Adjust pointers", gc_timer());
239 
240   ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_adjust);
241 
242   CodeBlobToOopClosure code_closure(&adjust_pointer_closure, CodeBlobToOopClosure::FixRelocations);
243   gch->process_roots(GenCollectedHeap::SO_AllCodeCache,
244                      &adjust_pointer_closure,
245                      &adjust_cld_closure,
246                      &adjust_cld_closure,
247                      &code_closure);
248 
249   gch->gen_process_weak_roots(&adjust_pointer_closure);
250 
251   adjust_marks();
252   GenAdjustPointersClosure blk;
253   gch->generation_iterate(&blk, true);
254 }
255 
256 class GenCompactClosure: public GenCollectedHeap::GenClosure {
257 public:
258   void do_generation(Generation* gen) {
259     gen->compact();
260   }
261 };
262 
263 void GenMarkSweep::mark_sweep_phase4() {
264   // All pointers are now adjusted, move objects accordingly
265   GCTraceTime(Info, gc, phases) tm("Phase 4: Move objects", _gc_timer);
266 
267   GenCompactClosure blk;
268   GenCollectedHeap::heap()->generation_iterate(&blk, true);
269 }