1 /*
  2  * Copyright (c) 2001, 2021, 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/genMarkSweep.hpp"
 36 #include "gc/serial/serialGcRefProcProxyTask.hpp"
 37 #include "gc/shared/collectedHeap.inline.hpp"
 38 #include "gc/shared/gcHeapSummary.hpp"
 39 #include "gc/shared/gcTimer.hpp"
 40 #include "gc/shared/gcTrace.hpp"
 41 #include "gc/shared/gcTraceTime.inline.hpp"
 42 #include "gc/shared/genCollectedHeap.hpp"
 43 #include "gc/shared/generation.hpp"
 44 #include "gc/shared/genOopClosures.inline.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/synchronizer.hpp"
 57 #include "runtime/thread.inline.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(ReferenceProcessor* rp, 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   // hook up weak ref data so it can be used during Mark-Sweep
 77   assert(ref_processor() == NULL, "no stomping");
 78   assert(rp != NULL, "should be non-NULL");
 79   set_ref_processor(rp);
 80 
 81   gch->trace_heap_before_gc(_gc_tracer);
 82 
 83   // Increment the invocation count
 84   _total_invocations++;
 85 
 86   // Capture used regions for each generation that will be
 87   // subject to collection, so that card table adjustments can
 88   // be made intelligently (see clear / invalidate further below).
 89   gch->save_used_regions();
 90 
 91   allocate_stacks();
 92 
 93   mark_sweep_phase1(clear_all_softrefs);
 94 
 95   mark_sweep_phase2();
 96 
 97   // Don't add any more derived pointers during phase3
 98 #if COMPILER2_OR_JVMCI
 99   assert(DerivedPointerTable::is_active(), "Sanity");
100   DerivedPointerTable::set_active(false);
101 #endif
102 
103   mark_sweep_phase3();
104 
105   mark_sweep_phase4();
106 
107   restore_marks();
108 
109   // Set saved marks for allocation profiler (and other things? -- dld)
110   // (Should this be in general part?)
111   gch->save_marks();
112 
113   deallocate_stacks();
114 
115   MarkSweep::_string_dedup_requests->flush();
116 
117   // If compaction completely evacuated the young generation then we
118   // can clear the card table.  Otherwise, we must invalidate
119   // it (consider all cards dirty).  In the future, we might consider doing
120   // compaction within generations only, and doing card-table sliding.
121   CardTableRS* rs = gch->rem_set();
122   Generation* old_gen = gch->old_gen();
123 
124   // Clear/invalidate below make use of the "prev_used_regions" saved earlier.
125   if (gch->young_gen()->used() == 0) {
126     // We've evacuated the young generation.
127     rs->clear_into_younger(old_gen);
128   } else {
129     // Invalidate the cards corresponding to the currently used
130     // region and clear those corresponding to the evacuated region.
131     rs->invalidate_or_clear(old_gen);
132   }
133 
134   gch->prune_scavengable_nmethods();
135 
136   // refs processing: clean slate
137   set_ref_processor(NULL);
138 
139   // Update heap occupancy information which is used as
140   // input to soft ref clearing policy at the next gc.
141   Universe::heap()->update_capacity_and_used_at_gc();
142 
143   // Signal that we have completed a visit to all live objects.
144   Universe::heap()->record_whole_heap_examined_timestamp();
145 
146   gch->trace_heap_after_gc(_gc_tracer);
147 }
148 
149 void GenMarkSweep::allocate_stacks() {
150   GenCollectedHeap* gch = GenCollectedHeap::heap();
151   // Scratch request on behalf of old generation; will do no allocation.
152   ScratchBlock* scratch = gch->gather_scratch(gch->old_gen(), 0);
153 
154   // $$$ To cut a corner, we'll only use the first scratch block, and then
155   // revert to malloc.
156   if (scratch != NULL) {
157     _preserved_count_max =
158       scratch->num_words * HeapWordSize / sizeof(PreservedMark);
159   } else {
160     _preserved_count_max = 0;
161   }
162 
163   _preserved_marks = (PreservedMark*)scratch;
164   _preserved_count = 0;
165 }
166 
167 
168 void GenMarkSweep::deallocate_stacks() {
169   GenCollectedHeap* gch = GenCollectedHeap::heap();
170   gch->release_scratch();
171 
172   _preserved_overflow_stack.clear(true);
173   _marking_stack.clear();
174   _objarray_stack.clear(true);
175 }
176 
177 void GenMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
178   // Recursively traverse all live objects and mark them
179   GCTraceTime(Info, gc, phases) tm("Phase 1: Mark live objects", _gc_timer);
180 
181   GenCollectedHeap* gch = GenCollectedHeap::heap();
182 
183   // Need new claim bits before marking starts.
184   ClassLoaderDataGraph::clear_claimed_marks();
185 
186   {
187     StrongRootsScope srs(0);
188 
189     gch->full_process_roots(false, // not the adjust phase
190                             GenCollectedHeap::SO_None,
191                             ClassUnloading, // only strong roots if ClassUnloading
192                                             // is enabled
193                             &follow_root_closure,
194                             &follow_cld_closure);
195   }
196 
197   // Process reference objects found during marking
198   {
199     GCTraceTime(Debug, gc, phases) tm_m("Reference Processing", gc_timer());
200 
201     ReferenceProcessorPhaseTimes pt(_gc_timer, ref_processor()->max_num_queues());
202     SerialGCRefProcProxyTask task(is_alive, keep_alive, follow_stack_closure);
203     const ReferenceProcessorStats& stats = ref_processor()->process_discovered_references(task, pt);
204     pt.print_all_references();
205     gc_tracer()->report_gc_reference_stats(stats);
206   }
207 
208   // This is the point where the entire marking should have completed.
209   assert(_marking_stack.is_empty(), "Marking should have completed");
210 
211   {
212     GCTraceTime(Debug, gc, phases) tm_m("Weak Processing", gc_timer());
213     WeakProcessor::weak_oops_do(&is_alive, &do_nothing_cl);
214   }
215 
216   {
217     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", gc_timer());
218 
219     // Unload classes and purge the SystemDictionary.
220     bool purged_class = SystemDictionary::do_unloading(gc_timer());
221 
222     // Unload nmethods.
223     CodeCache::do_unloading(&is_alive, purged_class);
224 
225     // Prune dead klasses from subklass/sibling/implementor lists.
226     Klass::clean_weak_klass_links(purged_class);
227 
228     // Clean JVMCI metadata handles.
229     JVMCI_ONLY(JVMCI::do_unloading(purged_class));
230   }
231 
232   gc_tracer()->report_object_count_after_gc(&is_alive);
233 }
234 
235 
236 void GenMarkSweep::mark_sweep_phase2() {
237   // Now all live objects are marked, compute the new object addresses.
238 
239   // It is not required that we traverse spaces in the same order in
240   // phase2, phase3 and phase4, but the ValidateMarkSweep live oops
241   // tracking expects us to do so. See comment under phase4.
242 
243   GenCollectedHeap* gch = GenCollectedHeap::heap();
244 
245   GCTraceTime(Info, gc, phases) tm("Phase 2: Compute new object addresses", _gc_timer);
246 
247   gch->prepare_for_compaction();
248 }
249 
250 class GenAdjustPointersClosure: public GenCollectedHeap::GenClosure {
251 public:
252   void do_generation(Generation* gen) {
253     gen->adjust_pointers();
254   }
255 };
256 
257 void GenMarkSweep::mark_sweep_phase3() {
258   GenCollectedHeap* gch = GenCollectedHeap::heap();
259 
260   // Adjust the pointers to reflect the new locations
261   GCTraceTime(Info, gc, phases) tm("Phase 3: Adjust pointers", gc_timer());
262 
263   // Need new claim bits for the pointer adjustment tracing.
264   ClassLoaderDataGraph::clear_claimed_marks();
265 
266   {
267     StrongRootsScope srs(0);
268 
269     gch->full_process_roots(true,  // this is the adjust phase
270                             GenCollectedHeap::SO_AllCodeCache,
271                             false, // all roots
272                             &adjust_pointer_closure,
273                             &adjust_cld_closure);
274   }
275 
276   gch->gen_process_weak_roots(&adjust_pointer_closure);
277 
278   adjust_marks();
279   GenAdjustPointersClosure blk;
280   gch->generation_iterate(&blk, true);
281 }
282 
283 class GenCompactClosure: public GenCollectedHeap::GenClosure {
284 public:
285   void do_generation(Generation* gen) {
286     gen->compact();
287   }
288 };
289 
290 void GenMarkSweep::mark_sweep_phase4() {
291   // All pointers are now adjusted, move objects accordingly
292 
293   // It is imperative that we traverse perm_gen first in phase4. All
294   // classes must be allocated earlier than their instances, and traversing
295   // perm_gen first makes sure that all Klass*s have moved to their new
296   // location before any instance does a dispatch through it's klass!
297 
298   // The ValidateMarkSweep live oops tracking expects us to traverse spaces
299   // in the same order in phase2, phase3 and phase4. We don't quite do that
300   // here (perm_gen first rather than last), so we tell the validate code
301   // to use a higher index (saved from phase2) when verifying perm_gen.
302   GenCollectedHeap* gch = GenCollectedHeap::heap();
303 
304   GCTraceTime(Info, gc, phases) tm("Phase 4: Move objects", _gc_timer);
305 
306   GenCompactClosure blk;
307   gch->generation_iterate(&blk, true);
308 }