1 /*
   2  * Copyright (c) 2001, 2010, 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_interface/collectedHeap.inline.hpp"
  33 #include "memory/genCollectedHeap.hpp"
  34 #include "memory/genMarkSweep.hpp"
  35 #include "memory/genOopClosures.inline.hpp"
  36 #include "memory/generation.inline.hpp"
  37 #include "memory/modRefBarrierSet.hpp"
  38 #include "memory/referencePolicy.hpp"
  39 #include "memory/space.hpp"
  40 #include "oops/instanceRefKlass.hpp"
  41 #include "oops/oop.inline.hpp"
  42 #include "prims/jvmtiExport.hpp"
  43 #include "runtime/fprofiler.hpp"
  44 #include "runtime/handles.inline.hpp"
  45 #include "runtime/synchronizer.hpp"
  46 #include "runtime/vmThread.hpp"
  47 #include "utilities/copy.hpp"
  48 #include "utilities/events.hpp"
  49 #ifdef TARGET_OS_FAMILY_linux
  50 # include "thread_linux.inline.hpp"
  51 #endif
  52 #ifdef TARGET_OS_FAMILY_solaris
  53 # include "thread_solaris.inline.hpp"
  54 #endif
  55 #ifdef TARGET_OS_FAMILY_windows
  56 # include "thread_windows.inline.hpp"
  57 #endif
  58 
  59 void GenMarkSweep::invoke_at_safepoint(int level, ReferenceProcessor* rp,
  60   bool clear_all_softrefs) {
  61   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
  62 
  63   GenCollectedHeap* gch = GenCollectedHeap::heap();
  64 #ifdef ASSERT
  65   if (gch->collector_policy()->should_clear_all_soft_refs()) {
  66     assert(clear_all_softrefs, "Policy should have been checked earlier");
  67   }
  68 #endif
  69 
  70   // hook up weak ref data so it can be used during Mark-Sweep
  71   assert(ref_processor() == NULL, "no stomping");
  72   assert(rp != NULL, "should be non-NULL");
  73   _ref_processor = rp;
  74   rp->setup_policy(clear_all_softrefs);
  75 
  76   TraceTime t1("Full GC", PrintGC && !PrintGCDetails, true, gclog_or_tty);
  77 
  78   // When collecting the permanent generation methodOops may be moving,
  79   // so we either have to flush all bcp data or convert it into bci.
  80   CodeCache::gc_prologue();
  81   Threads::gc_prologue();
  82 
  83   // Increment the invocation count for the permanent generation, since it is
  84   // implicitly collected whenever we do a full mark sweep collection.
  85   gch->perm_gen()->stat_record()->invocations++;
  86 
  87   // Capture heap size before collection for printing.
  88   size_t gch_prev_used = gch->used();
  89 
  90   // Some of the card table updates below assume that the perm gen is
  91   // also being collected.
  92   assert(level == gch->n_gens() - 1,
  93          "All generations are being collected, ergo perm gen too.");
  94 
  95   // Capture used regions for each generation that will be
  96   // subject to collection, so that card table adjustments can
  97   // be made intelligently (see clear / invalidate further below).
  98   gch->save_used_regions(level, true /* perm */);
  99 
 100   allocate_stacks();
 101 
 102   mark_sweep_phase1(level, clear_all_softrefs);
 103 
 104   mark_sweep_phase2();
 105 
 106   // Don't add any more derived pointers during phase3
 107   COMPILER2_PRESENT(assert(DerivedPointerTable::is_active(), "Sanity"));
 108   COMPILER2_PRESENT(DerivedPointerTable::set_active(false));
 109 
 110   mark_sweep_phase3(level);
 111 
 112   VALIDATE_MARK_SWEEP_ONLY(
 113     if (ValidateMarkSweep) {
 114       guarantee(_root_refs_stack->length() == 0, "should be empty by now");
 115     }
 116   )
 117 
 118   mark_sweep_phase4();
 119 
 120   VALIDATE_MARK_SWEEP_ONLY(
 121     if (ValidateMarkSweep) {
 122       guarantee(_live_oops->length() == _live_oops_moved_to->length(),
 123                 "should be the same size");
 124     }
 125   )
 126 
 127   restore_marks();
 128 
 129   // Set saved marks for allocation profiler (and other things? -- dld)
 130   // (Should this be in general part?)
 131   gch->save_marks();
 132 
 133   deallocate_stacks();
 134 
 135   // If compaction completely evacuated all generations younger than this
 136   // one, then we can clear the card table.  Otherwise, we must invalidate
 137   // it (consider all cards dirty).  In the future, we might consider doing
 138   // compaction within generations only, and doing card-table sliding.
 139   bool all_empty = true;
 140   for (int i = 0; all_empty && i < level; i++) {
 141     Generation* g = gch->get_gen(i);
 142     all_empty = all_empty && gch->get_gen(i)->used() == 0;
 143   }
 144   GenRemSet* rs = gch->rem_set();
 145   // Clear/invalidate below make use of the "prev_used_regions" saved earlier.
 146   if (all_empty) {
 147     // We've evacuated all generations below us.
 148     Generation* g = gch->get_gen(level);
 149     rs->clear_into_younger(g, true /* perm */);
 150   } else {
 151     // Invalidate the cards corresponding to the currently used
 152     // region and clear those corresponding to the evacuated region
 153     // of all generations just collected (i.e. level and younger).
 154     rs->invalidate_or_clear(gch->get_gen(level),
 155                             true /* younger */,
 156                             true /* perm */);
 157   }
 158 
 159   Threads::gc_epilogue();
 160   CodeCache::gc_epilogue();
 161 
 162   if (PrintGC && !PrintGCDetails) {
 163     gch->print_heap_change(gch_prev_used);
 164   }
 165 
 166   // refs processing: clean slate
 167   _ref_processor = NULL;
 168 
 169   // Update heap occupancy information which is used as
 170   // input to soft ref clearing policy at the next gc.
 171   Universe::update_heap_info_at_gc();
 172 
 173   // Update time of last gc for all generations we collected
 174   // (which curently is all the generations in the heap).
 175   gch->update_time_of_last_gc(os::javaTimeMillis());
 176 }
 177 
 178 void GenMarkSweep::allocate_stacks() {
 179   GenCollectedHeap* gch = GenCollectedHeap::heap();
 180   // Scratch request on behalf of oldest generation; will do no
 181   // allocation.
 182   ScratchBlock* scratch = gch->gather_scratch(gch->_gens[gch->_n_gens-1], 0);
 183 
 184   // $$$ To cut a corner, we'll only use the first scratch block, and then
 185   // revert to malloc.
 186   if (scratch != NULL) {
 187     _preserved_count_max =
 188       scratch->num_words * HeapWordSize / sizeof(PreservedMark);
 189   } else {
 190     _preserved_count_max = 0;
 191   }
 192 
 193   _preserved_marks = (PreservedMark*)scratch;
 194   _preserved_count = 0;
 195   _preserved_mark_stack = NULL;
 196   _preserved_oop_stack = NULL;
 197 
 198   _marking_stack       = new (ResourceObj::C_HEAP) GrowableArray<oop>(4000, true);
 199   _objarray_stack      = new (ResourceObj::C_HEAP) GrowableArray<ObjArrayTask>(50, true);
 200 
 201   int size = SystemDictionary::number_of_classes() * 2;
 202   _revisit_klass_stack = new (ResourceObj::C_HEAP) GrowableArray<Klass*>(size, true);
 203   // (#klass/k)^2 for k ~ 10 appears to be a better fit, but this will have to do for
 204   // now until we have had a chance to investigate a more optimal setting.
 205   _revisit_mdo_stack   = new (ResourceObj::C_HEAP) GrowableArray<DataLayout*>(2*size, true);
 206 
 207 #ifdef VALIDATE_MARK_SWEEP
 208   if (ValidateMarkSweep) {
 209     _root_refs_stack    = new (ResourceObj::C_HEAP) GrowableArray<void*>(100, true);
 210     _other_refs_stack   = new (ResourceObj::C_HEAP) GrowableArray<void*>(100, true);
 211     _adjusted_pointers  = new (ResourceObj::C_HEAP) GrowableArray<void*>(100, true);
 212     _live_oops          = new (ResourceObj::C_HEAP) GrowableArray<oop>(100, true);
 213     _live_oops_moved_to = new (ResourceObj::C_HEAP) GrowableArray<oop>(100, true);
 214     _live_oops_size     = new (ResourceObj::C_HEAP) GrowableArray<size_t>(100, true);
 215   }
 216   if (RecordMarkSweepCompaction) {
 217     if (_cur_gc_live_oops == NULL) {
 218       _cur_gc_live_oops           = new(ResourceObj::C_HEAP) GrowableArray<HeapWord*>(100, true);
 219       _cur_gc_live_oops_moved_to  = new(ResourceObj::C_HEAP) GrowableArray<HeapWord*>(100, true);
 220       _cur_gc_live_oops_size      = new(ResourceObj::C_HEAP) GrowableArray<size_t>(100, true);
 221       _last_gc_live_oops          = new(ResourceObj::C_HEAP) GrowableArray<HeapWord*>(100, true);
 222       _last_gc_live_oops_moved_to = new(ResourceObj::C_HEAP) GrowableArray<HeapWord*>(100, true);
 223       _last_gc_live_oops_size     = new(ResourceObj::C_HEAP) GrowableArray<size_t>(100, true);
 224     } else {
 225       _cur_gc_live_oops->clear();
 226       _cur_gc_live_oops_moved_to->clear();
 227       _cur_gc_live_oops_size->clear();
 228     }
 229   }
 230 #endif
 231 }
 232 
 233 
 234 void GenMarkSweep::deallocate_stacks() {
 235   if (!UseG1GC) {
 236     GenCollectedHeap* gch = GenCollectedHeap::heap();
 237     gch->release_scratch();
 238   }
 239 
 240   if (_preserved_oop_stack) {
 241     delete _preserved_mark_stack;
 242     _preserved_mark_stack = NULL;
 243     delete _preserved_oop_stack;
 244     _preserved_oop_stack = NULL;
 245   }
 246 
 247   delete _marking_stack;
 248   delete _objarray_stack;
 249   delete _revisit_klass_stack;
 250   delete _revisit_mdo_stack;
 251 
 252 #ifdef VALIDATE_MARK_SWEEP
 253   if (ValidateMarkSweep) {
 254     delete _root_refs_stack;
 255     delete _other_refs_stack;
 256     delete _adjusted_pointers;
 257     delete _live_oops;
 258     delete _live_oops_size;
 259     delete _live_oops_moved_to;
 260     _live_oops_index = 0;
 261     _live_oops_index_at_perm = 0;
 262   }
 263 #endif
 264 }
 265 
 266 void GenMarkSweep::mark_sweep_phase1(int level,
 267                                   bool clear_all_softrefs) {
 268   // Recursively traverse all live objects and mark them
 269   EventMark m("1 mark object");
 270   TraceTime tm("phase 1", PrintGC && Verbose, true, gclog_or_tty);
 271   trace(" 1");
 272 
 273   VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking(false));
 274 
 275   GenCollectedHeap* gch = GenCollectedHeap::heap();
 276 
 277   // Because follow_root_closure is created statically, cannot
 278   // use OopsInGenClosure constructor which takes a generation,
 279   // as the Universe has not been created when the static constructors
 280   // are run.
 281   follow_root_closure.set_orig_generation(gch->get_gen(level));
 282 
 283   gch->gen_process_strong_roots(level,
 284                                 false, // Younger gens are not roots.
 285                                 true,  // activate StrongRootsScope
 286                                 true,  // Collecting permanent generation.
 287                                 SharedHeap::SO_SystemClasses,
 288                                 &follow_root_closure,
 289                                 true,   // walk code active on stacks
 290                                 &follow_root_closure);
 291 
 292   // Process reference objects found during marking
 293   {
 294     ref_processor()->setup_policy(clear_all_softrefs);
 295     ref_processor()->process_discovered_references(
 296       &is_alive, &keep_alive, &follow_stack_closure, NULL);
 297   }
 298 
 299   // Follow system dictionary roots and unload classes
 300   bool purged_class = SystemDictionary::do_unloading(&is_alive);
 301 
 302   // Follow code cache roots
 303   CodeCache::do_unloading(&is_alive, &keep_alive, purged_class);
 304   follow_stack(); // Flush marking stack
 305 
 306   // Update subklass/sibling/implementor links of live klasses
 307   follow_weak_klass_links();
 308   assert(_marking_stack->is_empty(), "just drained");
 309 
 310   // Visit memoized MDO's and clear any unmarked weak refs
 311   follow_mdo_weak_refs();
 312   assert(_marking_stack->is_empty(), "just drained");
 313 
 314   // Visit symbol and interned string tables and delete unmarked oops
 315   SymbolTable::unlink(&is_alive);
 316   StringTable::unlink(&is_alive);
 317 
 318   assert(_marking_stack->is_empty(), "stack should be empty by now");
 319 }
 320 
 321 
 322 void GenMarkSweep::mark_sweep_phase2() {
 323   // Now all live objects are marked, compute the new object addresses.
 324 
 325   // It is imperative that we traverse perm_gen LAST. If dead space is
 326   // allowed a range of dead object may get overwritten by a dead int
 327   // array. If perm_gen is not traversed last a klassOop may get
 328   // overwritten. This is fine since it is dead, but if the class has dead
 329   // instances we have to skip them, and in order to find their size we
 330   // need the klassOop!
 331   //
 332   // It is not required that we traverse spaces in the same order in
 333   // phase2, phase3 and phase4, but the ValidateMarkSweep live oops
 334   // tracking expects us to do so. See comment under phase4.
 335 
 336   GenCollectedHeap* gch = GenCollectedHeap::heap();
 337   Generation* pg = gch->perm_gen();
 338 
 339   EventMark m("2 compute new addresses");
 340   TraceTime tm("phase 2", PrintGC && Verbose, true, gclog_or_tty);
 341   trace("2");
 342 
 343   VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking(false));
 344 
 345   gch->prepare_for_compaction();
 346 
 347   VALIDATE_MARK_SWEEP_ONLY(_live_oops_index_at_perm = _live_oops_index);
 348   CompactPoint perm_cp(pg, NULL, NULL);
 349   pg->prepare_for_compaction(&perm_cp);
 350 }
 351 
 352 class GenAdjustPointersClosure: public GenCollectedHeap::GenClosure {
 353 public:
 354   void do_generation(Generation* gen) {
 355     gen->adjust_pointers();
 356   }
 357 };
 358 
 359 void GenMarkSweep::mark_sweep_phase3(int level) {
 360   GenCollectedHeap* gch = GenCollectedHeap::heap();
 361   Generation* pg = gch->perm_gen();
 362 
 363   // Adjust the pointers to reflect the new locations
 364   EventMark m("3 adjust pointers");
 365   TraceTime tm("phase 3", PrintGC && Verbose, true, gclog_or_tty);
 366   trace("3");
 367 
 368   VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking(false));
 369 
 370   // Needs to be done before the system dictionary is adjusted.
 371   pg->pre_adjust_pointers();
 372 
 373   // Because the two closures below are created statically, cannot
 374   // use OopsInGenClosure constructor which takes a generation,
 375   // as the Universe has not been created when the static constructors
 376   // are run.
 377   adjust_root_pointer_closure.set_orig_generation(gch->get_gen(level));
 378   adjust_pointer_closure.set_orig_generation(gch->get_gen(level));
 379 
 380   gch->gen_process_strong_roots(level,
 381                                 false, // Younger gens are not roots.
 382                                 true,  // activate StrongRootsScope
 383                                 true,  // Collecting permanent generation.
 384                                 SharedHeap::SO_AllClasses,
 385                                 &adjust_root_pointer_closure,
 386                                 false, // do not walk code
 387                                 &adjust_root_pointer_closure);
 388 
 389   // Now adjust pointers in remaining weak roots.  (All of which should
 390   // have been cleared if they pointed to non-surviving objects.)
 391   CodeBlobToOopClosure adjust_code_pointer_closure(&adjust_pointer_closure,
 392                                                    /*do_marking=*/ false);
 393   gch->gen_process_weak_roots(&adjust_root_pointer_closure,
 394                               &adjust_code_pointer_closure,
 395                               &adjust_pointer_closure);
 396 
 397   adjust_marks();
 398   GenAdjustPointersClosure blk;
 399   gch->generation_iterate(&blk, true);
 400   pg->adjust_pointers();
 401 }
 402 
 403 class GenCompactClosure: public GenCollectedHeap::GenClosure {
 404 public:
 405   void do_generation(Generation* gen) {
 406     gen->compact();
 407   }
 408 };
 409 
 410 void GenMarkSweep::mark_sweep_phase4() {
 411   // All pointers are now adjusted, move objects accordingly
 412 
 413   // It is imperative that we traverse perm_gen first in phase4. All
 414   // classes must be allocated earlier than their instances, and traversing
 415   // perm_gen first makes sure that all klassOops have moved to their new
 416   // location before any instance does a dispatch through it's klass!
 417 
 418   // The ValidateMarkSweep live oops tracking expects us to traverse spaces
 419   // in the same order in phase2, phase3 and phase4. We don't quite do that
 420   // here (perm_gen first rather than last), so we tell the validate code
 421   // to use a higher index (saved from phase2) when verifying perm_gen.
 422   GenCollectedHeap* gch = GenCollectedHeap::heap();
 423   Generation* pg = gch->perm_gen();
 424 
 425   EventMark m("4 compact heap");
 426   TraceTime tm("phase 4", PrintGC && Verbose, true, gclog_or_tty);
 427   trace("4");
 428 
 429   VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking(true));
 430 
 431   pg->compact();
 432 
 433   VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking(false));
 434 
 435   GenCompactClosure blk;
 436   gch->generation_iterate(&blk, true);
 437 
 438   VALIDATE_MARK_SWEEP_ONLY(compaction_complete());
 439 
 440   pg->post_compact(); // Shared spaces verification.
 441 }