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