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/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "gc_implementation/parallelScavenge/generationSizer.hpp"
  30 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
  31 #include "gc_implementation/parallelScavenge/psAdaptiveSizePolicy.hpp"
  32 #include "gc_implementation/parallelScavenge/psMarkSweep.hpp"
  33 #include "gc_implementation/parallelScavenge/psMarkSweepDecorator.hpp"
  34 #include "gc_implementation/parallelScavenge/psOldGen.hpp"
  35 #include "gc_implementation/parallelScavenge/psPermGen.hpp"
  36 #include "gc_implementation/parallelScavenge/psScavenge.hpp"
  37 #include "gc_implementation/parallelScavenge/psYoungGen.hpp"
  38 #include "gc_implementation/shared/isGCActiveMark.hpp"
  39 #include "gc_implementation/shared/spaceDecorator.hpp"
  40 #include "gc_interface/gcCause.hpp"
  41 #include "memory/gcLocker.inline.hpp"
  42 #include "memory/referencePolicy.hpp"
  43 #include "memory/referenceProcessor.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "runtime/biasedLocking.hpp"
  46 #include "runtime/fprofiler.hpp"
  47 #include "runtime/safepoint.hpp"
  48 #include "runtime/vmThread.hpp"
  49 #include "services/management.hpp"
  50 #include "services/memoryService.hpp"
  51 #include "utilities/events.hpp"
  52 
  53 elapsedTimer        PSMarkSweep::_accumulated_time;
  54 unsigned int        PSMarkSweep::_total_invocations = 0;
  55 jlong               PSMarkSweep::_time_of_last_gc   = 0;
  56 CollectorCounters*  PSMarkSweep::_counters = NULL;
  57 
  58 void PSMarkSweep::initialize() {
  59   MemRegion mr = Universe::heap()->reserved_region();
  60   _ref_processor = new ReferenceProcessor(mr,
  61                                           true,    // atomic_discovery
  62                                           false);  // mt_discovery
  63   _counters = new CollectorCounters("PSMarkSweep", 1);
  64 }
  65 
  66 // This method contains all heap specific policy for invoking mark sweep.
  67 // PSMarkSweep::invoke_no_policy() will only attempt to mark-sweep-compact
  68 // the heap. It will do nothing further. If we need to bail out for policy
  69 // reasons, scavenge before full gc, or any other specialized behavior, it
  70 // needs to be added here.
  71 //
  72 // Note that this method should only be called from the vm_thread while
  73 // at a safepoint!
  74 //
  75 // Note that the all_soft_refs_clear flag in the collector policy
  76 // may be true because this method can be called without intervening
  77 // activity.  For example when the heap space is tight and full measure
  78 // are being taken to free space.
  79 
  80 void PSMarkSweep::invoke(bool maximum_heap_compaction) {
  81   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
  82   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
  83   assert(!Universe::heap()->is_gc_active(), "not reentrant");
  84 
  85   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
  86   GCCause::Cause gc_cause = heap->gc_cause();
  87   PSAdaptiveSizePolicy* policy = heap->size_policy();
  88   IsGCActiveMark mark;
  89 
  90   if (ScavengeBeforeFullGC) {
  91     PSScavenge::invoke_no_policy();
  92   }
  93 
  94   const bool clear_all_soft_refs =
  95     heap->collector_policy()->should_clear_all_soft_refs();
  96 
  97   int count = (maximum_heap_compaction)?1:MarkSweepAlwaysCompactCount;
  98   IntFlagSetting flag_setting(MarkSweepAlwaysCompactCount, count);
  99   PSMarkSweep::invoke_no_policy(clear_all_soft_refs || maximum_heap_compaction);
 100 }
 101 
 102 // This method contains no policy. You should probably
 103 // be calling invoke() instead.
 104 void PSMarkSweep::invoke_no_policy(bool clear_all_softrefs) {
 105   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
 106   assert(ref_processor() != NULL, "Sanity");
 107 
 108   if (GC_locker::check_active_before_gc()) {
 109     return;
 110   }
 111 
 112   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 113   GCCause::Cause gc_cause = heap->gc_cause();
 114   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 115   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
 116 
 117   // The scope of casr should end after code that can change
 118   // CollectorPolicy::_should_clear_all_soft_refs.
 119   ClearedAllSoftRefs casr(clear_all_softrefs, heap->collector_policy());
 120 
 121   PSYoungGen* young_gen = heap->young_gen();
 122   PSOldGen* old_gen = heap->old_gen();
 123   PSPermGen* perm_gen = heap->perm_gen();
 124 
 125   // Increment the invocation count
 126   heap->increment_total_collections(true /* full */);
 127 
 128   // Save information needed to minimize mangling
 129   heap->record_gen_tops_before_GC();
 130 
 131   // We need to track unique mark sweep invocations as well.
 132   _total_invocations++;
 133 
 134   AdaptiveSizePolicyOutput(size_policy, heap->total_collections());
 135 
 136   if (PrintHeapAtGC) {
 137     Universe::print_heap_before_gc();
 138   }
 139 
 140   // Fill in TLABs
 141   heap->accumulate_statistics_all_tlabs();
 142   heap->ensure_parsability(true);  // retire TLABs
 143 
 144   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
 145     HandleMark hm;  // Discard invalid handles created during verification
 146     gclog_or_tty->print(" VerifyBeforeGC:");
 147     Universe::verify(true);
 148   }
 149 
 150   // Verify object start arrays
 151   if (VerifyObjectStartArray &&
 152       VerifyBeforeGC) {
 153     old_gen->verify_object_start_array();
 154     perm_gen->verify_object_start_array();
 155   }
 156 
 157   heap->pre_full_gc_dump();
 158 
 159   // Filled in below to track the state of the young gen after the collection.
 160   bool eden_empty;
 161   bool survivors_empty;
 162   bool young_gen_empty;
 163 
 164   {
 165     HandleMark hm;
 166     const bool is_system_gc = gc_cause == GCCause::_java_lang_system_gc;
 167     // This is useful for debugging but don't change the output the
 168     // the customer sees.
 169     const char* gc_cause_str = "Full GC";
 170     if (is_system_gc && PrintGCDetails) {
 171       gc_cause_str = "Full GC (System)";
 172     }
 173     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
 174     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
 175     TraceTime t1(gc_cause_str, PrintGC, !PrintGCDetails, gclog_or_tty);
 176     TraceCollectorStats tcs(counters());
 177     TraceMemoryManagerStats tms(true /* Full GC */);
 178 
 179     if (TraceGen1Time) accumulated_time()->start();
 180 
 181     // Let the size policy know we're starting
 182     size_policy->major_collection_begin();
 183 
 184     // When collecting the permanent generation methodOops may be moving,
 185     // so we either have to flush all bcp data or convert it into bci.
 186     CodeCache::gc_prologue();
 187     Threads::gc_prologue();
 188     BiasedLocking::preserve_marks();
 189 
 190     // Capture heap size before collection for printing.
 191     size_t prev_used = heap->used();
 192 
 193     // Capture perm gen size before collection for sizing.
 194     size_t perm_gen_prev_used = perm_gen->used_in_bytes();
 195 
 196     // For PrintGCDetails
 197     size_t old_gen_prev_used = old_gen->used_in_bytes();
 198     size_t young_gen_prev_used = young_gen->used_in_bytes();
 199 
 200     allocate_stacks();
 201 
 202     NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
 203     COMPILER2_PRESENT(DerivedPointerTable::clear());
 204 
 205     ref_processor()->enable_discovery();
 206     ref_processor()->setup_policy(clear_all_softrefs);
 207 
 208     mark_sweep_phase1(clear_all_softrefs);
 209 
 210     mark_sweep_phase2();
 211 
 212     // Don't add any more derived pointers during phase3
 213     COMPILER2_PRESENT(assert(DerivedPointerTable::is_active(), "Sanity"));
 214     COMPILER2_PRESENT(DerivedPointerTable::set_active(false));
 215 
 216     mark_sweep_phase3();
 217 
 218     mark_sweep_phase4();
 219 
 220     restore_marks();
 221 
 222     deallocate_stacks();
 223 
 224     if (ZapUnusedHeapArea) {
 225       // Do a complete mangle (top to end) because the usage for
 226       // scratch does not maintain a top pointer.
 227       young_gen->to_space()->mangle_unused_area_complete();
 228     }
 229 
 230     eden_empty = young_gen->eden_space()->is_empty();
 231     if (!eden_empty) {
 232       eden_empty = absorb_live_data_from_eden(size_policy, young_gen, old_gen);
 233     }
 234 
 235     // Update heap occupancy information which is used as
 236     // input to soft ref clearing policy at the next gc.
 237     Universe::update_heap_info_at_gc();
 238 
 239     survivors_empty = young_gen->from_space()->is_empty() &&
 240                       young_gen->to_space()->is_empty();
 241     young_gen_empty = eden_empty && survivors_empty;
 242 
 243     BarrierSet* bs = heap->barrier_set();
 244     if (bs->is_a(BarrierSet::ModRef)) {
 245       ModRefBarrierSet* modBS = (ModRefBarrierSet*)bs;
 246       MemRegion old_mr = heap->old_gen()->reserved();
 247       MemRegion perm_mr = heap->perm_gen()->reserved();
 248       assert(perm_mr.end() <= old_mr.start(), "Generations out of order");
 249 
 250       if (young_gen_empty) {
 251         modBS->clear(MemRegion(perm_mr.start(), old_mr.end()));
 252       } else {
 253         modBS->invalidate(MemRegion(perm_mr.start(), old_mr.end()));
 254       }
 255     }
 256 
 257     BiasedLocking::restore_marks();
 258     Threads::gc_epilogue();
 259     CodeCache::gc_epilogue();
 260 
 261     COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 262 
 263     ref_processor()->enqueue_discovered_references(NULL);
 264 
 265     // Update time of last GC
 266     reset_millis_since_last_gc();
 267 
 268     // Let the size policy know we're done
 269     size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
 270 
 271     if (UseAdaptiveSizePolicy) {
 272 
 273       if (PrintAdaptiveSizePolicy) {
 274         gclog_or_tty->print("AdaptiveSizeStart: ");
 275         gclog_or_tty->stamp();
 276         gclog_or_tty->print_cr(" collection: %d ",
 277                        heap->total_collections());
 278         if (Verbose) {
 279           gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d"
 280             " perm_gen_capacity: %d ",
 281             old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes(),
 282             perm_gen->capacity_in_bytes());
 283         }
 284       }
 285 
 286       // Don't check if the size_policy is ready here.  Let
 287       // the size_policy check that internally.
 288       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
 289           ((gc_cause != GCCause::_java_lang_system_gc) ||
 290             UseAdaptiveSizePolicyWithSystemGC)) {
 291         // Calculate optimal free space amounts
 292         assert(young_gen->max_size() >
 293           young_gen->from_space()->capacity_in_bytes() +
 294           young_gen->to_space()->capacity_in_bytes(),
 295           "Sizes of space in young gen are out-of-bounds");
 296         size_t max_eden_size = young_gen->max_size() -
 297           young_gen->from_space()->capacity_in_bytes() -
 298           young_gen->to_space()->capacity_in_bytes();
 299         size_policy->compute_generation_free_space(young_gen->used_in_bytes(),
 300                                  young_gen->eden_space()->used_in_bytes(),
 301                                  old_gen->used_in_bytes(),
 302                                  perm_gen->used_in_bytes(),
 303                                  young_gen->eden_space()->capacity_in_bytes(),
 304                                  old_gen->max_gen_size(),
 305                                  max_eden_size,
 306                                  true /* full gc*/,
 307                                  gc_cause,
 308                                  heap->collector_policy());
 309 
 310         heap->resize_old_gen(size_policy->calculated_old_free_size_in_bytes());
 311 
 312         // Don't resize the young generation at an major collection.  A
 313         // desired young generation size may have been calculated but
 314         // resizing the young generation complicates the code because the
 315         // resizing of the old generation may have moved the boundary
 316         // between the young generation and the old generation.  Let the
 317         // young generation resizing happen at the minor collections.
 318       }
 319       if (PrintAdaptiveSizePolicy) {
 320         gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ",
 321                        heap->total_collections());
 322       }
 323     }
 324 
 325     if (UsePerfData) {
 326       heap->gc_policy_counters()->update_counters();
 327       heap->gc_policy_counters()->update_old_capacity(
 328         old_gen->capacity_in_bytes());
 329       heap->gc_policy_counters()->update_young_capacity(
 330         young_gen->capacity_in_bytes());
 331     }
 332 
 333     heap->resize_all_tlabs();
 334 
 335     // We collected the perm gen, so we'll resize it here.
 336     perm_gen->compute_new_size(perm_gen_prev_used);
 337 
 338     if (TraceGen1Time) accumulated_time()->stop();
 339 
 340     if (PrintGC) {
 341       if (PrintGCDetails) {
 342         // Don't print a GC timestamp here.  This is after the GC so
 343         // would be confusing.
 344         young_gen->print_used_change(young_gen_prev_used);
 345         old_gen->print_used_change(old_gen_prev_used);
 346       }
 347       heap->print_heap_change(prev_used);
 348       // Do perm gen after heap becase prev_used does
 349       // not include the perm gen (done this way in the other
 350       // collectors).
 351       if (PrintGCDetails) {
 352         perm_gen->print_used_change(perm_gen_prev_used);
 353       }
 354     }
 355 
 356     // Track memory usage and detect low memory
 357     MemoryService::track_memory_usage();
 358     heap->update_counters();
 359   }
 360 
 361   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
 362     HandleMark hm;  // Discard invalid handles created during verification
 363     gclog_or_tty->print(" VerifyAfterGC:");
 364     Universe::verify(false);
 365   }
 366 
 367   // Re-verify object start arrays
 368   if (VerifyObjectStartArray &&
 369       VerifyAfterGC) {
 370     old_gen->verify_object_start_array();
 371     perm_gen->verify_object_start_array();
 372   }
 373 
 374   if (ZapUnusedHeapArea) {
 375     old_gen->object_space()->check_mangled_unused_area_complete();
 376     perm_gen->object_space()->check_mangled_unused_area_complete();
 377   }
 378 
 379   NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
 380 
 381   if (PrintHeapAtGC) {
 382     Universe::print_heap_after_gc();
 383   }
 384 
 385   heap->post_full_gc_dump();
 386 
 387 #ifdef TRACESPINNING
 388   ParallelTaskTerminator::print_termination_counts();
 389 #endif
 390 }
 391 
 392 bool PSMarkSweep::absorb_live_data_from_eden(PSAdaptiveSizePolicy* size_policy,
 393                                              PSYoungGen* young_gen,
 394                                              PSOldGen* old_gen) {
 395   MutableSpace* const eden_space = young_gen->eden_space();
 396   assert(!eden_space->is_empty(), "eden must be non-empty");
 397   assert(young_gen->virtual_space()->alignment() ==
 398          old_gen->virtual_space()->alignment(), "alignments do not match");
 399 
 400   if (!(UseAdaptiveSizePolicy && UseAdaptiveGCBoundary)) {
 401     return false;
 402   }
 403 
 404   // Both generations must be completely committed.
 405   if (young_gen->virtual_space()->uncommitted_size() != 0) {
 406     return false;
 407   }
 408   if (old_gen->virtual_space()->uncommitted_size() != 0) {
 409     return false;
 410   }
 411 
 412   // Figure out how much to take from eden.  Include the average amount promoted
 413   // in the total; otherwise the next young gen GC will simply bail out to a
 414   // full GC.
 415   const size_t alignment = old_gen->virtual_space()->alignment();
 416   const size_t eden_used = eden_space->used_in_bytes();
 417   const size_t promoted = (size_t)size_policy->avg_promoted()->padded_average();
 418   const size_t absorb_size = align_size_up(eden_used + promoted, alignment);
 419   const size_t eden_capacity = eden_space->capacity_in_bytes();
 420 
 421   if (absorb_size >= eden_capacity) {
 422     return false; // Must leave some space in eden.
 423   }
 424 
 425   const size_t new_young_size = young_gen->capacity_in_bytes() - absorb_size;
 426   if (new_young_size < young_gen->min_gen_size()) {
 427     return false; // Respect young gen minimum size.
 428   }
 429 
 430   if (TraceAdaptiveGCBoundary && Verbose) {
 431     gclog_or_tty->print(" absorbing " SIZE_FORMAT "K:  "
 432                         "eden " SIZE_FORMAT "K->" SIZE_FORMAT "K "
 433                         "from " SIZE_FORMAT "K, to " SIZE_FORMAT "K "
 434                         "young_gen " SIZE_FORMAT "K->" SIZE_FORMAT "K ",
 435                         absorb_size / K,
 436                         eden_capacity / K, (eden_capacity - absorb_size) / K,
 437                         young_gen->from_space()->used_in_bytes() / K,
 438                         young_gen->to_space()->used_in_bytes() / K,
 439                         young_gen->capacity_in_bytes() / K, new_young_size / K);
 440   }
 441 
 442   // Fill the unused part of the old gen.
 443   MutableSpace* const old_space = old_gen->object_space();
 444   HeapWord* const unused_start = old_space->top();
 445   size_t const unused_words = pointer_delta(old_space->end(), unused_start);
 446 
 447   if (unused_words > 0) {
 448     if (unused_words < CollectedHeap::min_fill_size()) {
 449       return false;  // If the old gen cannot be filled, must give up.
 450     }
 451     CollectedHeap::fill_with_objects(unused_start, unused_words);
 452   }
 453 
 454   // Take the live data from eden and set both top and end in the old gen to
 455   // eden top.  (Need to set end because reset_after_change() mangles the region
 456   // from end to virtual_space->high() in debug builds).
 457   HeapWord* const new_top = eden_space->top();
 458   old_gen->virtual_space()->expand_into(young_gen->virtual_space(),
 459                                         absorb_size);
 460   young_gen->reset_after_change();
 461   old_space->set_top(new_top);
 462   old_space->set_end(new_top);
 463   old_gen->reset_after_change();
 464 
 465   // Update the object start array for the filler object and the data from eden.
 466   ObjectStartArray* const start_array = old_gen->start_array();
 467   for (HeapWord* p = unused_start; p < new_top; p += oop(p)->size()) {
 468     start_array->allocate_block(p);
 469   }
 470 
 471   // Could update the promoted average here, but it is not typically updated at
 472   // full GCs and the value to use is unclear.  Something like
 473   //
 474   // cur_promoted_avg + absorb_size / number_of_scavenges_since_last_full_gc.
 475 
 476   size_policy->set_bytes_absorbed_from_eden(absorb_size);
 477   return true;
 478 }
 479 
 480 void PSMarkSweep::allocate_stacks() {
 481   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 482   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 483 
 484   PSYoungGen* young_gen = heap->young_gen();
 485 
 486   MutableSpace* to_space = young_gen->to_space();
 487   _preserved_marks = (PreservedMark*)to_space->top();
 488   _preserved_count = 0;
 489 
 490   // We want to calculate the size in bytes first.
 491   _preserved_count_max  = pointer_delta(to_space->end(), to_space->top(), sizeof(jbyte));
 492   // Now divide by the size of a PreservedMark
 493   _preserved_count_max /= sizeof(PreservedMark);
 494 
 495   _preserved_mark_stack = NULL;
 496   _preserved_oop_stack = NULL;
 497 
 498   _marking_stack = new (ResourceObj::C_HEAP) GrowableArray<oop>(4000, true);
 499   _objarray_stack = new (ResourceObj::C_HEAP) GrowableArray<ObjArrayTask>(50, true);
 500 
 501   int size = SystemDictionary::number_of_classes() * 2;
 502   _revisit_klass_stack = new (ResourceObj::C_HEAP) GrowableArray<Klass*>(size, true);
 503   // (#klass/k)^2, for k ~ 10 appears a better setting, but this will have to do for
 504   // now until we investigate a more optimal setting.
 505   _revisit_mdo_stack   = new (ResourceObj::C_HEAP) GrowableArray<DataLayout*>(size*2, true);
 506 }
 507 
 508 
 509 void PSMarkSweep::deallocate_stacks() {
 510   if (_preserved_oop_stack) {
 511     delete _preserved_mark_stack;
 512     _preserved_mark_stack = NULL;
 513     delete _preserved_oop_stack;
 514     _preserved_oop_stack = NULL;
 515   }
 516 
 517   delete _marking_stack;
 518   delete _objarray_stack;
 519   delete _revisit_klass_stack;
 520   delete _revisit_mdo_stack;
 521 }
 522 
 523 void PSMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
 524   // Recursively traverse all live objects and mark them
 525   EventMark m("1 mark object");
 526   TraceTime tm("phase 1", PrintGCDetails && Verbose, true, gclog_or_tty);
 527   trace(" 1");
 528 
 529   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 530   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 531 
 532   // General strong roots.
 533   {
 534     ParallelScavengeHeap::ParStrongRootsScope psrs;
 535     Universe::oops_do(mark_and_push_closure());
 536     ReferenceProcessor::oops_do(mark_and_push_closure());
 537     JNIHandles::oops_do(mark_and_push_closure());   // Global (strong) JNI handles
 538     CodeBlobToOopClosure each_active_code_blob(mark_and_push_closure(), /*do_marking=*/ true);
 539     Threads::oops_do(mark_and_push_closure(), &each_active_code_blob);
 540     ObjectSynchronizer::oops_do(mark_and_push_closure());
 541     FlatProfiler::oops_do(mark_and_push_closure());
 542     Management::oops_do(mark_and_push_closure());
 543     JvmtiExport::oops_do(mark_and_push_closure());
 544     SystemDictionary::always_strong_oops_do(mark_and_push_closure());
 545     vmSymbols::oops_do(mark_and_push_closure());
 546     // Do not treat nmethods as strong roots for mark/sweep, since we can unload them.
 547     //CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure(mark_and_push_closure()));
 548   }
 549 
 550   // Flush marking stack.
 551   follow_stack();
 552 
 553   // Process reference objects found during marking
 554   {
 555     ref_processor()->setup_policy(clear_all_softrefs);
 556     ref_processor()->process_discovered_references(
 557       is_alive_closure(), mark_and_push_closure(), follow_stack_closure(), NULL);
 558   }
 559 
 560   // Follow system dictionary roots and unload classes
 561   bool purged_class = SystemDictionary::do_unloading(is_alive_closure());
 562 
 563   // Follow code cache roots
 564   CodeCache::do_unloading(is_alive_closure(), mark_and_push_closure(),
 565                           purged_class);
 566   follow_stack(); // Flush marking stack
 567 
 568   // Update subklass/sibling/implementor links of live klasses
 569   follow_weak_klass_links();
 570   assert(_marking_stack->is_empty(), "just drained");
 571 
 572   // Visit memoized mdo's and clear unmarked weak refs
 573   follow_mdo_weak_refs();
 574   assert(_marking_stack->is_empty(), "just drained");
 575 
 576   // Visit symbol and interned string tables and delete unmarked oops
 577   SymbolTable::unlink(is_alive_closure());
 578   StringTable::unlink(is_alive_closure());
 579 
 580   assert(_marking_stack->is_empty(), "stack should be empty by now");
 581 }
 582 
 583 
 584 void PSMarkSweep::mark_sweep_phase2() {
 585   EventMark m("2 compute new addresses");
 586   TraceTime tm("phase 2", PrintGCDetails && Verbose, true, gclog_or_tty);
 587   trace("2");
 588 
 589   // Now all live objects are marked, compute the new object addresses.
 590 
 591   // It is imperative that we traverse perm_gen LAST. If dead space is
 592   // allowed a range of dead object may get overwritten by a dead int
 593   // array. If perm_gen is not traversed last a klassOop may get
 594   // overwritten. This is fine since it is dead, but if the class has dead
 595   // instances we have to skip them, and in order to find their size we
 596   // need the klassOop!
 597   //
 598   // It is not required that we traverse spaces in the same order in
 599   // phase2, phase3 and phase4, but the ValidateMarkSweep live oops
 600   // tracking expects us to do so. See comment under phase4.
 601 
 602   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 603   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 604 
 605   PSOldGen* old_gen = heap->old_gen();
 606   PSPermGen* perm_gen = heap->perm_gen();
 607 
 608   // Begin compacting into the old gen
 609   PSMarkSweepDecorator::set_destination_decorator_tenured();
 610 
 611   // This will also compact the young gen spaces.
 612   old_gen->precompact();
 613 
 614   // Compact the perm gen into the perm gen
 615   PSMarkSweepDecorator::set_destination_decorator_perm_gen();
 616 
 617   perm_gen->precompact();
 618 }
 619 
 620 // This should be moved to the shared markSweep code!
 621 class PSAlwaysTrueClosure: public BoolObjectClosure {
 622 public:
 623   void do_object(oop p) { ShouldNotReachHere(); }
 624   bool do_object_b(oop p) { return true; }
 625 };
 626 static PSAlwaysTrueClosure always_true;
 627 
 628 void PSMarkSweep::mark_sweep_phase3() {
 629   // Adjust the pointers to reflect the new locations
 630   EventMark m("3 adjust pointers");
 631   TraceTime tm("phase 3", PrintGCDetails && Verbose, true, gclog_or_tty);
 632   trace("3");
 633 
 634   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 635   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 636 
 637   PSYoungGen* young_gen = heap->young_gen();
 638   PSOldGen* old_gen = heap->old_gen();
 639   PSPermGen* perm_gen = heap->perm_gen();
 640 
 641   // General strong roots.
 642   Universe::oops_do(adjust_root_pointer_closure());
 643   ReferenceProcessor::oops_do(adjust_root_pointer_closure());
 644   JNIHandles::oops_do(adjust_root_pointer_closure());   // Global (strong) JNI handles
 645   Threads::oops_do(adjust_root_pointer_closure(), NULL);
 646   ObjectSynchronizer::oops_do(adjust_root_pointer_closure());
 647   FlatProfiler::oops_do(adjust_root_pointer_closure());
 648   Management::oops_do(adjust_root_pointer_closure());
 649   JvmtiExport::oops_do(adjust_root_pointer_closure());
 650   // SO_AllClasses
 651   SystemDictionary::oops_do(adjust_root_pointer_closure());
 652   vmSymbols::oops_do(adjust_root_pointer_closure());
 653   //CodeCache::scavenge_root_nmethods_oops_do(adjust_root_pointer_closure());
 654 
 655   // Now adjust pointers in remaining weak roots.  (All of which should
 656   // have been cleared if they pointed to non-surviving objects.)
 657   // Global (weak) JNI handles
 658   JNIHandles::weak_oops_do(&always_true, adjust_root_pointer_closure());
 659 
 660   CodeCache::oops_do(adjust_pointer_closure());
 661   SymbolTable::oops_do(adjust_root_pointer_closure());
 662   StringTable::oops_do(adjust_root_pointer_closure());
 663   ref_processor()->weak_oops_do(adjust_root_pointer_closure());
 664   PSScavenge::reference_processor()->weak_oops_do(adjust_root_pointer_closure());
 665 
 666   adjust_marks();
 667 
 668   young_gen->adjust_pointers();
 669   old_gen->adjust_pointers();
 670   perm_gen->adjust_pointers();
 671 }
 672 
 673 void PSMarkSweep::mark_sweep_phase4() {
 674   EventMark m("4 compact heap");
 675   TraceTime tm("phase 4", PrintGCDetails && Verbose, true, gclog_or_tty);
 676   trace("4");
 677 
 678   // All pointers are now adjusted, move objects accordingly
 679 
 680   // It is imperative that we traverse perm_gen first in phase4. All
 681   // classes must be allocated earlier than their instances, and traversing
 682   // perm_gen first makes sure that all klassOops have moved to their new
 683   // location before any instance does a dispatch through it's klass!
 684   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 685   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 686 
 687   PSYoungGen* young_gen = heap->young_gen();
 688   PSOldGen* old_gen = heap->old_gen();
 689   PSPermGen* perm_gen = heap->perm_gen();
 690 
 691   perm_gen->compact();
 692   old_gen->compact();
 693   young_gen->compact();
 694 }
 695 
 696 jlong PSMarkSweep::millis_since_last_gc() {
 697   jlong ret_val = os::javaTimeMillis() - _time_of_last_gc;
 698   // XXX See note in genCollectedHeap::millis_since_last_gc().
 699   if (ret_val < 0) {
 700     NOT_PRODUCT(warning("time warp: %d", ret_val);)
 701     return 0;
 702   }
 703   return ret_val;
 704 }
 705 
 706 void PSMarkSweep::reset_millis_since_last_gc() {
 707   _time_of_last_gc = os::javaTimeMillis();
 708 }