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