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