genMarkSweep.cpp 14.8 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
#include "precompiled.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/symbolTable.hpp"
#include "classfile/systemDictionary.hpp"
#include "classfile/vmSymbols.hpp"
#include "code/codeCache.hpp"
#include "code/icBuffer.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "memory/genCollectedHeap.hpp"
#include "memory/genMarkSweep.hpp"
#include "memory/genOopClosures.inline.hpp"
#include "memory/generation.inline.hpp"
#include "memory/modRefBarrierSet.hpp"
#include "memory/referencePolicy.hpp"
#include "memory/space.hpp"
#include "oops/instanceRefKlass.hpp"
#include "oops/oop.inline.hpp"
#include "prims/jvmtiExport.hpp"
#include "runtime/fprofiler.hpp"
#include "runtime/handles.inline.hpp"
#include "runtime/synchronizer.hpp"
#include "runtime/vmThread.hpp"
#include "utilities/copy.hpp"
#include "utilities/events.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "thread_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "thread_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "thread_windows.inline.hpp"
#endif
N
never 已提交
58 59 60
#ifdef TARGET_OS_FAMILY_bsd
# include "thread_bsd.inline.hpp"
#endif
D
duke 已提交
61 62 63 64 65

void GenMarkSweep::invoke_at_safepoint(int level, ReferenceProcessor* rp,
  bool clear_all_softrefs) {
  assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");

66 67 68 69 70 71 72
  GenCollectedHeap* gch = GenCollectedHeap::heap();
#ifdef ASSERT
  if (gch->collector_policy()->should_clear_all_soft_refs()) {
    assert(clear_all_softrefs, "Policy should have been checked earlier");
  }
#endif

D
duke 已提交
73 74 75
  // hook up weak ref data so it can be used during Mark-Sweep
  assert(ref_processor() == NULL, "no stomping");
  assert(rp != NULL, "should be non-NULL");
76
  _ref_processor = rp;
77
  rp->setup_policy(clear_all_softrefs);
D
duke 已提交
78

79
  TraceTime t1(GCCauseString("Full GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, gclog_or_tty);
D
duke 已提交
80

81
  // When collecting the permanent generation Method*s may be moving,
D
duke 已提交
82 83 84 85
  // so we either have to flush all bcp data or convert it into bci.
  CodeCache::gc_prologue();
  Threads::gc_prologue();

86 87
  // Increment the invocation count
  _total_invocations++;
D
duke 已提交
88 89 90 91 92 93 94 95 96 97 98 99

  // Capture heap size before collection for printing.
  size_t gch_prev_used = gch->used();

  // Some of the card table updates below assume that the perm gen is
  // also being collected.
  assert(level == gch->n_gens() - 1,
         "All generations are being collected, ergo perm gen too.");

  // Capture used regions for each generation that will be
  // subject to collection, so that card table adjustments can
  // be made intelligently (see clear / invalidate further below).
100
  gch->save_used_regions(level);
D
duke 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115

  allocate_stacks();

  mark_sweep_phase1(level, clear_all_softrefs);

  mark_sweep_phase2();

  // Don't add any more derived pointers during phase3
  COMPILER2_PRESENT(assert(DerivedPointerTable::is_active(), "Sanity"));
  COMPILER2_PRESENT(DerivedPointerTable::set_active(false));

  mark_sweep_phase3(level);

  VALIDATE_MARK_SWEEP_ONLY(
    if (ValidateMarkSweep) {
116
      guarantee(_root_refs_stack->length() == 0, "should be empty by now");
D
duke 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    }
  )

  mark_sweep_phase4();

  VALIDATE_MARK_SWEEP_ONLY(
    if (ValidateMarkSweep) {
      guarantee(_live_oops->length() == _live_oops_moved_to->length(),
                "should be the same size");
    }
  )

  restore_marks();

  // Set saved marks for allocation profiler (and other things? -- dld)
  // (Should this be in general part?)
  gch->save_marks();

  deallocate_stacks();

  // If compaction completely evacuated all generations younger than this
  // one, then we can clear the card table.  Otherwise, we must invalidate
  // it (consider all cards dirty).  In the future, we might consider doing
  // compaction within generations only, and doing card-table sliding.
  bool all_empty = true;
  for (int i = 0; all_empty && i < level; i++) {
    Generation* g = gch->get_gen(i);
    all_empty = all_empty && gch->get_gen(i)->used() == 0;
  }
  GenRemSet* rs = gch->rem_set();
  // Clear/invalidate below make use of the "prev_used_regions" saved earlier.
  if (all_empty) {
    // We've evacuated all generations below us.
    Generation* g = gch->get_gen(level);
151
    rs->clear_into_younger(g);
D
duke 已提交
152 153 154 155 156
  } else {
    // Invalidate the cards corresponding to the currently used
    // region and clear those corresponding to the evacuated region
    // of all generations just collected (i.e. level and younger).
    rs->invalidate_or_clear(gch->get_gen(level),
157
                            true /* younger */);
D
duke 已提交
158 159 160 161
  }

  Threads::gc_epilogue();
  CodeCache::gc_epilogue();
162
  JvmtiExport::gc_epilogue();
D
duke 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176

  if (PrintGC && !PrintGCDetails) {
    gch->print_heap_change(gch_prev_used);
  }

  // refs processing: clean slate
  _ref_processor = NULL;

  // Update heap occupancy information which is used as
  // input to soft ref clearing policy at the next gc.
  Universe::update_heap_info_at_gc();

  // Update time of last gc for all generations we collected
  // (which curently is all the generations in the heap).
177 178 179 180 181
  // We need to use a monotonically non-deccreasing time in ms
  // or we will see time-warp warnings and os::javaTimeMillis()
  // does not guarantee monotonicity.
  jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
  gch->update_time_of_last_gc(now);
D
duke 已提交
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
}

void GenMarkSweep::allocate_stacks() {
  GenCollectedHeap* gch = GenCollectedHeap::heap();
  // Scratch request on behalf of oldest generation; will do no
  // allocation.
  ScratchBlock* scratch = gch->gather_scratch(gch->_gens[gch->_n_gens-1], 0);

  // $$$ To cut a corner, we'll only use the first scratch block, and then
  // revert to malloc.
  if (scratch != NULL) {
    _preserved_count_max =
      scratch->num_words * HeapWordSize / sizeof(PreservedMark);
  } else {
    _preserved_count_max = 0;
  }

  _preserved_marks = (PreservedMark*)scratch;
  _preserved_count = 0;

#ifdef VALIDATE_MARK_SWEEP
  if (ValidateMarkSweep) {
Z
zgu 已提交
204 205 206 207 208 209
    _root_refs_stack    = new (ResourceObj::C_HEAP, mtGC) GrowableArray<void*>(100, true);
    _other_refs_stack   = new (ResourceObj::C_HEAP, mtGC) GrowableArray<void*>(100, true);
    _adjusted_pointers  = new (ResourceObj::C_HEAP, mtGC) GrowableArray<void*>(100, true);
    _live_oops          = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(100, true);
    _live_oops_moved_to = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(100, true);
    _live_oops_size     = new (ResourceObj::C_HEAP, mtGC) GrowableArray<size_t>(100, true);
D
duke 已提交
210 211 212
  }
  if (RecordMarkSweepCompaction) {
    if (_cur_gc_live_oops == NULL) {
Z
zgu 已提交
213 214 215 216 217 218
      _cur_gc_live_oops           = new(ResourceObj::C_HEAP, mtGC) GrowableArray<HeapWord*>(100, true);
      _cur_gc_live_oops_moved_to  = new(ResourceObj::C_HEAP, mtGC) GrowableArray<HeapWord*>(100, true);
      _cur_gc_live_oops_size      = new(ResourceObj::C_HEAP, mtGC) GrowableArray<size_t>(100, true);
      _last_gc_live_oops          = new(ResourceObj::C_HEAP, mtGC) GrowableArray<HeapWord*>(100, true);
      _last_gc_live_oops_moved_to = new(ResourceObj::C_HEAP, mtGC) GrowableArray<HeapWord*>(100, true);
      _last_gc_live_oops_size     = new(ResourceObj::C_HEAP, mtGC) GrowableArray<size_t>(100, true);
D
duke 已提交
219 220 221 222 223 224 225 226 227 228 229
    } else {
      _cur_gc_live_oops->clear();
      _cur_gc_live_oops_moved_to->clear();
      _cur_gc_live_oops_size->clear();
    }
  }
#endif
}


void GenMarkSweep::deallocate_stacks() {
T
Merge  
tonyp 已提交
230 231 232 233
  if (!UseG1GC) {
    GenCollectedHeap* gch = GenCollectedHeap::heap();
    gch->release_scratch();
  }
234

235 236 237 238
  _preserved_mark_stack.clear(true);
  _preserved_oop_stack.clear(true);
  _marking_stack.clear();
  _objarray_stack.clear(true);
D
duke 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259

#ifdef VALIDATE_MARK_SWEEP
  if (ValidateMarkSweep) {
    delete _root_refs_stack;
    delete _other_refs_stack;
    delete _adjusted_pointers;
    delete _live_oops;
    delete _live_oops_size;
    delete _live_oops_moved_to;
    _live_oops_index = 0;
    _live_oops_index_at_perm = 0;
  }
#endif
}

void GenMarkSweep::mark_sweep_phase1(int level,
                                  bool clear_all_softrefs) {
  // Recursively traverse all live objects and mark them
  TraceTime tm("phase 1", PrintGC && Verbose, true, gclog_or_tty);
  trace(" 1");

260
  VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking());
D
duke 已提交
261 262 263 264 265 266 267 268 269

  GenCollectedHeap* gch = GenCollectedHeap::heap();

  // Because follow_root_closure is created statically, cannot
  // use OopsInGenClosure constructor which takes a generation,
  // as the Universe has not been created when the static constructors
  // are run.
  follow_root_closure.set_orig_generation(gch->get_gen(level));

270 271 272
  // Need new claim bits before marking starts.
  ClassLoaderDataGraph::clear_claimed_marks();

D
duke 已提交
273 274
  gch->gen_process_strong_roots(level,
                                false, // Younger gens are not roots.
275
                                true,  // activate StrongRootsScope
276
                                false, // not scavenging
D
duke 已提交
277
                                SharedHeap::SO_SystemClasses,
278 279
                                &follow_root_closure,
                                true,   // walk code active on stacks
280 281
                                &follow_root_closure,
                                &follow_klass_closure);
D
duke 已提交
282 283 284

  // Process reference objects found during marking
  {
285
    ref_processor()->setup_policy(clear_all_softrefs);
D
duke 已提交
286
    ref_processor()->process_discovered_references(
287
      &is_alive, &keep_alive, &follow_stack_closure, NULL);
D
duke 已提交
288 289 290 291 292 293
  }

  // Follow system dictionary roots and unload classes
  bool purged_class = SystemDictionary::do_unloading(&is_alive);

  // Follow code cache roots
294
  CodeCache::do_unloading(&is_alive, purged_class);
D
duke 已提交
295 296 297
  follow_stack(); // Flush marking stack

  // Update subklass/sibling/implementor links of live klasses
298
  Klass::clean_weak_klass_links(&is_alive);
299
  assert(_marking_stack.is_empty(), "just drained");
Y
ysr 已提交
300

301
  // Visit interned string tables and delete unmarked oops
D
duke 已提交
302
  StringTable::unlink(&is_alive);
303 304
  // Clean up unreferenced symbols in symbol table.
  SymbolTable::unlink();
D
duke 已提交
305

306
  assert(_marking_stack.is_empty(), "stack should be empty by now");
D
duke 已提交
307 308 309 310 311 312 313 314
}


void GenMarkSweep::mark_sweep_phase2() {
  // Now all live objects are marked, compute the new object addresses.

  // It is imperative that we traverse perm_gen LAST. If dead space is
  // allowed a range of dead object may get overwritten by a dead int
315
  // array. If perm_gen is not traversed last a Klass* may get
D
duke 已提交
316 317
  // overwritten. This is fine since it is dead, but if the class has dead
  // instances we have to skip them, and in order to find their size we
318
  // need the Klass*!
D
duke 已提交
319 320 321 322 323 324 325 326 327 328
  //
  // It is not required that we traverse spaces in the same order in
  // phase2, phase3 and phase4, but the ValidateMarkSweep live oops
  // tracking expects us to do so. See comment under phase4.

  GenCollectedHeap* gch = GenCollectedHeap::heap();

  TraceTime tm("phase 2", PrintGC && Verbose, true, gclog_or_tty);
  trace("2");

329
  VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking());
D
duke 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

  gch->prepare_for_compaction();
}

class GenAdjustPointersClosure: public GenCollectedHeap::GenClosure {
public:
  void do_generation(Generation* gen) {
    gen->adjust_pointers();
  }
};

void GenMarkSweep::mark_sweep_phase3(int level) {
  GenCollectedHeap* gch = GenCollectedHeap::heap();

  // Adjust the pointers to reflect the new locations
  TraceTime tm("phase 3", PrintGC && Verbose, true, gclog_or_tty);
  trace("3");

348 349
  // Need new claim bits for the pointer adjustment tracing.
  ClassLoaderDataGraph::clear_claimed_marks();
D
duke 已提交
350

351
  VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking());
D
duke 已提交
352 353 354 355 356 357 358 359 360 361

  // Because the two closures below are created statically, cannot
  // use OopsInGenClosure constructor which takes a generation,
  // as the Universe has not been created when the static constructors
  // are run.
  adjust_root_pointer_closure.set_orig_generation(gch->get_gen(level));
  adjust_pointer_closure.set_orig_generation(gch->get_gen(level));

  gch->gen_process_strong_roots(level,
                                false, // Younger gens are not roots.
362
                                true,  // activate StrongRootsScope
363
                                false, // not scavenging
D
duke 已提交
364 365
                                SharedHeap::SO_AllClasses,
                                &adjust_root_pointer_closure,
366
                                false, // do not walk code
367 368
                                &adjust_root_pointer_closure,
                                &adjust_klass_closure);
D
duke 已提交
369 370 371

  // Now adjust pointers in remaining weak roots.  (All of which should
  // have been cleared if they pointed to non-surviving objects.)
372 373
  CodeBlobToOopClosure adjust_code_pointer_closure(&adjust_pointer_closure,
                                                   /*do_marking=*/ false);
D
duke 已提交
374
  gch->gen_process_weak_roots(&adjust_root_pointer_closure,
375
                              &adjust_code_pointer_closure,
D
duke 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
                              &adjust_pointer_closure);

  adjust_marks();
  GenAdjustPointersClosure blk;
  gch->generation_iterate(&blk, true);
}

class GenCompactClosure: public GenCollectedHeap::GenClosure {
public:
  void do_generation(Generation* gen) {
    gen->compact();
  }
};

void GenMarkSweep::mark_sweep_phase4() {
  // All pointers are now adjusted, move objects accordingly

  // It is imperative that we traverse perm_gen first in phase4. All
  // classes must be allocated earlier than their instances, and traversing
395
  // perm_gen first makes sure that all Klass*s have moved to their new
D
duke 已提交
396 397 398 399 400 401 402 403 404 405 406
  // location before any instance does a dispatch through it's klass!

  // The ValidateMarkSweep live oops tracking expects us to traverse spaces
  // in the same order in phase2, phase3 and phase4. We don't quite do that
  // here (perm_gen first rather than last), so we tell the validate code
  // to use a higher index (saved from phase2) when verifying perm_gen.
  GenCollectedHeap* gch = GenCollectedHeap::heap();

  TraceTime tm("phase 4", PrintGC && Verbose, true, gclog_or_tty);
  trace("4");

407
  VALIDATE_MARK_SWEEP_ONLY(reset_live_oop_tracking());
D
duke 已提交
408 409 410 411 412 413

  GenCompactClosure blk;
  gch->generation_iterate(&blk, true);

  VALIDATE_MARK_SWEEP_ONLY(compaction_complete());
}