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