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