1 /*
   2  * Copyright 2001-2008 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   // Filled in below to track the state of the young gen after the collection.
 129   bool eden_empty;
 130   bool survivors_empty;
 131   bool young_gen_empty;
 132 
 133   {
 134     HandleMark hm;
 135     const bool is_system_gc = gc_cause == GCCause::_java_lang_system_gc;
 136     // This is useful for debugging but don't change the output the
 137     // the customer sees.
 138     const char* gc_cause_str = "Full GC";
 139     if (is_system_gc && PrintGCDetails) {
 140       gc_cause_str = "Full GC (System)";
 141     }
 142     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
 143     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
 144     TraceTime t1(gc_cause_str, PrintGC, !PrintGCDetails, gclog_or_tty);
 145     TraceCollectorStats tcs(counters());
 146     TraceMemoryManagerStats tms(true /* Full GC */);
 147 
 148     if (TraceGen1Time) accumulated_time()->start();
 149 
 150     // Let the size policy know we're starting
 151     size_policy->major_collection_begin();
 152 
 153     // When collecting the permanent generation methodOops may be moving,
 154     // so we either have to flush all bcp data or convert it into bci.
 155     CodeCache::gc_prologue();
 156     Threads::gc_prologue();
 157     BiasedLocking::preserve_marks();
 158 
 159     // Capture heap size before collection for printing.
 160     size_t prev_used = heap->used();
 161 
 162     // Capture perm gen size before collection for sizing.
 163     size_t perm_gen_prev_used = perm_gen->used_in_bytes();
 164 
 165     // For PrintGCDetails
 166     size_t old_gen_prev_used = old_gen->used_in_bytes();
 167     size_t young_gen_prev_used = young_gen->used_in_bytes();
 168 
 169     allocate_stacks();
 170 
 171     NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
 172     COMPILER2_PRESENT(DerivedPointerTable::clear());
 173 
 174     ref_processor()->enable_discovery();
 175 
 176     mark_sweep_phase1(clear_all_softrefs);
 177 
 178     mark_sweep_phase2();
 179 
 180     // Don't add any more derived pointers during phase3
 181     COMPILER2_PRESENT(assert(DerivedPointerTable::is_active(), "Sanity"));
 182     COMPILER2_PRESENT(DerivedPointerTable::set_active(false));
 183 
 184     mark_sweep_phase3();
 185 
 186     mark_sweep_phase4();
 187 
 188     restore_marks();
 189 
 190     deallocate_stacks();
 191 
 192     if (ZapUnusedHeapArea) {
 193       // Do a complete mangle (top to end) because the usage for
 194       // scratch does not maintain a top pointer.
 195       young_gen->to_space()->mangle_unused_area_complete();
 196     }
 197 
 198     eden_empty = young_gen->eden_space()->is_empty();
 199     if (!eden_empty) {
 200       eden_empty = absorb_live_data_from_eden(size_policy, young_gen, old_gen);
 201     }
 202 
 203     // Update heap occupancy information which is used as
 204     // input to soft ref clearing policy at the next gc.
 205     Universe::update_heap_info_at_gc();
 206 
 207     survivors_empty = young_gen->from_space()->is_empty() &&
 208                       young_gen->to_space()->is_empty();
 209     young_gen_empty = eden_empty && survivors_empty;
 210 
 211     BarrierSet* bs = heap->barrier_set();
 212     if (bs->is_a(BarrierSet::ModRef)) {
 213       ModRefBarrierSet* modBS = (ModRefBarrierSet*)bs;
 214       MemRegion old_mr = heap->old_gen()->reserved();
 215       MemRegion perm_mr = heap->perm_gen()->reserved();
 216       assert(perm_mr.end() <= old_mr.start(), "Generations out of order");
 217 
 218       if (young_gen_empty) {
 219         modBS->clear(MemRegion(perm_mr.start(), old_mr.end()));
 220       } else {
 221         modBS->invalidate(MemRegion(perm_mr.start(), old_mr.end()));
 222       }
 223     }
 224 
 225     BiasedLocking::restore_marks();
 226     Threads::gc_epilogue();
 227     CodeCache::gc_epilogue();
 228 
 229     COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 230 
 231     ref_processor()->enqueue_discovered_references(NULL);
 232 
 233     // Update time of last GC
 234     reset_millis_since_last_gc();
 235 
 236     // Let the size policy know we're done
 237     size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
 238 
 239     if (UseAdaptiveSizePolicy) {
 240 
 241       if (PrintAdaptiveSizePolicy) {
 242         gclog_or_tty->print("AdaptiveSizeStart: ");
 243         gclog_or_tty->stamp();
 244         gclog_or_tty->print_cr(" collection: %d ",
 245                        heap->total_collections());
 246         if (Verbose) {
 247           gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d"
 248             " perm_gen_capacity: %d ",
 249             old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes(),
 250             perm_gen->capacity_in_bytes());
 251         }
 252       }
 253 
 254       // Don't check if the size_policy is ready here.  Let
 255       // the size_policy check that internally.
 256       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
 257           ((gc_cause != GCCause::_java_lang_system_gc) ||
 258             UseAdaptiveSizePolicyWithSystemGC)) {
 259         // Calculate optimal free space amounts
 260         assert(young_gen->max_size() >
 261           young_gen->from_space()->capacity_in_bytes() +
 262           young_gen->to_space()->capacity_in_bytes(),
 263           "Sizes of space in young gen are out-of-bounds");
 264         size_t max_eden_size = young_gen->max_size() -
 265           young_gen->from_space()->capacity_in_bytes() -
 266           young_gen->to_space()->capacity_in_bytes();
 267         size_policy->compute_generation_free_space(young_gen->used_in_bytes(),
 268                                  young_gen->eden_space()->used_in_bytes(),
 269                                  old_gen->used_in_bytes(),
 270                                  perm_gen->used_in_bytes(),
 271                                  young_gen->eden_space()->capacity_in_bytes(),
 272                                  old_gen->max_gen_size(),
 273                                  max_eden_size,
 274                                  true /* full gc*/,
 275                                  gc_cause);
 276 
 277         heap->resize_old_gen(size_policy->calculated_old_free_size_in_bytes());
 278 
 279         // Don't resize the young generation at an major collection.  A
 280         // desired young generation size may have been calculated but
 281         // resizing the young generation complicates the code because the
 282         // resizing of the old generation may have moved the boundary
 283         // between the young generation and the old generation.  Let the
 284         // young generation resizing happen at the minor collections.
 285       }
 286       if (PrintAdaptiveSizePolicy) {
 287         gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ",
 288                        heap->total_collections());
 289       }
 290     }
 291 
 292     if (UsePerfData) {
 293       heap->gc_policy_counters()->update_counters();
 294       heap->gc_policy_counters()->update_old_capacity(
 295         old_gen->capacity_in_bytes());
 296       heap->gc_policy_counters()->update_young_capacity(
 297         young_gen->capacity_in_bytes());
 298     }
 299 
 300     heap->resize_all_tlabs();
 301 
 302     // We collected the perm gen, so we'll resize it here.
 303     perm_gen->compute_new_size(perm_gen_prev_used);
 304 
 305     if (TraceGen1Time) accumulated_time()->stop();
 306 
 307     if (PrintGC) {
 308       if (PrintGCDetails) {
 309         // Don't print a GC timestamp here.  This is after the GC so
 310         // would be confusing.
 311         young_gen->print_used_change(young_gen_prev_used);
 312         old_gen->print_used_change(old_gen_prev_used);
 313       }
 314       heap->print_heap_change(prev_used);
 315       // Do perm gen after heap becase prev_used does
 316       // not include the perm gen (done this way in the other
 317       // collectors).
 318       if (PrintGCDetails) {
 319         perm_gen->print_used_change(perm_gen_prev_used);
 320       }
 321     }
 322 
 323     // Track memory usage and detect low memory
 324     MemoryService::track_memory_usage();
 325     heap->update_counters();
 326 
 327     if (PrintGCDetails) {
 328       if (size_policy->print_gc_time_limit_would_be_exceeded()) {
 329         if (size_policy->gc_time_limit_exceeded()) {
 330           gclog_or_tty->print_cr("      GC time is exceeding GCTimeLimit "
 331             "of %d%%", GCTimeLimit);
 332         } else {
 333           gclog_or_tty->print_cr("      GC time would exceed GCTimeLimit "
 334             "of %d%%", GCTimeLimit);
 335         }
 336       }
 337       size_policy->set_print_gc_time_limit_would_be_exceeded(false);
 338     }
 339   }
 340 
 341   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
 342     HandleMark hm;  // Discard invalid handles created during verification
 343     gclog_or_tty->print(" VerifyAfterGC:");
 344     Universe::verify(false);
 345   }
 346 
 347   // Re-verify object start arrays
 348   if (VerifyObjectStartArray &&
 349       VerifyAfterGC) {
 350     old_gen->verify_object_start_array();
 351     perm_gen->verify_object_start_array();
 352   }
 353 
 354   if (ZapUnusedHeapArea) {
 355     old_gen->object_space()->check_mangled_unused_area_complete();
 356     perm_gen->object_space()->check_mangled_unused_area_complete();
 357   }
 358 
 359   NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
 360 
 361   if (PrintHeapAtGC) {
 362     Universe::print_heap_after_gc();
 363   }
 364 }
 365 
 366 bool PSMarkSweep::absorb_live_data_from_eden(PSAdaptiveSizePolicy* size_policy,
 367                                              PSYoungGen* young_gen,
 368                                              PSOldGen* old_gen) {
 369   MutableSpace* const eden_space = young_gen->eden_space();
 370   assert(!eden_space->is_empty(), "eden must be non-empty");
 371   assert(young_gen->virtual_space()->alignment() ==
 372          old_gen->virtual_space()->alignment(), "alignments do not match");
 373 
 374   if (!(UseAdaptiveSizePolicy && UseAdaptiveGCBoundary)) {
 375     return false;
 376   }
 377 
 378   // Both generations must be completely committed.
 379   if (young_gen->virtual_space()->uncommitted_size() != 0) {
 380     return false;
 381   }
 382   if (old_gen->virtual_space()->uncommitted_size() != 0) {
 383     return false;
 384   }
 385 
 386   // Figure out how much to take from eden.  Include the average amount promoted
 387   // in the total; otherwise the next young gen GC will simply bail out to a
 388   // full GC.
 389   const size_t alignment = old_gen->virtual_space()->alignment();
 390   const size_t eden_used = eden_space->used_in_bytes();
 391   const size_t promoted = (size_t)(size_policy->avg_promoted()->padded_average());
 392   const size_t absorb_size = align_size_up(eden_used + promoted, alignment);
 393   const size_t eden_capacity = eden_space->capacity_in_bytes();
 394 
 395   if (absorb_size >= eden_capacity) {
 396     return false; // Must leave some space in eden.
 397   }
 398 
 399   const size_t new_young_size = young_gen->capacity_in_bytes() - absorb_size;
 400   if (new_young_size < young_gen->min_gen_size()) {
 401     return false; // Respect young gen minimum size.
 402   }
 403 
 404   if (TraceAdaptiveGCBoundary && Verbose) {
 405     gclog_or_tty->print(" absorbing " SIZE_FORMAT "K:  "
 406                         "eden " SIZE_FORMAT "K->" SIZE_FORMAT "K "
 407                         "from " SIZE_FORMAT "K, to " SIZE_FORMAT "K "
 408                         "young_gen " SIZE_FORMAT "K->" SIZE_FORMAT "K ",
 409                         absorb_size / K,
 410                         eden_capacity / K, (eden_capacity - absorb_size) / K,
 411                         young_gen->from_space()->used_in_bytes() / K,
 412                         young_gen->to_space()->used_in_bytes() / K,
 413                         young_gen->capacity_in_bytes() / K, new_young_size / K);
 414   }
 415 
 416   // Fill the unused part of the old gen.
 417   MutableSpace* const old_space = old_gen->object_space();
 418   MemRegion old_gen_unused(old_space->top(), old_space->end());
 419 
 420   // If the unused part of the old gen cannot be filled, skip
 421   // absorbing eden.
 422   if (old_gen_unused.word_size() < SharedHeap::min_fill_size()) {
 423     return false;
 424   }
 425 
 426   if (!old_gen_unused.is_empty()) {
 427     SharedHeap::fill_region_with_object(old_gen_unused);
 428   }
 429 
 430   // Take the live data from eden and set both top and end in the old gen to
 431   // eden top.  (Need to set end because reset_after_change() mangles the region
 432   // from end to virtual_space->high() in debug builds).
 433   HeapWord* const new_top = eden_space->top();
 434   old_gen->virtual_space()->expand_into(young_gen->virtual_space(),
 435                                         absorb_size);
 436   young_gen->reset_after_change();
 437   old_space->set_top(new_top);
 438   old_space->set_end(new_top);
 439   old_gen->reset_after_change();
 440 
 441   // Update the object start array for the filler object and the data from eden.
 442   ObjectStartArray* const start_array = old_gen->start_array();
 443   HeapWord* const start = old_gen_unused.start();
 444   for (HeapWord* addr = start; addr < new_top; addr += oop(addr)->size()) {
 445     start_array->allocate_block(addr);
 446   }
 447 
 448   // Could update the promoted average here, but it is not typically updated at
 449   // full GCs and the value to use is unclear.  Something like
 450   //
 451   // cur_promoted_avg + absorb_size / number_of_scavenges_since_last_full_gc.
 452 
 453   size_policy->set_bytes_absorbed_from_eden(absorb_size);
 454   return true;
 455 }
 456 
 457 void PSMarkSweep::allocate_stacks() {
 458   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 459   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 460 
 461   PSYoungGen* young_gen = heap->young_gen();
 462 
 463   MutableSpace* to_space = young_gen->to_space();
 464   _preserved_marks = (PreservedMark*)to_space->top();
 465   _preserved_count = 0;
 466 
 467   // We want to calculate the size in bytes first.
 468   _preserved_count_max  = pointer_delta(to_space->end(), to_space->top(), sizeof(jbyte));
 469   // Now divide by the size of a PreservedMark
 470   _preserved_count_max /= sizeof(PreservedMark);
 471 
 472   _preserved_mark_stack = NULL;
 473   _preserved_oop_stack = NULL;
 474 
 475   _marking_stack = new (ResourceObj::C_HEAP) GrowableArray<oop>(4000, true);
 476 
 477   int size = SystemDictionary::number_of_classes() * 2;
 478   _revisit_klass_stack = new (ResourceObj::C_HEAP) GrowableArray<Klass*>(size, true);
 479 }
 480 
 481 
 482 void PSMarkSweep::deallocate_stacks() {
 483   if (_preserved_oop_stack) {
 484     delete _preserved_mark_stack;
 485     _preserved_mark_stack = NULL;
 486     delete _preserved_oop_stack;
 487     _preserved_oop_stack = NULL;
 488   }
 489 
 490   delete _marking_stack;
 491   delete _revisit_klass_stack;
 492 }
 493 
 494 void PSMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
 495   // Recursively traverse all live objects and mark them
 496   EventMark m("1 mark object");
 497   TraceTime tm("phase 1", PrintGCDetails && Verbose, true, gclog_or_tty);
 498   trace(" 1");
 499 
 500   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 501   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 502 
 503   // General strong roots.
 504   Universe::oops_do(mark_and_push_closure());
 505   ReferenceProcessor::oops_do(mark_and_push_closure());
 506   JNIHandles::oops_do(mark_and_push_closure());   // Global (strong) JNI handles
 507   Threads::oops_do(mark_and_push_closure());
 508   ObjectSynchronizer::oops_do(mark_and_push_closure());
 509   FlatProfiler::oops_do(mark_and_push_closure());
 510   Management::oops_do(mark_and_push_closure());
 511   JvmtiExport::oops_do(mark_and_push_closure());
 512   SystemDictionary::always_strong_oops_do(mark_and_push_closure());
 513   vmSymbols::oops_do(mark_and_push_closure());
 514 
 515   // Flush marking stack.
 516   follow_stack();
 517 
 518   // Process reference objects found during marking
 519   {
 520     ReferencePolicy *soft_ref_policy;
 521     if (clear_all_softrefs) {
 522       soft_ref_policy = new AlwaysClearPolicy();
 523     } else {
 524 #ifdef COMPILER2
 525       soft_ref_policy = new LRUMaxHeapPolicy();
 526 #else
 527       soft_ref_policy = new LRUCurrentHeapPolicy();
 528 #endif // COMPILER2
 529     }
 530     assert(soft_ref_policy != NULL,"No soft reference policy");
 531     ref_processor()->process_discovered_references(
 532       soft_ref_policy, is_alive_closure(), mark_and_push_closure(),
 533       follow_stack_closure(), NULL);
 534   }
 535 
 536   // Follow system dictionary roots and unload classes
 537   bool purged_class = SystemDictionary::do_unloading(is_alive_closure());
 538 
 539   // Follow code cache roots
 540   CodeCache::do_unloading(is_alive_closure(), mark_and_push_closure(),
 541                           purged_class);
 542   follow_stack(); // Flush marking stack
 543 
 544   // Update subklass/sibling/implementor links of live klasses
 545   follow_weak_klass_links();
 546   assert(_marking_stack->is_empty(), "just drained");
 547 
 548   // Visit symbol and interned string tables and delete unmarked oops
 549   SymbolTable::unlink(is_alive_closure());
 550   StringTable::unlink(is_alive_closure());
 551 
 552   assert(_marking_stack->is_empty(), "stack should be empty by now");
 553 }
 554 
 555 
 556 void PSMarkSweep::mark_sweep_phase2() {
 557   EventMark m("2 compute new addresses");
 558   TraceTime tm("phase 2", PrintGCDetails && Verbose, true, gclog_or_tty);
 559   trace("2");
 560 
 561   // Now all live objects are marked, compute the new object addresses.
 562 
 563   // It is imperative that we traverse perm_gen LAST. If dead space is
 564   // allowed a range of dead object may get overwritten by a dead int
 565   // array. If perm_gen is not traversed last a klassOop may get
 566   // overwritten. This is fine since it is dead, but if the class has dead
 567   // instances we have to skip them, and in order to find their size we
 568   // need the klassOop!
 569   //
 570   // It is not required that we traverse spaces in the same order in
 571   // phase2, phase3 and phase4, but the ValidateMarkSweep live oops
 572   // tracking expects us to do so. See comment under phase4.
 573 
 574   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 575   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 576 
 577   PSOldGen* old_gen = heap->old_gen();
 578   PSPermGen* perm_gen = heap->perm_gen();
 579 
 580   // Begin compacting into the old gen
 581   PSMarkSweepDecorator::set_destination_decorator_tenured();
 582 
 583   // This will also compact the young gen spaces.
 584   old_gen->precompact();
 585 
 586   // Compact the perm gen into the perm gen
 587   PSMarkSweepDecorator::set_destination_decorator_perm_gen();
 588 
 589   perm_gen->precompact();
 590 }
 591 
 592 // This should be moved to the shared markSweep code!
 593 class PSAlwaysTrueClosure: public BoolObjectClosure {
 594 public:
 595   void do_object(oop p) { ShouldNotReachHere(); }
 596   bool do_object_b(oop p) { return true; }
 597 };
 598 static PSAlwaysTrueClosure always_true;
 599 
 600 void PSMarkSweep::mark_sweep_phase3() {
 601   // Adjust the pointers to reflect the new locations
 602   EventMark m("3 adjust pointers");
 603   TraceTime tm("phase 3", PrintGCDetails && Verbose, true, gclog_or_tty);
 604   trace("3");
 605 
 606   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 607   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 608 
 609   PSYoungGen* young_gen = heap->young_gen();
 610   PSOldGen* old_gen = heap->old_gen();
 611   PSPermGen* perm_gen = heap->perm_gen();
 612 
 613   // General strong roots.
 614   Universe::oops_do(adjust_root_pointer_closure());
 615   ReferenceProcessor::oops_do(adjust_root_pointer_closure());
 616   JNIHandles::oops_do(adjust_root_pointer_closure());   // Global (strong) JNI handles
 617   Threads::oops_do(adjust_root_pointer_closure());
 618   ObjectSynchronizer::oops_do(adjust_root_pointer_closure());
 619   FlatProfiler::oops_do(adjust_root_pointer_closure());
 620   Management::oops_do(adjust_root_pointer_closure());
 621   JvmtiExport::oops_do(adjust_root_pointer_closure());
 622   // SO_AllClasses
 623   SystemDictionary::oops_do(adjust_root_pointer_closure());
 624   vmSymbols::oops_do(adjust_root_pointer_closure());
 625 
 626   // Now adjust pointers in remaining weak roots.  (All of which should
 627   // have been cleared if they pointed to non-surviving objects.)
 628   // Global (weak) JNI handles
 629   JNIHandles::weak_oops_do(&always_true, adjust_root_pointer_closure());
 630 
 631   CodeCache::oops_do(adjust_pointer_closure());
 632   SymbolTable::oops_do(adjust_root_pointer_closure());
 633   StringTable::oops_do(adjust_root_pointer_closure());
 634   ref_processor()->weak_oops_do(adjust_root_pointer_closure());
 635   PSScavenge::reference_processor()->weak_oops_do(adjust_root_pointer_closure());
 636 
 637   adjust_marks();
 638 
 639   young_gen->adjust_pointers();
 640   old_gen->adjust_pointers();
 641   perm_gen->adjust_pointers();
 642 }
 643 
 644 void PSMarkSweep::mark_sweep_phase4() {
 645   EventMark m("4 compact heap");
 646   TraceTime tm("phase 4", PrintGCDetails && Verbose, true, gclog_or_tty);
 647   trace("4");
 648 
 649   // All pointers are now adjusted, move objects accordingly
 650 
 651   // It is imperative that we traverse perm_gen first in phase4. All
 652   // classes must be allocated earlier than their instances, and traversing
 653   // perm_gen first makes sure that all klassOops have moved to their new
 654   // location before any instance does a dispatch through it's klass!
 655   ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
 656   assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");
 657 
 658   PSYoungGen* young_gen = heap->young_gen();
 659   PSOldGen* old_gen = heap->old_gen();
 660   PSPermGen* perm_gen = heap->perm_gen();
 661 
 662   perm_gen->compact();
 663   old_gen->compact();
 664   young_gen->compact();
 665 }
 666 
 667 jlong PSMarkSweep::millis_since_last_gc() {
 668   jlong ret_val = os::javaTimeMillis() - _time_of_last_gc;
 669   // XXX See note in genCollectedHeap::millis_since_last_gc().
 670   if (ret_val < 0) {
 671     NOT_PRODUCT(warning("time warp: %d", ret_val);)
 672     return 0;
 673   }
 674   return ret_val;
 675 }
 676 
 677 void PSMarkSweep::reset_millis_since_last_gc() {
 678   _time_of_last_gc = os::javaTimeMillis();
 679 }