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