1 /*
   2  * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/stringTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "gc/parallel/parallelScavengeHeap.hpp"
  30 #include "gc/parallel/psAdaptiveSizePolicy.hpp"
  31 #include "gc/parallel/psMarkSweep.hpp"
  32 #include "gc/parallel/psMarkSweepDecorator.hpp"
  33 #include "gc/parallel/psOldGen.hpp"
  34 #include "gc/parallel/psScavenge.hpp"
  35 #include "gc/parallel/psYoungGen.hpp"
  36 #include "gc/serial/markSweep.hpp"
  37 #include "gc/shared/gcCause.hpp"
  38 #include "gc/shared/gcHeapSummary.hpp"
  39 #include "gc/shared/gcId.hpp"
  40 #include "gc/shared/gcLocker.inline.hpp"
  41 #include "gc/shared/gcTimer.hpp"
  42 #include "gc/shared/gcTrace.hpp"
  43 #include "gc/shared/gcTraceTime.hpp"
  44 #include "gc/shared/isGCActiveMark.hpp"
  45 #include "gc/shared/referencePolicy.hpp"
  46 #include "gc/shared/referenceProcessor.hpp"
  47 #include "gc/shared/spaceDecorator.hpp"
  48 #include "logging/log.hpp"
  49 #include "oops/oop.inline.hpp"
  50 #include "runtime/biasedLocking.hpp"
  51 #include "runtime/fprofiler.hpp"
  52 #include "runtime/safepoint.hpp"
  53 #include "runtime/vmThread.hpp"
  54 #include "services/management.hpp"
  55 #include "services/memoryService.hpp"
  56 #include "utilities/events.hpp"
  57 #include "utilities/stack.inline.hpp"
  58 
  59 elapsedTimer        PSMarkSweep::_accumulated_time;
  60 jlong               PSMarkSweep::_time_of_last_gc   = 0;
  61 CollectorCounters*  PSMarkSweep::_counters = NULL;
  62 
  63 void PSMarkSweep::initialize() {
  64   MemRegion mr = ParallelScavengeHeap::heap()->reserved_region();
  65   set_ref_processor(new ReferenceProcessor(mr));     // a vanilla ref proc
  66   _counters = new CollectorCounters("PSMarkSweep", 1);
  67 }
  68 
  69 // This method contains all heap specific policy for invoking mark sweep.
  70 // PSMarkSweep::invoke_no_policy() will only attempt to mark-sweep-compact
  71 // the heap. It will do nothing further. If we need to bail out for policy
  72 // reasons, scavenge before full gc, or any other specialized behavior, it
  73 // needs to be added here.
  74 //
  75 // Note that this method should only be called from the vm_thread while
  76 // at a safepoint!
  77 //
  78 // Note that the all_soft_refs_clear flag in the collector policy
  79 // may be true because this method can be called without intervening
  80 // activity.  For example when the heap space is tight and full measure
  81 // are being taken to free space.
  82 
  83 void PSMarkSweep::invoke(bool maximum_heap_compaction) {
  84   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
  85   assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");
  86   assert(!ParallelScavengeHeap::heap()->is_gc_active(), "not reentrant");
  87 
  88   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
  89   GCCause::Cause gc_cause = heap->gc_cause();
  90   PSAdaptiveSizePolicy* policy = heap->size_policy();
  91   IsGCActiveMark mark;
  92 
  93   if (ScavengeBeforeFullGC) {
  94     PSScavenge::invoke_no_policy();
  95   }
  96 
  97   const bool clear_all_soft_refs =
  98     heap->collector_policy()->should_clear_all_soft_refs();
  99 
 100   uint count = maximum_heap_compaction ? 1 : MarkSweepAlwaysCompactCount;
 101   UIntXFlagSetting flag_setting(MarkSweepAlwaysCompactCount, count);
 102   PSMarkSweep::invoke_no_policy(clear_all_soft_refs || maximum_heap_compaction);
 103 }
 104 
 105 // This method contains no policy. You should probably
 106 // be calling invoke() instead.
 107 bool PSMarkSweep::invoke_no_policy(bool clear_all_softrefs) {
 108   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
 109   assert(ref_processor() != NULL, "Sanity");
 110 
 111   if (GC_locker::check_active_before_gc()) {
 112     return false;
 113   }
 114 
 115   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 116   GCCause::Cause gc_cause = heap->gc_cause();
 117 
 118   GCIdMark gc_id_mark;
 119   _gc_timer->register_gc_start();
 120   _gc_tracer->report_gc_start(gc_cause, _gc_timer->gc_start());
 121 
 122   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
 123 
 124   // The scope of casr should end after code that can change
 125   // CollectorPolicy::_should_clear_all_soft_refs.
 126   ClearedAllSoftRefs casr(clear_all_softrefs, heap->collector_policy());
 127 
 128   PSYoungGen* young_gen = heap->young_gen();
 129   PSOldGen* old_gen = heap->old_gen();
 130 
 131   // Increment the invocation count
 132   heap->increment_total_collections(true /* full */);
 133 
 134   // Save information needed to minimize mangling
 135   heap->record_gen_tops_before_GC();
 136 
 137   // We need to track unique mark sweep invocations as well.
 138   _total_invocations++;
 139 
 140   heap->print_heap_before_gc();
 141   heap->trace_heap_before_gc(_gc_tracer);
 142 
 143   // Fill in TLABs
 144   heap->accumulate_statistics_all_tlabs();
 145   heap->ensure_parsability(true);  // retire TLABs
 146 
 147   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
 148     HandleMark hm;  // Discard invalid handles created during verification
 149     Universe::verify("Before GC");
 150   }
 151 
 152   // Verify object start arrays
 153   if (VerifyObjectStartArray &&
 154       VerifyBeforeGC) {
 155     old_gen->verify_object_start_array();
 156   }
 157 
 158   heap->pre_full_gc_dump(_gc_timer);
 159 
 160   // Filled in below to track the state of the young gen after the collection.
 161   bool eden_empty;
 162   bool survivors_empty;
 163   bool young_gen_empty;
 164 
 165   {
 166     HandleMark hm;
 167 
 168     GCTraceCPUTime tcpu;
 169     GCTraceTime(Info, gc) t("Pause Full", NULL, gc_cause, true);
 170     TraceCollectorStats tcs(counters());
 171     TraceMemoryManagerStats tms(true /* Full GC */,gc_cause);
 172 
 173     if (TraceOldGenTime) accumulated_time()->start();
 174 
 175     // Let the size policy know we're starting
 176     size_policy->major_collection_begin();
 177 
 178     CodeCache::gc_prologue();
 179     BiasedLocking::preserve_marks();
 180 
 181     // Capture metadata size before collection for sizing.
 182     size_t metadata_prev_used = MetaspaceAux::used_bytes();
 183 
 184     size_t old_gen_prev_used = old_gen->used_in_bytes();
 185     size_t young_gen_prev_used = young_gen->used_in_bytes();
 186 
 187     allocate_stacks();
 188 
 189 #if defined(COMPILER2) || INCLUDE_JVMCI
 190     DerivedPointerTable::clear();
 191 #endif
 192 
 193     ref_processor()->enable_discovery();
 194     ref_processor()->setup_policy(clear_all_softrefs);
 195 
 196     mark_sweep_phase1(clear_all_softrefs);
 197 
 198     mark_sweep_phase2();
 199 
 200 #if defined(COMPILER2) || INCLUDE_JVMCI
 201     // Don't add any more derived pointers during phase3
 202     assert(DerivedPointerTable::is_active(), "Sanity");
 203     DerivedPointerTable::set_active(false);
 204 #endif
 205 
 206     mark_sweep_phase3();
 207 
 208     mark_sweep_phase4();
 209 
 210     restore_marks();
 211 
 212     deallocate_stacks();
 213 
 214     if (ZapUnusedHeapArea) {
 215       // Do a complete mangle (top to end) because the usage for
 216       // scratch does not maintain a top pointer.
 217       young_gen->to_space()->mangle_unused_area_complete();
 218     }
 219 
 220     eden_empty = young_gen->eden_space()->is_empty();
 221     if (!eden_empty) {
 222       eden_empty = absorb_live_data_from_eden(size_policy, young_gen, old_gen);
 223     }
 224 
 225     // Update heap occupancy information which is used as
 226     // input to soft ref clearing policy at the next gc.
 227     Universe::update_heap_info_at_gc();
 228 
 229     survivors_empty = young_gen->from_space()->is_empty() &&
 230                       young_gen->to_space()->is_empty();
 231     young_gen_empty = eden_empty && survivors_empty;
 232 
 233     ModRefBarrierSet* modBS = barrier_set_cast<ModRefBarrierSet>(heap->barrier_set());
 234     MemRegion old_mr = heap->old_gen()->reserved();
 235     if (young_gen_empty) {
 236       modBS->clear(MemRegion(old_mr.start(), old_mr.end()));
 237     } else {
 238       modBS->invalidate(MemRegion(old_mr.start(), old_mr.end()));
 239     }
 240 
 241     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
 242     ClassLoaderDataGraph::purge();
 243     MetaspaceAux::verify_metrics();
 244 
 245     BiasedLocking::restore_marks();
 246     CodeCache::gc_epilogue();
 247     JvmtiExport::gc_epilogue();
 248 
 249 #if defined(COMPILER2) || INCLUDE_JVMCI
 250     DerivedPointerTable::update_pointers();
 251 #endif
 252 
 253     ref_processor()->enqueue_discovered_references(NULL);
 254 
 255     // Update time of last GC
 256     reset_millis_since_last_gc();
 257 
 258     // Let the size policy know we're done
 259     size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
 260 
 261     if (UseAdaptiveSizePolicy) {
 262 
 263      log_debug(gc, ergo)("AdaptiveSizeStart: collection: %d ", heap->total_collections());
 264      log_trace(gc, ergo)("old_gen_capacity: " SIZE_FORMAT " young_gen_capacity: " SIZE_FORMAT,
 265                          old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
 266 
 267       // Don't check if the size_policy is ready here.  Let
 268       // the size_policy check that internally.
 269       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
 270           AdaptiveSizePolicy::should_update_promo_stats(gc_cause)) {
 271         // Swap the survivor spaces if from_space is empty. The
 272         // resize_young_gen() called below is normally used after
 273         // a successful young GC and swapping of survivor spaces;
 274         // otherwise, it will fail to resize the young gen with
 275         // the current implementation.
 276         if (young_gen->from_space()->is_empty()) {
 277           young_gen->from_space()->clear(SpaceDecorator::Mangle);
 278           young_gen->swap_spaces();
 279         }
 280 
 281         // Calculate optimal free space amounts
 282         assert(young_gen->max_size() >
 283           young_gen->from_space()->capacity_in_bytes() +
 284           young_gen->to_space()->capacity_in_bytes(),
 285           "Sizes of space in young gen are out-of-bounds");
 286 
 287         size_t young_live = young_gen->used_in_bytes();
 288         size_t eden_live = young_gen->eden_space()->used_in_bytes();
 289         size_t old_live = old_gen->used_in_bytes();
 290         size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();
 291         size_t max_old_gen_size = old_gen->max_gen_size();
 292         size_t max_eden_size = young_gen->max_size() -
 293           young_gen->from_space()->capacity_in_bytes() -
 294           young_gen->to_space()->capacity_in_bytes();
 295 
 296         // Used for diagnostics
 297         size_policy->clear_generation_free_space_flags();
 298 
 299         size_policy->compute_generations_free_space(young_live,
 300                                                     eden_live,
 301                                                     old_live,
 302                                                     cur_eden,
 303                                                     max_old_gen_size,
 304                                                     max_eden_size,
 305                                                     true /* full gc*/);
 306 
 307         size_policy->check_gc_overhead_limit(young_live,
 308                                              eden_live,
 309                                              max_old_gen_size,
 310                                              max_eden_size,
 311                                              true /* full gc*/,
 312                                              gc_cause,
 313                                              heap->collector_policy());
 314 
 315         size_policy->decay_supplemental_growth(true /* full gc*/);
 316 
 317         heap->resize_old_gen(size_policy->calculated_old_free_size_in_bytes());
 318 
 319         heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
 320                                size_policy->calculated_survivor_size_in_bytes());
 321       }
 322       log_debug(gc, ergo)("AdaptiveSizeStop: collection: %d ", heap->total_collections());
 323     }
 324 
 325     if (UsePerfData) {
 326       heap->gc_policy_counters()->update_counters();
 327       heap->gc_policy_counters()->update_old_capacity(
 328         old_gen->capacity_in_bytes());
 329       heap->gc_policy_counters()->update_young_capacity(
 330         young_gen->capacity_in_bytes());
 331     }
 332 
 333     heap->resize_all_tlabs();
 334 
 335     // We collected the heap, recalculate the metaspace capacity
 336     MetaspaceGC::compute_new_size();
 337 
 338     if (TraceOldGenTime) accumulated_time()->stop();
 339 
 340     young_gen->print_used_change(young_gen_prev_used);
 341     old_gen->print_used_change(old_gen_prev_used);
 342     MetaspaceAux::print_metaspace_change(metadata_prev_used);
 343 
 344     // Track memory usage and detect low memory
 345     MemoryService::track_memory_usage();
 346     heap->update_counters();
 347   }
 348 
 349   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
 350     HandleMark hm;  // Discard invalid handles created during verification
 351     Universe::verify("After GC");
 352   }
 353 
 354   // Re-verify object start arrays
 355   if (VerifyObjectStartArray &&
 356       VerifyAfterGC) {
 357     old_gen->verify_object_start_array();
 358   }
 359 
 360   if (ZapUnusedHeapArea) {
 361     old_gen->object_space()->check_mangled_unused_area_complete();
 362   }
 363 
 364   NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
 365 
 366   heap->print_heap_after_gc();
 367   heap->trace_heap_after_gc(_gc_tracer);
 368 
 369   heap->post_full_gc_dump(_gc_timer);
 370 
 371 #ifdef TRACESPINNING
 372   ParallelTaskTerminator::print_termination_counts();
 373 #endif
 374 
 375   AdaptiveSizePolicyOutput::print(size_policy, heap->total_collections());
 376 
 377   _gc_timer->register_gc_end();
 378 
 379   _gc_tracer->report_gc_end(_gc_timer->gc_end(), _gc_timer->time_partitions());
 380 
 381   return true;
 382 }
 383 
 384 bool PSMarkSweep::absorb_live_data_from_eden(PSAdaptiveSizePolicy* size_policy,
 385                                              PSYoungGen* young_gen,
 386                                              PSOldGen* old_gen) {
 387   MutableSpace* const eden_space = young_gen->eden_space();
 388   assert(!eden_space->is_empty(), "eden must be non-empty");
 389   assert(young_gen->virtual_space()->alignment() ==
 390          old_gen->virtual_space()->alignment(), "alignments do not match");
 391 
 392   if (!(UseAdaptiveSizePolicy && UseAdaptiveGCBoundary)) {
 393     return false;
 394   }
 395 
 396   // Both generations must be completely committed.
 397   if (young_gen->virtual_space()->uncommitted_size() != 0) {
 398     return false;
 399   }
 400   if (old_gen->virtual_space()->uncommitted_size() != 0) {
 401     return false;
 402   }
 403 
 404   // Figure out how much to take from eden.  Include the average amount promoted
 405   // in the total; otherwise the next young gen GC will simply bail out to a
 406   // full GC.
 407   const size_t alignment = old_gen->virtual_space()->alignment();
 408   const size_t eden_used = eden_space->used_in_bytes();
 409   const size_t promoted = (size_t)size_policy->avg_promoted()->padded_average();
 410   const size_t absorb_size = align_size_up(eden_used + promoted, alignment);
 411   const size_t eden_capacity = eden_space->capacity_in_bytes();
 412 
 413   if (absorb_size >= eden_capacity) {
 414     return false; // Must leave some space in eden.
 415   }
 416 
 417   const size_t new_young_size = young_gen->capacity_in_bytes() - absorb_size;
 418   if (new_young_size < young_gen->min_gen_size()) {
 419     return false; // Respect young gen minimum size.
 420   }
 421 
 422   log_trace(heap, ergo)(" absorbing " SIZE_FORMAT "K:  "
 423                         "eden " SIZE_FORMAT "K->" SIZE_FORMAT "K "
 424                         "from " SIZE_FORMAT "K, to " SIZE_FORMAT "K "
 425                         "young_gen " SIZE_FORMAT "K->" SIZE_FORMAT "K ",
 426                         absorb_size / K,
 427                         eden_capacity / K, (eden_capacity - absorb_size) / K,
 428                         young_gen->from_space()->used_in_bytes() / K,
 429                         young_gen->to_space()->used_in_bytes() / K,
 430                         young_gen->capacity_in_bytes() / K, new_young_size / K);
 431 
 432   // Fill the unused part of the old gen.
 433   MutableSpace* const old_space = old_gen->object_space();
 434   HeapWord* const unused_start = old_space->top();
 435   size_t const unused_words = pointer_delta(old_space->end(), unused_start);
 436 
 437   if (unused_words > 0) {
 438     if (unused_words < CollectedHeap::min_fill_size()) {
 439       return false;  // If the old gen cannot be filled, must give up.
 440     }
 441     CollectedHeap::fill_with_objects(unused_start, unused_words);
 442   }
 443 
 444   // Take the live data from eden and set both top and end in the old gen to
 445   // eden top.  (Need to set end because reset_after_change() mangles the region
 446   // from end to virtual_space->high() in debug builds).
 447   HeapWord* const new_top = eden_space->top();
 448   old_gen->virtual_space()->expand_into(young_gen->virtual_space(),
 449                                         absorb_size);
 450   young_gen->reset_after_change();
 451   old_space->set_top(new_top);
 452   old_space->set_end(new_top);
 453   old_gen->reset_after_change();
 454 
 455   // Update the object start array for the filler object and the data from eden.
 456   ObjectStartArray* const start_array = old_gen->start_array();
 457   for (HeapWord* p = unused_start; p < new_top; p += oop(p)->size()) {
 458     start_array->allocate_block(p);
 459   }
 460 
 461   // Could update the promoted average here, but it is not typically updated at
 462   // full GCs and the value to use is unclear.  Something like
 463   //
 464   // cur_promoted_avg + absorb_size / number_of_scavenges_since_last_full_gc.
 465 
 466   size_policy->set_bytes_absorbed_from_eden(absorb_size);
 467   return true;
 468 }
 469 
 470 void PSMarkSweep::allocate_stacks() {
 471   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 472   PSYoungGen* young_gen = heap->young_gen();
 473 
 474   MutableSpace* to_space = young_gen->to_space();
 475   _preserved_marks = (PreservedMark*)to_space->top();
 476   _preserved_count = 0;
 477 
 478   // We want to calculate the size in bytes first.
 479   _preserved_count_max  = pointer_delta(to_space->end(), to_space->top(), sizeof(jbyte));
 480   // Now divide by the size of a PreservedMark
 481   _preserved_count_max /= sizeof(PreservedMark);
 482 }
 483 
 484 
 485 void PSMarkSweep::deallocate_stacks() {
 486   _preserved_mark_stack.clear(true);
 487   _preserved_oop_stack.clear(true);
 488   _marking_stack.clear();
 489   _objarray_stack.clear(true);
 490 }
 491 
 492 void PSMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
 493   // Recursively traverse all live objects and mark them
 494   GCTraceTime(Trace, gc) tm("Phase 1: Mark live objects", _gc_timer);
 495 
 496   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 497 
 498   // Need to clear claim bits before the tracing starts.
 499   ClassLoaderDataGraph::clear_claimed_marks();
 500 
 501   // General strong roots.
 502   {
 503     ParallelScavengeHeap::ParStrongRootsScope psrs;
 504     Universe::oops_do(mark_and_push_closure());
 505     JNIHandles::oops_do(mark_and_push_closure());   // Global (strong) JNI handles
 506     CLDToOopClosure mark_and_push_from_cld(mark_and_push_closure());
 507     MarkingCodeBlobClosure each_active_code_blob(mark_and_push_closure(), !CodeBlobToOopClosure::FixRelocations);
 508     Threads::oops_do(mark_and_push_closure(), &mark_and_push_from_cld, &each_active_code_blob);
 509     ObjectSynchronizer::oops_do(mark_and_push_closure());
 510     FlatProfiler::oops_do(mark_and_push_closure());
 511     Management::oops_do(mark_and_push_closure());
 512     JvmtiExport::oops_do(mark_and_push_closure());
 513     SystemDictionary::always_strong_oops_do(mark_and_push_closure());
 514     ClassLoaderDataGraph::always_strong_cld_do(follow_cld_closure());
 515     // Do not treat nmethods as strong roots for mark/sweep, since we can unload them.
 516     //CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure(mark_and_push_closure()));
 517   }
 518 
 519   // Flush marking stack.
 520   follow_stack();
 521 
 522   // Process reference objects found during marking
 523   {
 524     ref_processor()->setup_policy(clear_all_softrefs);
 525     const ReferenceProcessorStats& stats =
 526       ref_processor()->process_discovered_references(
 527         is_alive_closure(), mark_and_push_closure(), follow_stack_closure(), NULL, _gc_timer);
 528     gc_tracer()->report_gc_reference_stats(stats);
 529   }
 530 
 531   // This is the point where the entire marking should have completed.
 532   assert(_marking_stack.is_empty(), "Marking should have completed");
 533 
 534   // Unload classes and purge the SystemDictionary.
 535   bool purged_class = SystemDictionary::do_unloading(is_alive_closure());
 536 
 537   // Unload nmethods.
 538   CodeCache::do_unloading(is_alive_closure(), purged_class);
 539 
 540   // Prune dead klasses from subklass/sibling/implementor lists.
 541   Klass::clean_weak_klass_links(is_alive_closure());
 542 
 543   // Delete entries for dead interned strings.
 544   StringTable::unlink(is_alive_closure());
 545 
 546   // Clean up unreferenced symbols in symbol table.
 547   SymbolTable::unlink();
 548   _gc_tracer->report_object_count_after_gc(is_alive_closure());
 549 }
 550 
 551 
 552 void PSMarkSweep::mark_sweep_phase2() {
 553   GCTraceTime(Trace, gc) tm("Phase 2: Compute new object addresses", _gc_timer);
 554 
 555   // Now all live objects are marked, compute the new object addresses.
 556 
 557   // It is not required that we traverse spaces in the same order in
 558   // phase2, phase3 and phase4, but the ValidateMarkSweep live oops
 559   // tracking expects us to do so. See comment under phase4.
 560 
 561   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 562   PSOldGen* old_gen = heap->old_gen();
 563 
 564   // Begin compacting into the old gen
 565   PSMarkSweepDecorator::set_destination_decorator_tenured();
 566 
 567   // This will also compact the young gen spaces.
 568   old_gen->precompact();
 569 }
 570 
 571 // This should be moved to the shared markSweep code!
 572 class PSAlwaysTrueClosure: public BoolObjectClosure {
 573 public:
 574   bool do_object_b(oop p) { return true; }
 575 };
 576 static PSAlwaysTrueClosure always_true;
 577 
 578 void PSMarkSweep::mark_sweep_phase3() {
 579   // Adjust the pointers to reflect the new locations
 580   GCTraceTime(Trace, gc) tm("Phase 3: Adjust pointers", _gc_timer);
 581 
 582   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 583   PSYoungGen* young_gen = heap->young_gen();
 584   PSOldGen* old_gen = heap->old_gen();
 585 
 586   // Need to clear claim bits before the tracing starts.
 587   ClassLoaderDataGraph::clear_claimed_marks();
 588 
 589   // General strong roots.
 590   Universe::oops_do(adjust_pointer_closure());
 591   JNIHandles::oops_do(adjust_pointer_closure());   // Global (strong) JNI handles
 592   CLDToOopClosure adjust_from_cld(adjust_pointer_closure());
 593   Threads::oops_do(adjust_pointer_closure(), &adjust_from_cld, NULL);
 594   ObjectSynchronizer::oops_do(adjust_pointer_closure());
 595   FlatProfiler::oops_do(adjust_pointer_closure());
 596   Management::oops_do(adjust_pointer_closure());
 597   JvmtiExport::oops_do(adjust_pointer_closure());
 598   SystemDictionary::oops_do(adjust_pointer_closure());
 599   ClassLoaderDataGraph::cld_do(adjust_cld_closure());
 600 
 601   // Now adjust pointers in remaining weak roots.  (All of which should
 602   // have been cleared if they pointed to non-surviving objects.)
 603   // Global (weak) JNI handles
 604   JNIHandles::weak_oops_do(&always_true, adjust_pointer_closure());
 605 
 606   CodeBlobToOopClosure adjust_from_blobs(adjust_pointer_closure(), CodeBlobToOopClosure::FixRelocations);
 607   CodeCache::blobs_do(&adjust_from_blobs);
 608   StringTable::oops_do(adjust_pointer_closure());
 609   ref_processor()->weak_oops_do(adjust_pointer_closure());
 610   PSScavenge::reference_processor()->weak_oops_do(adjust_pointer_closure());
 611 
 612   adjust_marks();
 613 
 614   young_gen->adjust_pointers();
 615   old_gen->adjust_pointers();
 616 }
 617 
 618 void PSMarkSweep::mark_sweep_phase4() {
 619   EventMark m("4 compact heap");
 620   GCTraceTime(Trace, gc) tm("Phase 4: Move objects", _gc_timer);
 621 
 622   // All pointers are now adjusted, move objects accordingly
 623 
 624   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 625   PSYoungGen* young_gen = heap->young_gen();
 626   PSOldGen* old_gen = heap->old_gen();
 627 
 628   old_gen->compact();
 629   young_gen->compact();
 630 }
 631 
 632 jlong PSMarkSweep::millis_since_last_gc() {
 633   // We need a monotonically non-decreasing time in ms but
 634   // os::javaTimeMillis() does not guarantee monotonicity.
 635   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
 636   jlong ret_val = now - _time_of_last_gc;
 637   // XXX See note in genCollectedHeap::millis_since_last_gc().
 638   if (ret_val < 0) {
 639     NOT_PRODUCT(warning("time warp: " JLONG_FORMAT, ret_val);)
 640     return 0;
 641   }
 642   return ret_val;
 643 }
 644 
 645 void PSMarkSweep::reset_millis_since_last_gc() {
 646   // We need a monotonically non-decreasing time in ms but
 647   // os::javaTimeMillis() does not guarantee monotonicity.
 648   _time_of_last_gc = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
 649 }