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("Full GC", 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     // For PrintGCDetails
 185     size_t old_gen_prev_used = old_gen->used_in_bytes();
 186     size_t young_gen_prev_used = young_gen->used_in_bytes();
 187 
 188     allocate_stacks();
 189 
 190 #if defined(COMPILER2) || INCLUDE_JVMCI
 191     DerivedPointerTable::clear();
 192 #endif
 193 
 194     ref_processor()->enable_discovery();
 195     ref_processor()->setup_policy(clear_all_softrefs);
 196 
 197     mark_sweep_phase1(clear_all_softrefs);
 198 
 199     mark_sweep_phase2();
 200 
 201 #if defined(COMPILER2) || INCLUDE_JVMCI
 202     // Don't add any more derived pointers during phase3
 203     assert(DerivedPointerTable::is_active(), "Sanity");
 204     DerivedPointerTable::set_active(false);
 205 #endif
 206 
 207     mark_sweep_phase3();
 208 
 209     mark_sweep_phase4();
 210 
 211     restore_marks();
 212 
 213     deallocate_stacks();
 214 
 215     if (ZapUnusedHeapArea) {
 216       // Do a complete mangle (top to end) because the usage for
 217       // scratch does not maintain a top pointer.
 218       young_gen->to_space()->mangle_unused_area_complete();
 219     }
 220 
 221     eden_empty = young_gen->eden_space()->is_empty();
 222     if (!eden_empty) {
 223       eden_empty = absorb_live_data_from_eden(size_policy, young_gen, old_gen);
 224     }
 225 
 226     // Update heap occupancy information which is used as
 227     // input to soft ref clearing policy at the next gc.
 228     Universe::update_heap_info_at_gc();
 229 
 230     survivors_empty = young_gen->from_space()->is_empty() &&
 231                       young_gen->to_space()->is_empty();
 232     young_gen_empty = eden_empty && survivors_empty;
 233 
 234     ModRefBarrierSet* modBS = barrier_set_cast<ModRefBarrierSet>(heap->barrier_set());
 235     MemRegion old_mr = heap->old_gen()->reserved();
 236     if (young_gen_empty) {
 237       modBS->clear(MemRegion(old_mr.start(), old_mr.end()));
 238     } else {
 239       modBS->invalidate(MemRegion(old_mr.start(), old_mr.end()));
 240     }
 241 
 242     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
 243     ClassLoaderDataGraph::purge();
 244     MetaspaceAux::verify_metrics();
 245 
 246     BiasedLocking::restore_marks();
 247     CodeCache::gc_epilogue();
 248     JvmtiExport::gc_epilogue();
 249 
 250 #if defined(COMPILER2) || INCLUDE_JVMCI
 251     DerivedPointerTable::update_pointers();
 252 #endif
 253 
 254     ref_processor()->enqueue_discovered_references(NULL);
 255 
 256     // Update time of last GC
 257     reset_millis_since_last_gc();
 258 
 259     // Let the size policy know we're done
 260     size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
 261 
 262     if (UseAdaptiveSizePolicy) {
 263 
 264      log_debug(gc, ergo)("AdaptiveSizeStart: collection: %d ", heap->total_collections());
 265      log_trace(gc, ergo)("old_gen_capacity: " SIZE_FORMAT " young_gen_capacity: " SIZE_FORMAT,
 266                          old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
 267 
 268       // Don't check if the size_policy is ready here.  Let
 269       // the size_policy check that internally.
 270       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
 271           AdaptiveSizePolicy::should_update_promo_stats(gc_cause)) {
 272         // Swap the survivor spaces if from_space is empty. The
 273         // resize_young_gen() called below is normally used after
 274         // a successful young GC and swapping of survivor spaces;
 275         // otherwise, it will fail to resize the young gen with
 276         // the current implementation.
 277         if (young_gen->from_space()->is_empty()) {
 278           young_gen->from_space()->clear(SpaceDecorator::Mangle);
 279           young_gen->swap_spaces();
 280         }
 281 
 282         // Calculate optimal free space amounts
 283         assert(young_gen->max_size() >
 284           young_gen->from_space()->capacity_in_bytes() +
 285           young_gen->to_space()->capacity_in_bytes(),
 286           "Sizes of space in young gen are out-of-bounds");
 287 
 288         size_t young_live = young_gen->used_in_bytes();
 289         size_t eden_live = young_gen->eden_space()->used_in_bytes();
 290         size_t old_live = old_gen->used_in_bytes();
 291         size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();
 292         size_t max_old_gen_size = old_gen->max_gen_size();
 293         size_t max_eden_size = young_gen->max_size() -
 294           young_gen->from_space()->capacity_in_bytes() -
 295           young_gen->to_space()->capacity_in_bytes();
 296 
 297         // Used for diagnostics
 298         size_policy->clear_generation_free_space_flags();
 299 
 300         size_policy->compute_generations_free_space(young_live,
 301                                                     eden_live,
 302                                                     old_live,
 303                                                     cur_eden,
 304                                                     max_old_gen_size,
 305                                                     max_eden_size,
 306                                                     true /* full gc*/);
 307 
 308         size_policy->check_gc_overhead_limit(young_live,
 309                                              eden_live,
 310                                              max_old_gen_size,
 311                                              max_eden_size,
 312                                              true /* full gc*/,
 313                                              gc_cause,
 314                                              heap->collector_policy());
 315 
 316         size_policy->decay_supplemental_growth(true /* full gc*/);
 317 
 318         heap->resize_old_gen(size_policy->calculated_old_free_size_in_bytes());
 319 
 320         heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
 321                                size_policy->calculated_survivor_size_in_bytes());
 322       }
 323       log_debug(gc, ergo)("AdaptiveSizeStop: collection: %d ", heap->total_collections());
 324     }
 325 
 326     if (UsePerfData) {
 327       heap->gc_policy_counters()->update_counters();
 328       heap->gc_policy_counters()->update_old_capacity(
 329         old_gen->capacity_in_bytes());
 330       heap->gc_policy_counters()->update_young_capacity(
 331         young_gen->capacity_in_bytes());
 332     }
 333 
 334     heap->resize_all_tlabs();
 335 
 336     // We collected the heap, recalculate the metaspace capacity
 337     MetaspaceGC::compute_new_size();
 338 
 339     if (TraceOldGenTime) accumulated_time()->stop();
 340 
 341     if (PrintGC) {
 342       if (PrintGCDetails) {
 343         // Don't print a GC timestamp here.  This is after the GC so
 344         // would be confusing.
 345         young_gen->print_used_change(young_gen_prev_used);
 346         old_gen->print_used_change(old_gen_prev_used);
 347       }
 348       if (PrintGCDetails) {
 349         MetaspaceAux::print_metaspace_change(metadata_prev_used);
 350       }
 351     }
 352 
 353     // Track memory usage and detect low memory
 354     MemoryService::track_memory_usage();
 355     heap->update_counters();
 356   }
 357 
 358   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
 359     HandleMark hm;  // Discard invalid handles created during verification
 360     Universe::verify("After GC");
 361   }
 362 
 363   // Re-verify object start arrays
 364   if (VerifyObjectStartArray &&
 365       VerifyAfterGC) {
 366     old_gen->verify_object_start_array();
 367   }
 368 
 369   if (ZapUnusedHeapArea) {
 370     old_gen->object_space()->check_mangled_unused_area_complete();
 371   }
 372 
 373   NOT_PRODUCT(ref_processor()->verify_no_references_recorded());
 374 
 375   heap->print_heap_after_gc();
 376   heap->trace_heap_after_gc(_gc_tracer);
 377 
 378   heap->post_full_gc_dump(_gc_timer);
 379 
 380 #ifdef TRACESPINNING
 381   ParallelTaskTerminator::print_termination_counts();
 382 #endif
 383 
 384   AdaptiveSizePolicyOutput::print(size_policy, heap->total_collections());
 385 
 386   _gc_timer->register_gc_end();
 387 
 388   _gc_tracer->report_gc_end(_gc_timer->gc_end(), _gc_timer->time_partitions());
 389 
 390   return true;
 391 }
 392 
 393 bool PSMarkSweep::absorb_live_data_from_eden(PSAdaptiveSizePolicy* size_policy,
 394                                              PSYoungGen* young_gen,
 395                                              PSOldGen* old_gen) {
 396   MutableSpace* const eden_space = young_gen->eden_space();
 397   assert(!eden_space->is_empty(), "eden must be non-empty");
 398   assert(young_gen->virtual_space()->alignment() ==
 399          old_gen->virtual_space()->alignment(), "alignments do not match");
 400 
 401   if (!(UseAdaptiveSizePolicy && UseAdaptiveGCBoundary)) {
 402     return false;
 403   }
 404 
 405   // Both generations must be completely committed.
 406   if (young_gen->virtual_space()->uncommitted_size() != 0) {
 407     return false;
 408   }
 409   if (old_gen->virtual_space()->uncommitted_size() != 0) {
 410     return false;
 411   }
 412 
 413   // Figure out how much to take from eden.  Include the average amount promoted
 414   // in the total; otherwise the next young gen GC will simply bail out to a
 415   // full GC.
 416   const size_t alignment = old_gen->virtual_space()->alignment();
 417   const size_t eden_used = eden_space->used_in_bytes();
 418   const size_t promoted = (size_t)size_policy->avg_promoted()->padded_average();
 419   const size_t absorb_size = align_size_up(eden_used + promoted, alignment);
 420   const size_t eden_capacity = eden_space->capacity_in_bytes();
 421 
 422   if (absorb_size >= eden_capacity) {
 423     return false; // Must leave some space in eden.
 424   }
 425 
 426   const size_t new_young_size = young_gen->capacity_in_bytes() - absorb_size;
 427   if (new_young_size < young_gen->min_gen_size()) {
 428     return false; // Respect young gen minimum size.
 429   }
 430 
 431   log_trace(heap, ergo)(" absorbing " SIZE_FORMAT "K:  "
 432                         "eden " SIZE_FORMAT "K->" SIZE_FORMAT "K "
 433                         "from " SIZE_FORMAT "K, to " SIZE_FORMAT "K "
 434                         "young_gen " SIZE_FORMAT "K->" SIZE_FORMAT "K ",
 435                         absorb_size / K,
 436                         eden_capacity / K, (eden_capacity - absorb_size) / K,
 437                         young_gen->from_space()->used_in_bytes() / K,
 438                         young_gen->to_space()->used_in_bytes() / K,
 439                         young_gen->capacity_in_bytes() / K, new_young_size / K);
 440 
 441   // Fill the unused part of the old gen.
 442   MutableSpace* const old_space = old_gen->object_space();
 443   HeapWord* const unused_start = old_space->top();
 444   size_t const unused_words = pointer_delta(old_space->end(), unused_start);
 445 
 446   if (unused_words > 0) {
 447     if (unused_words < CollectedHeap::min_fill_size()) {
 448       return false;  // If the old gen cannot be filled, must give up.
 449     }
 450     CollectedHeap::fill_with_objects(unused_start, unused_words);
 451   }
 452 
 453   // Take the live data from eden and set both top and end in the old gen to
 454   // eden top.  (Need to set end because reset_after_change() mangles the region
 455   // from end to virtual_space->high() in debug builds).
 456   HeapWord* const new_top = eden_space->top();
 457   old_gen->virtual_space()->expand_into(young_gen->virtual_space(),
 458                                         absorb_size);
 459   young_gen->reset_after_change();
 460   old_space->set_top(new_top);
 461   old_space->set_end(new_top);
 462   old_gen->reset_after_change();
 463 
 464   // Update the object start array for the filler object and the data from eden.
 465   ObjectStartArray* const start_array = old_gen->start_array();
 466   for (HeapWord* p = unused_start; p < new_top; p += oop(p)->size()) {
 467     start_array->allocate_block(p);
 468   }
 469 
 470   // Could update the promoted average here, but it is not typically updated at
 471   // full GCs and the value to use is unclear.  Something like
 472   //
 473   // cur_promoted_avg + absorb_size / number_of_scavenges_since_last_full_gc.
 474 
 475   size_policy->set_bytes_absorbed_from_eden(absorb_size);
 476   return true;
 477 }
 478 
 479 void PSMarkSweep::allocate_stacks() {
 480   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 481   PSYoungGen* young_gen = heap->young_gen();
 482 
 483   MutableSpace* to_space = young_gen->to_space();
 484   _preserved_marks = (PreservedMark*)to_space->top();
 485   _preserved_count = 0;
 486 
 487   // We want to calculate the size in bytes first.
 488   _preserved_count_max  = pointer_delta(to_space->end(), to_space->top(), sizeof(jbyte));
 489   // Now divide by the size of a PreservedMark
 490   _preserved_count_max /= sizeof(PreservedMark);
 491 }
 492 
 493 
 494 void PSMarkSweep::deallocate_stacks() {
 495   _preserved_mark_stack.clear(true);
 496   _preserved_oop_stack.clear(true);
 497   _marking_stack.clear();
 498   _objarray_stack.clear(true);
 499 }
 500 
 501 void PSMarkSweep::mark_sweep_phase1(bool clear_all_softrefs) {
 502   // Recursively traverse all live objects and mark them
 503   GCTraceTime(Trace, gc) tm("phase 1: Mark live objects", _gc_timer);
 504 
 505   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 506 
 507   // Need to clear claim bits before the tracing starts.
 508   ClassLoaderDataGraph::clear_claimed_marks();
 509 
 510   // General strong roots.
 511   {
 512     ParallelScavengeHeap::ParStrongRootsScope psrs;
 513     Universe::oops_do(mark_and_push_closure());
 514     JNIHandles::oops_do(mark_and_push_closure());   // Global (strong) JNI handles
 515     CLDToOopClosure mark_and_push_from_cld(mark_and_push_closure());
 516     MarkingCodeBlobClosure each_active_code_blob(mark_and_push_closure(), !CodeBlobToOopClosure::FixRelocations);
 517     Threads::oops_do(mark_and_push_closure(), &mark_and_push_from_cld, &each_active_code_blob);
 518     ObjectSynchronizer::oops_do(mark_and_push_closure());
 519     FlatProfiler::oops_do(mark_and_push_closure());
 520     Management::oops_do(mark_and_push_closure());
 521     JvmtiExport::oops_do(mark_and_push_closure());
 522     SystemDictionary::always_strong_oops_do(mark_and_push_closure());
 523     ClassLoaderDataGraph::always_strong_cld_do(follow_cld_closure());
 524     // Do not treat nmethods as strong roots for mark/sweep, since we can unload them.
 525     //CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure(mark_and_push_closure()));
 526   }
 527 
 528   // Flush marking stack.
 529   follow_stack();
 530 
 531   // Process reference objects found during marking
 532   {
 533     ref_processor()->setup_policy(clear_all_softrefs);
 534     const ReferenceProcessorStats& stats =
 535       ref_processor()->process_discovered_references(
 536         is_alive_closure(), mark_and_push_closure(), follow_stack_closure(), NULL, _gc_timer);
 537     gc_tracer()->report_gc_reference_stats(stats);
 538   }
 539 
 540   // This is the point where the entire marking should have completed.
 541   assert(_marking_stack.is_empty(), "Marking should have completed");
 542 
 543   // Unload classes and purge the SystemDictionary.
 544   bool purged_class = SystemDictionary::do_unloading(is_alive_closure());
 545 
 546   // Unload nmethods.
 547   CodeCache::do_unloading(is_alive_closure(), purged_class);
 548 
 549   // Prune dead klasses from subklass/sibling/implementor lists.
 550   Klass::clean_weak_klass_links(is_alive_closure());
 551 
 552   // Delete entries for dead interned strings.
 553   StringTable::unlink(is_alive_closure());
 554 
 555   // Clean up unreferenced symbols in symbol table.
 556   SymbolTable::unlink();
 557   _gc_tracer->report_object_count_after_gc(is_alive_closure());
 558 }
 559 
 560 
 561 void PSMarkSweep::mark_sweep_phase2() {
 562   GCTraceTime(Trace, gc) tm("phase 2: Compute new object addresses", _gc_timer);
 563 
 564   // Now all live objects are marked, compute the new object addresses.
 565 
 566   // It is not required that we traverse spaces in the same order in
 567   // phase2, phase3 and phase4, but the ValidateMarkSweep live oops
 568   // tracking expects us to do so. See comment under phase4.
 569 
 570   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 571   PSOldGen* old_gen = heap->old_gen();
 572 
 573   // Begin compacting into the old gen
 574   PSMarkSweepDecorator::set_destination_decorator_tenured();
 575 
 576   // This will also compact the young gen spaces.
 577   old_gen->precompact();
 578 }
 579 
 580 // This should be moved to the shared markSweep code!
 581 class PSAlwaysTrueClosure: public BoolObjectClosure {
 582 public:
 583   bool do_object_b(oop p) { return true; }
 584 };
 585 static PSAlwaysTrueClosure always_true;
 586 
 587 void PSMarkSweep::mark_sweep_phase3() {
 588   // Adjust the pointers to reflect the new locations
 589   GCTraceTime(Trace, gc) tm("phase 3: Adjust pointers", _gc_timer);
 590 
 591   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 592   PSYoungGen* young_gen = heap->young_gen();
 593   PSOldGen* old_gen = heap->old_gen();
 594 
 595   // Need to clear claim bits before the tracing starts.
 596   ClassLoaderDataGraph::clear_claimed_marks();
 597 
 598   // General strong roots.
 599   Universe::oops_do(adjust_pointer_closure());
 600   JNIHandles::oops_do(adjust_pointer_closure());   // Global (strong) JNI handles
 601   CLDToOopClosure adjust_from_cld(adjust_pointer_closure());
 602   Threads::oops_do(adjust_pointer_closure(), &adjust_from_cld, NULL);
 603   ObjectSynchronizer::oops_do(adjust_pointer_closure());
 604   FlatProfiler::oops_do(adjust_pointer_closure());
 605   Management::oops_do(adjust_pointer_closure());
 606   JvmtiExport::oops_do(adjust_pointer_closure());
 607   SystemDictionary::oops_do(adjust_pointer_closure());
 608   ClassLoaderDataGraph::cld_do(adjust_cld_closure());
 609 
 610   // Now adjust pointers in remaining weak roots.  (All of which should
 611   // have been cleared if they pointed to non-surviving objects.)
 612   // Global (weak) JNI handles
 613   JNIHandles::weak_oops_do(&always_true, adjust_pointer_closure());
 614 
 615   CodeBlobToOopClosure adjust_from_blobs(adjust_pointer_closure(), CodeBlobToOopClosure::FixRelocations);
 616   CodeCache::blobs_do(&adjust_from_blobs);
 617   StringTable::oops_do(adjust_pointer_closure());
 618   ref_processor()->weak_oops_do(adjust_pointer_closure());
 619   PSScavenge::reference_processor()->weak_oops_do(adjust_pointer_closure());
 620 
 621   adjust_marks();
 622 
 623   young_gen->adjust_pointers();
 624   old_gen->adjust_pointers();
 625 }
 626 
 627 void PSMarkSweep::mark_sweep_phase4() {
 628   EventMark m("4 compact heap");
 629   GCTraceTime(Trace, gc) tm("phase 4: Move objects", _gc_timer);
 630 
 631   // All pointers are now adjusted, move objects accordingly
 632 
 633   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 634   PSYoungGen* young_gen = heap->young_gen();
 635   PSOldGen* old_gen = heap->old_gen();
 636 
 637   old_gen->compact();
 638   young_gen->compact();
 639 }
 640 
 641 jlong PSMarkSweep::millis_since_last_gc() {
 642   // We need a monotonically non-decreasing time in ms but
 643   // os::javaTimeMillis() does not guarantee monotonicity.
 644   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
 645   jlong ret_val = now - _time_of_last_gc;
 646   // XXX See note in genCollectedHeap::millis_since_last_gc().
 647   if (ret_val < 0) {
 648     NOT_PRODUCT(warning("time warp: " JLONG_FORMAT, ret_val);)
 649     return 0;
 650   }
 651   return ret_val;
 652 }
 653 
 654 void PSMarkSweep::reset_millis_since_last_gc() {
 655   // We need a monotonically non-decreasing time in ms but
 656   // os::javaTimeMillis() does not guarantee monotonicity.
 657   _time_of_last_gc = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
 658 }