1 /*
   2  * Copyright (c) 2000, 2014, 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/symbolTable.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "classfile/vmSymbols.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "gc_implementation/shared/collectorCounters.hpp"
  31 #include "gc_implementation/shared/gcTrace.hpp"
  32 #include "gc_implementation/shared/gcTraceTime.hpp"
  33 #include "gc_implementation/shared/vmGCOperations.hpp"
  34 #include "gc_interface/collectedHeap.inline.hpp"
  35 #include "memory/filemap.hpp"
  36 #include "memory/gcLocker.inline.hpp"
  37 #include "memory/genCollectedHeap.hpp"
  38 #include "memory/genOopClosures.inline.hpp"
  39 #include "memory/generation.inline.hpp"
  40 #include "memory/generationSpec.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "memory/sharedHeap.hpp"
  43 #include "memory/space.hpp"
  44 #include "oops/oop.inline.hpp"
  45 #include "oops/oop.inline2.hpp"
  46 #include "runtime/biasedLocking.hpp"
  47 #include "runtime/fprofiler.hpp"
  48 #include "runtime/handles.hpp"
  49 #include "runtime/handles.inline.hpp"
  50 #include "runtime/java.hpp"
  51 #include "runtime/vmThread.hpp"
  52 #include "services/memoryService.hpp"
  53 #include "utilities/vmError.hpp"
  54 #include "utilities/workgroup.hpp"
  55 #include "utilities/macros.hpp"
  56 #if INCLUDE_ALL_GCS
  57 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
  58 #include "gc_implementation/concurrentMarkSweep/vmCMSOperations.hpp"
  59 #endif // INCLUDE_ALL_GCS
  60 
  61 GenCollectedHeap* GenCollectedHeap::_gch;
  62 NOT_PRODUCT(size_t GenCollectedHeap::_skip_header_HeapWords = 0;)
  63 
  64 // The set of potentially parallel tasks in root scanning.
  65 enum GCH_strong_roots_tasks {
  66   // We probably want to parallelize both of these internally, but for now...
  67   GCH_PS_younger_gens,
  68   // Leave this one last.
  69   GCH_PS_NumElements
  70 };
  71 
  72 GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy) :
  73   SharedHeap(policy),
  74   _gen_policy(policy),
  75   _gen_process_roots_tasks(new SubTasksDone(GCH_PS_NumElements)),
  76   _full_collections_completed(0)
  77 {
  78   if (_gen_process_roots_tasks == NULL ||
  79       !_gen_process_roots_tasks->valid()) {
  80     vm_exit_during_initialization("Failed necessary allocation.");
  81   }
  82   assert(policy != NULL, "Sanity check");
  83 }
  84 
  85 jint GenCollectedHeap::initialize() {
  86   CollectedHeap::pre_initialize();
  87 
  88   int i;
  89   _n_gens = gen_policy()->number_of_generations();
  90 
  91   // While there are no constraints in the GC code that HeapWordSize
  92   // be any particular value, there are multiple other areas in the
  93   // system which believe this to be true (e.g. oop->object_size in some
  94   // cases incorrectly returns the size in wordSize units rather than
  95   // HeapWordSize).
  96   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
  97 
  98   // Allocate space for the heap.
  99 
 100   char* heap_address;
 101   size_t total_reserved = 0;
 102   int n_covered_regions = 0;
 103   ReservedSpace heap_rs;
 104 
 105   size_t heap_alignment = collector_policy()->heap_alignment();
 106 
 107   heap_address = allocate(heap_alignment, &total_reserved,
 108                           &n_covered_regions, &heap_rs);
 109 
 110   if (!heap_rs.is_reserved()) {
 111     vm_shutdown_during_initialization(
 112       "Could not reserve enough space for object heap");
 113     return JNI_ENOMEM;
 114   }
 115 
 116   initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*)(heap_rs.base() + heap_rs.size()));
 117 
 118   _rem_set = collector_policy()->create_rem_set(reserved_region(), n_covered_regions);
 119   set_barrier_set(rem_set()->bs());
 120 
 121   _gch = this;
 122 
 123   ReservedSpace young_rs = heap_rs.first_part(gen_policy()->young_gen_spec()->max_size(), false, false);
 124   _young_gen = gen_policy()->young_gen_spec()->init(young_rs, 0, rem_set());
 125   heap_rs = heap_rs.last_part(gen_policy()->young_gen_spec()->max_size());
 126 
 127   ReservedSpace old_rs = heap_rs.first_part(gen_policy()->old_gen_spec()->max_size(), false, false);
 128   _old_gen = gen_policy()->old_gen_spec()->init(old_rs, 1, rem_set());
 129   heap_rs = heap_rs.last_part(gen_policy()->old_gen_spec()->max_size());
 130 
 131   clear_incremental_collection_failed();
 132 
 133 #if INCLUDE_ALL_GCS
 134   // If we are running CMS, create the collector responsible
 135   // for collecting the CMS generations.
 136   if (collector_policy()->is_concurrent_mark_sweep_policy()) {
 137     bool success = create_cms_collector();
 138     if (!success) return JNI_ENOMEM;
 139   }
 140 #endif // INCLUDE_ALL_GCS
 141 
 142   return JNI_OK;
 143 }
 144 
 145 char* GenCollectedHeap::allocate(size_t alignment,
 146                                  size_t* _total_reserved,
 147                                  int* _n_covered_regions,
 148                                  ReservedSpace* heap_rs){
 149   const char overflow_msg[] = "The size of the object heap + VM data exceeds "
 150     "the maximum representable size";
 151 
 152   // Now figure out the total size.
 153   const size_t pageSize = UseLargePages ? os::large_page_size() : os::vm_page_size();
 154   assert(alignment % pageSize == 0, "Must be");
 155 
 156   size_t total_reserved = gen_policy()->young_gen_spec()->max_size() +
 157                           gen_policy()->old_gen_spec()->max_size();
 158   if (total_reserved < gen_policy()->young_gen_spec()->max_size() ||
 159       total_reserved < gen_policy()->old_gen_spec()->max_size()) {
 160     vm_exit_during_initialization(overflow_msg);
 161   }
 162   assert(total_reserved % alignment == 0,
 163          err_msg("Gen size; total_reserved=" SIZE_FORMAT ", alignment="
 164                  SIZE_FORMAT, total_reserved, alignment));
 165 
 166   int n_covered_regions = gen_policy()->young_gen_spec()->n_covered_regions() +
 167                           gen_policy()->old_gen_spec()->n_covered_regions();
 168 
 169   // Needed until the cardtable is fixed to have the right number
 170   // of covered regions.
 171   n_covered_regions += 2;
 172 
 173   *_total_reserved = total_reserved;
 174   *_n_covered_regions = n_covered_regions;
 175 
 176   *heap_rs = Universe::reserve_heap(total_reserved, alignment);
 177   return heap_rs->base();
 178 }
 179 
 180 void GenCollectedHeap::post_initialize() {
 181   SharedHeap::post_initialize();
 182   GenCollectorPolicy *policy = (GenCollectorPolicy *)collector_policy();
 183   guarantee(policy->is_generation_policy(), "Illegal policy type");
 184   DefNewGeneration* def_new_gen = (DefNewGeneration*) _young_gen;
 185   assert(def_new_gen->kind() == Generation::DefNew ||
 186          def_new_gen->kind() == Generation::ParNew,
 187          "Wrong generation kind");
 188 
 189   assert(_old_gen->kind() == Generation::ConcurrentMarkSweep ||
 190          _old_gen->kind() == Generation::MarkSweepCompact,
 191     "Wrong generation kind");
 192 
 193   policy->initialize_size_policy(def_new_gen->eden()->capacity(),
 194                                  _old_gen->capacity(),
 195                                  def_new_gen->from()->capacity());
 196   policy->initialize_gc_policy_counters();
 197 }
 198 
 199 void GenCollectedHeap::ref_processing_init() {
 200   SharedHeap::ref_processing_init();
 201   _young_gen->ref_processor_init();
 202   _old_gen->ref_processor_init();
 203 }
 204 
 205 size_t GenCollectedHeap::capacity() const {
 206   return _young_gen->capacity() + _old_gen->capacity();
 207 }
 208 
 209 size_t GenCollectedHeap::used() const {
 210   return _young_gen->used() + _old_gen->used();
 211 }
 212 
 213 // Save the "used_region" for generations level and lower.
 214 void GenCollectedHeap::save_used_regions(int level) {
 215   assert(level < _n_gens, "Illegal level parameter");
 216   if (level == 1) {
 217     _old_gen->save_used_region();
 218   }
 219   _young_gen->save_used_region();
 220 }
 221 
 222 size_t GenCollectedHeap::max_capacity() const {
 223   return _young_gen->max_capacity() + _old_gen->max_capacity();
 224 }
 225 
 226 // Update the _full_collections_completed counter
 227 // at the end of a stop-world full GC.
 228 unsigned int GenCollectedHeap::update_full_collections_completed() {
 229   MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
 230   assert(_full_collections_completed <= _total_full_collections,
 231          "Can't complete more collections than were started");
 232   _full_collections_completed = _total_full_collections;
 233   ml.notify_all();
 234   return _full_collections_completed;
 235 }
 236 
 237 // Update the _full_collections_completed counter, as appropriate,
 238 // at the end of a concurrent GC cycle. Note the conditional update
 239 // below to allow this method to be called by a concurrent collector
 240 // without synchronizing in any manner with the VM thread (which
 241 // may already have initiated a STW full collection "concurrently").
 242 unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) {
 243   MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
 244   assert((_full_collections_completed <= _total_full_collections) &&
 245          (count <= _total_full_collections),
 246          "Can't complete more collections than were started");
 247   if (count > _full_collections_completed) {
 248     _full_collections_completed = count;
 249     ml.notify_all();
 250   }
 251   return _full_collections_completed;
 252 }
 253 
 254 
 255 #ifndef PRODUCT
 256 // Override of memory state checking method in CollectedHeap:
 257 // Some collectors (CMS for example) can't have badHeapWordVal written
 258 // in the first two words of an object. (For instance , in the case of
 259 // CMS these words hold state used to synchronize between certain
 260 // (concurrent) GC steps and direct allocating mutators.)
 261 // The skip_header_HeapWords() method below, allows us to skip
 262 // over the requisite number of HeapWord's. Note that (for
 263 // generational collectors) this means that those many words are
 264 // skipped in each object, irrespective of the generation in which
 265 // that object lives. The resultant loss of precision seems to be
 266 // harmless and the pain of avoiding that imprecision appears somewhat
 267 // higher than we are prepared to pay for such rudimentary debugging
 268 // support.
 269 void GenCollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr,
 270                                                          size_t size) {
 271   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
 272     // We are asked to check a size in HeapWords,
 273     // but the memory is mangled in juint words.
 274     juint* start = (juint*) (addr + skip_header_HeapWords());
 275     juint* end   = (juint*) (addr + size);
 276     for (juint* slot = start; slot < end; slot += 1) {
 277       assert(*slot == badHeapWordVal,
 278              "Found non badHeapWordValue in pre-allocation check");
 279     }
 280   }
 281 }
 282 #endif
 283 
 284 HeapWord* GenCollectedHeap::attempt_allocation(size_t size,
 285                                                bool is_tlab,
 286                                                bool first_only) {
 287   HeapWord* res = NULL;
 288 
 289   if (_young_gen->should_allocate(size, is_tlab)) {
 290     res = _young_gen->allocate(size, is_tlab);
 291     if (res != NULL || first_only) {
 292       return res;
 293     }
 294   }
 295 
 296   if (_old_gen->should_allocate(size, is_tlab)) {
 297     res = _old_gen->allocate(size, is_tlab);
 298   }
 299 
 300   return res;
 301 }
 302 
 303 HeapWord* GenCollectedHeap::mem_allocate(size_t size,
 304                                          bool* gc_overhead_limit_was_exceeded) {
 305   return collector_policy()->mem_allocate_work(size,
 306                                                false /* is_tlab */,
 307                                                gc_overhead_limit_was_exceeded);
 308 }
 309 
 310 bool GenCollectedHeap::must_clear_all_soft_refs() {
 311   return _gc_cause == GCCause::_last_ditch_collection;
 312 }
 313 
 314 bool GenCollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
 315   return UseConcMarkSweepGC &&
 316          ((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||
 317           (cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent));
 318 }
 319 
 320 void GenCollectedHeap::collect_generation(Generation* gen, bool full, size_t size,
 321                                           bool is_tlab, bool run_verification, bool clear_soft_refs) {
 322   // Timer for individual generations. Last argument is false: no CR
 323   // FIXME: We should try to start the timing earlier to cover more of the GC pause
 324   // The PrintGCDetails logging starts before we have incremented the GC id. We will do that later
 325   // so we can assume here that the next GC id is what we want.
 326   GCTraceTime t1(gen->short_name(), PrintGCDetails, false, NULL, GCId::peek());
 327   TraceCollectorStats tcs(gen->counters());
 328   TraceMemoryManagerStats tmms(gen->kind(),gc_cause());
 329 
 330   size_t prev_used = gen->used();
 331   gen->stat_record()->invocations++;
 332   gen->stat_record()->accumulated_time.start();
 333 
 334   // Must be done anew before each collection because
 335   // a previous collection will do mangling and will
 336   // change top of some spaces.
 337   record_gen_tops_before_GC();
 338 
 339   if (PrintGC && Verbose) {
 340     gclog_or_tty->print("level=%d invoke=%d size=" SIZE_FORMAT,
 341                         gen->level(),
 342                         gen->stat_record()->invocations,
 343                         size * HeapWordSize);
 344   }
 345 
 346   if (run_verification && VerifyBeforeGC) {
 347     HandleMark hm;  // Discard invalid handles created during verification
 348     Universe::verify(" VerifyBeforeGC:");
 349   }
 350   COMPILER2_PRESENT(DerivedPointerTable::clear());
 351 
 352   // Do collection work
 353   {
 354     // Note on ref discovery: For what appear to be historical reasons,
 355     // GCH enables and disabled (by enqueing) refs discovery.
 356     // In the future this should be moved into the generation's
 357     // collect method so that ref discovery and enqueueing concerns
 358     // are local to a generation. The collect method could return
 359     // an appropriate indication in the case that notification on
 360     // the ref lock was needed. This will make the treatment of
 361     // weak refs more uniform (and indeed remove such concerns
 362     // from GCH). XXX
 363 
 364     HandleMark hm;  // Discard invalid handles created during gc
 365     save_marks();   // save marks for all gens
 366     // We want to discover references, but not process them yet.
 367     // This mode is disabled in process_discovered_references if the
 368     // generation does some collection work, or in
 369     // enqueue_discovered_references if the generation returns
 370     // without doing any work.
 371     ReferenceProcessor* rp = gen->ref_processor();
 372     // If the discovery of ("weak") refs in this generation is
 373     // atomic wrt other collectors in this configuration, we
 374     // are guaranteed to have empty discovered ref lists.
 375     if (rp->discovery_is_atomic()) {
 376       rp->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
 377       rp->setup_policy(clear_soft_refs);
 378     } else {
 379       // collect() below will enable discovery as appropriate
 380     }
 381     gen->collect(full, clear_soft_refs, size, is_tlab);
 382     if (!rp->enqueuing_is_done()) {
 383       rp->enqueue_discovered_references();
 384     } else {
 385       rp->set_enqueuing_is_done(false);
 386     }
 387     rp->verify_no_references_recorded();
 388   }
 389 
 390   // Determine if allocation request was met.
 391   if (size > 0) {
 392     if (!is_tlab || gen->supports_tlab_allocation()) {
 393       if (size * HeapWordSize <= gen->unsafe_max_alloc_nogc()) {
 394         size = 0;
 395       }
 396     }
 397   }
 398 
 399   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 400 
 401   gen->stat_record()->accumulated_time.stop();
 402 
 403   update_gc_stats(gen->level(), full);
 404 
 405   if (run_verification && VerifyAfterGC) {
 406     HandleMark hm;  // Discard invalid handles created during verification
 407     Universe::verify(" VerifyAfterGC:");
 408   }
 409 
 410   if (PrintGCDetails) {
 411     gclog_or_tty->print(":");
 412     gen->print_heap_change(prev_used);
 413   }
 414 }
 415 
 416 void GenCollectedHeap::do_collection(bool   full,
 417                                      bool   clear_all_soft_refs,
 418                                      size_t size,
 419                                      bool   is_tlab,
 420                                      int    max_level) {
 421   ResourceMark rm;
 422   DEBUG_ONLY(Thread* my_thread = Thread::current();)
 423 
 424   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 425   assert(my_thread->is_VM_thread() ||
 426          my_thread->is_ConcurrentGC_thread(),
 427          "incorrect thread type capability");
 428   assert(Heap_lock->is_locked(),
 429          "the requesting thread should have the Heap_lock");
 430   guarantee(!is_gc_active(), "collection is not reentrant");
 431   assert(max_level < n_gens(), "sanity check");
 432 
 433   if (GC_locker::check_active_before_gc()) {
 434     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
 435   }
 436 
 437   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
 438                           collector_policy()->should_clear_all_soft_refs();
 439 
 440   ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());
 441 
 442   const size_t metadata_prev_used = MetaspaceAux::used_bytes();
 443 
 444   print_heap_before_gc();
 445 
 446   {
 447     FlagSetting fl(_is_gc_active, true);
 448 
 449     bool complete = full && (max_level == (n_gens()-1));
 450     const char* gc_cause_prefix = complete ? "Full GC" : "GC";
 451     gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
 452     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
 453     // The PrintGCDetails logging starts before we have incremented the GC id. We will do that later
 454     // so we can assume here that the next GC id is what we want.
 455     GCTraceTime t(GCCauseString(gc_cause_prefix, gc_cause()), PrintGCDetails, false, NULL, GCId::peek());
 456 
 457     gc_prologue(complete);
 458     increment_total_collections(complete);
 459 
 460     size_t gch_prev_used = used();
 461     bool must_restore_marks_for_biased_locking = false;
 462     bool run_verification = total_collections() >= VerifyGCStartAt;
 463 
 464     if (_young_gen->performs_in_place_marking() ||
 465         _old_gen->performs_in_place_marking()) {
 466       // We want to avoid doing this for
 467       // scavenge-only collections where it's unnecessary.
 468       must_restore_marks_for_biased_locking = true;
 469       BiasedLocking::preserve_marks();
 470     }
 471 
 472     bool prepared_for_verification = false;
 473     int max_level_collected = 0;
 474     if (!(full && _old_gen->full_collects_younger_generations()) &&
 475         _young_gen->should_collect(full, size, is_tlab)) {
 476       if (run_verification && VerifyGCLevel <= 0 && VerifyBeforeGC) {
 477         prepare_for_verify();
 478         prepared_for_verification = true;
 479       }
 480       collect_generation(_young_gen, full, size, is_tlab, run_verification && VerifyGCLevel <= 0, do_clear_all_soft_refs);
 481     }
 482     if (max_level == 1 && _old_gen->should_collect(full, size, is_tlab)) {
 483       if (!complete) {
 484         // The full_collections increment was missed above.
 485         increment_total_full_collections();
 486       }
 487       pre_full_gc_dump(NULL);    // do any pre full gc dumps
 488       if (run_verification && VerifyGCLevel <= 1 && VerifyBeforeGC) {
 489         if (!prepared_for_verification) {
 490           prepare_for_verify();
 491         }
 492       }
 493       collect_generation(_old_gen, full, size, is_tlab, run_verification && VerifyGCLevel <= 1, do_clear_all_soft_refs);
 494       max_level_collected = 1;
 495     }
 496 
 497     // Update "complete" boolean wrt what actually transpired --
 498     // for instance, a promotion failure could have led to
 499     // a whole heap collection.
 500     complete = complete || (max_level_collected == n_gens() - 1);
 501 
 502     if (complete) { // We did a "major" collection
 503       // FIXME: See comment at pre_full_gc_dump call
 504       post_full_gc_dump(NULL);   // do any post full gc dumps
 505     }
 506 
 507     if (PrintGCDetails) {
 508       print_heap_change(gch_prev_used);
 509 
 510       // Print metaspace info for full GC with PrintGCDetails flag.
 511       if (complete) {
 512         MetaspaceAux::print_metaspace_change(metadata_prev_used);
 513       }
 514     }
 515 
 516     // Adjust generation sizes.
 517     if (max_level_collected == 1) {
 518       _old_gen->compute_new_size();
 519     }
 520     _young_gen->compute_new_size();
 521 
 522     if (complete) {
 523       // Delete metaspaces for unloaded class loaders and clean up loader_data graph
 524       ClassLoaderDataGraph::purge();
 525       MetaspaceAux::verify_metrics();
 526       // Resize the metaspace capacity after full collections
 527       MetaspaceGC::compute_new_size();
 528       update_full_collections_completed();
 529     }
 530 
 531     // Track memory usage and detect low memory after GC finishes
 532     MemoryService::track_memory_usage();
 533 
 534     gc_epilogue(complete);
 535 
 536     if (must_restore_marks_for_biased_locking) {
 537       BiasedLocking::restore_marks();
 538     }
 539   }
 540 
 541   print_heap_after_gc();
 542 
 543 #ifdef TRACESPINNING
 544   ParallelTaskTerminator::print_termination_counts();
 545 #endif
 546 }
 547 
 548 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {
 549   return collector_policy()->satisfy_failed_allocation(size, is_tlab);
 550 }
 551 
 552 void GenCollectedHeap::set_par_threads(uint t) {
 553   SharedHeap::set_par_threads(t);
 554   _gen_process_roots_tasks->set_n_threads(t);
 555 }
 556 
 557 void GenCollectedHeap::
 558 gen_process_roots(int level,
 559                   bool younger_gens_as_roots,
 560                   bool activate_scope,
 561                   SharedHeap::ScanningOption so,
 562                   OopsInGenClosure* not_older_gens,
 563                   OopsInGenClosure* weak_roots,
 564                   OopsInGenClosure* older_gens,
 565                   CLDClosure* cld_closure,
 566                   CLDClosure* weak_cld_closure,
 567                   CodeBlobClosure* code_closure) {
 568 
 569   // General roots.
 570   SharedHeap::process_roots(activate_scope, so,
 571                             not_older_gens, weak_roots,
 572                             cld_closure, weak_cld_closure,
 573                             code_closure);
 574 
 575   if (younger_gens_as_roots) {
 576     if (!_gen_process_roots_tasks->is_task_claimed(GCH_PS_younger_gens)) {
 577       if (level == 1) {
 578         not_older_gens->set_generation(_young_gen);
 579         _young_gen->oop_iterate(not_older_gens);
 580       }
 581       not_older_gens->reset_generation();
 582     }
 583   }
 584   // When collection is parallel, all threads get to cooperate to do
 585   // older-gen scanning.
 586   if (level == 0) {
 587     older_gens->set_generation(_old_gen);
 588     rem_set()->younger_refs_iterate(_old_gen, older_gens);
 589     older_gens->reset_generation();
 590   }
 591 
 592   _gen_process_roots_tasks->all_tasks_completed();
 593 }
 594 
 595 void GenCollectedHeap::
 596 gen_process_roots(int level,
 597                   bool younger_gens_as_roots,
 598                   bool activate_scope,
 599                   SharedHeap::ScanningOption so,
 600                   bool only_strong_roots,
 601                   OopsInGenClosure* not_older_gens,
 602                   OopsInGenClosure* older_gens,
 603                   CLDClosure* cld_closure) {
 604 
 605   const bool is_adjust_phase = !only_strong_roots && !younger_gens_as_roots;
 606 
 607   bool is_moving_collection = false;
 608   if (level == 0 || is_adjust_phase) {
 609     // young collections are always moving
 610     is_moving_collection = true;
 611   }
 612 
 613   MarkingCodeBlobClosure mark_code_closure(not_older_gens, is_moving_collection);
 614   CodeBlobClosure* code_closure = &mark_code_closure;
 615 
 616   gen_process_roots(level,
 617                     younger_gens_as_roots,
 618                     activate_scope, so,
 619                     not_older_gens, only_strong_roots ? NULL : not_older_gens,
 620                     older_gens,
 621                     cld_closure, only_strong_roots ? NULL : cld_closure,
 622                     code_closure);
 623 
 624 }
 625 
 626 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) {
 627   SharedHeap::process_weak_roots(root_closure);
 628   // "Local" "weak" refs
 629   _young_gen->ref_processor()->weak_oops_do(root_closure);
 630   _old_gen->ref_processor()->weak_oops_do(root_closure);
 631 }
 632 
 633 #define GCH_SINCE_SAVE_MARKS_ITERATE_DEFN(OopClosureType, nv_suffix)    \
 634 void GenCollectedHeap::                                                 \
 635 oop_since_save_marks_iterate(int level,                                 \
 636                              OopClosureType* cur,                       \
 637                              OopClosureType* older) {                   \
 638   if (level == 0) {                                                     \
 639     _young_gen->oop_since_save_marks_iterate##nv_suffix(cur);           \
 640     _old_gen->oop_since_save_marks_iterate##nv_suffix(older);           \
 641   } else {                                                              \
 642     _old_gen->oop_since_save_marks_iterate##nv_suffix(cur);             \
 643   }                                                                     \
 644 }
 645 
 646 ALL_SINCE_SAVE_MARKS_CLOSURES(GCH_SINCE_SAVE_MARKS_ITERATE_DEFN)
 647 
 648 #undef GCH_SINCE_SAVE_MARKS_ITERATE_DEFN
 649 
 650 bool GenCollectedHeap::no_allocs_since_save_marks(int level) {
 651   if (level == 0) {
 652     if (!_young_gen->no_allocs_since_save_marks()) return false;
 653   }
 654   if (!_old_gen->no_allocs_since_save_marks()) return false;
 655   return true;
 656 }
 657 
 658 bool GenCollectedHeap::supports_inline_contig_alloc() const {
 659   return _young_gen->supports_inline_contig_alloc();
 660 }
 661 
 662 HeapWord** GenCollectedHeap::top_addr() const {
 663   return _young_gen->top_addr();
 664 }
 665 
 666 HeapWord** GenCollectedHeap::end_addr() const {
 667   return _young_gen->end_addr();
 668 }
 669 
 670 // public collection interfaces
 671 
 672 void GenCollectedHeap::collect(GCCause::Cause cause) {
 673   if (should_do_concurrent_full_gc(cause)) {
 674 #if INCLUDE_ALL_GCS
 675     // mostly concurrent full collection
 676     collect_mostly_concurrent(cause);
 677 #else  // INCLUDE_ALL_GCS
 678     ShouldNotReachHere();
 679 #endif // INCLUDE_ALL_GCS
 680   } else if (cause == GCCause::_wb_young_gc) {
 681     // minor collection for WhiteBox API
 682     collect(cause, 0);
 683   } else {
 684 #ifdef ASSERT
 685   if (cause == GCCause::_scavenge_alot) {
 686     // minor collection only
 687     collect(cause, 0);
 688   } else {
 689     // Stop-the-world full collection
 690     collect(cause, n_gens() - 1);
 691   }
 692 #else
 693     // Stop-the-world full collection
 694     collect(cause, n_gens() - 1);
 695 #endif
 696   }
 697 }
 698 
 699 void GenCollectedHeap::collect(GCCause::Cause cause, int max_level) {
 700   // The caller doesn't have the Heap_lock
 701   assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
 702   MutexLocker ml(Heap_lock);
 703   collect_locked(cause, max_level);
 704 }
 705 
 706 void GenCollectedHeap::collect_locked(GCCause::Cause cause) {
 707   // The caller has the Heap_lock
 708   assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock");
 709   collect_locked(cause, n_gens() - 1);
 710 }
 711 
 712 // this is the private collection interface
 713 // The Heap_lock is expected to be held on entry.
 714 
 715 void GenCollectedHeap::collect_locked(GCCause::Cause cause, int max_level) {
 716   // Read the GC count while holding the Heap_lock
 717   unsigned int gc_count_before      = total_collections();
 718   unsigned int full_gc_count_before = total_full_collections();
 719   {
 720     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
 721     VM_GenCollectFull op(gc_count_before, full_gc_count_before,
 722                          cause, max_level);
 723     VMThread::execute(&op);
 724   }
 725 }
 726 
 727 #if INCLUDE_ALL_GCS
 728 bool GenCollectedHeap::create_cms_collector() {
 729 
 730   assert(_old_gen->kind() == Generation::ConcurrentMarkSweep,
 731          "Unexpected generation kinds");
 732   // Skip two header words in the block content verification
 733   NOT_PRODUCT(_skip_header_HeapWords = CMSCollector::skip_header_HeapWords();)
 734   CMSCollector* collector = new CMSCollector(
 735     (ConcurrentMarkSweepGeneration*)_old_gen,
 736     _rem_set->as_CardTableRS(),
 737     (ConcurrentMarkSweepPolicy*) collector_policy());
 738 
 739   if (collector == NULL || !collector->completed_initialization()) {
 740     if (collector) {
 741       delete collector;  // Be nice in embedded situation
 742     }
 743     vm_shutdown_during_initialization("Could not create CMS collector");
 744     return false;
 745   }
 746   return true;  // success
 747 }
 748 
 749 void GenCollectedHeap::collect_mostly_concurrent(GCCause::Cause cause) {
 750   assert(!Heap_lock->owned_by_self(), "Should not own Heap_lock");
 751 
 752   MutexLocker ml(Heap_lock);
 753   // Read the GC counts while holding the Heap_lock
 754   unsigned int full_gc_count_before = total_full_collections();
 755   unsigned int gc_count_before      = total_collections();
 756   {
 757     MutexUnlocker mu(Heap_lock);
 758     VM_GenCollectFullConcurrent op(gc_count_before, full_gc_count_before, cause);
 759     VMThread::execute(&op);
 760   }
 761 }
 762 #endif // INCLUDE_ALL_GCS
 763 
 764 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) {
 765    do_full_collection(clear_all_soft_refs, _n_gens - 1);
 766 }
 767 
 768 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs,
 769                                           int max_level) {
 770   int local_max_level;
 771   if (!incremental_collection_will_fail(false /* don't consult_young */) &&
 772       gc_cause() == GCCause::_gc_locker) {
 773     local_max_level = 0;
 774   } else {
 775     local_max_level = max_level;
 776   }
 777 
 778   do_collection(true                 /* full */,
 779                 clear_all_soft_refs  /* clear_all_soft_refs */,
 780                 0                    /* size */,
 781                 false                /* is_tlab */,
 782                 local_max_level      /* max_level */);
 783   // Hack XXX FIX ME !!!
 784   // A scavenge may not have been attempted, or may have
 785   // been attempted and failed, because the old gen was too full
 786   if (local_max_level == 0 && gc_cause() == GCCause::_gc_locker &&
 787       incremental_collection_will_fail(false /* don't consult_young */)) {
 788     if (PrintGCDetails) {
 789       gclog_or_tty->print_cr("GC locker: Trying a full collection "
 790                              "because scavenge failed");
 791     }
 792     // This time allow the old gen to be collected as well
 793     do_collection(true                 /* full */,
 794                   clear_all_soft_refs  /* clear_all_soft_refs */,
 795                   0                    /* size */,
 796                   false                /* is_tlab */,
 797                   n_gens() - 1         /* max_level */);
 798   }
 799 }
 800 
 801 bool GenCollectedHeap::is_in_young(oop p) {
 802   bool result = ((HeapWord*)p) < _old_gen->reserved().start();
 803   assert(result == _young_gen->is_in_reserved(p),
 804          err_msg("incorrect test - result=%d, p=" INTPTR_FORMAT, result, p2i((void*)p)));
 805   return result;
 806 }
 807 
 808 // Returns "TRUE" iff "p" points into the committed areas of the heap.
 809 bool GenCollectedHeap::is_in(const void* p) const {
 810   #ifndef ASSERT
 811   guarantee(VerifyBeforeGC      ||
 812             VerifyDuringGC      ||
 813             VerifyBeforeExit    ||
 814             VerifyDuringStartup ||
 815             PrintAssembly       ||
 816             tty->count() != 0   ||   // already printing
 817             VerifyAfterGC       ||
 818     VMError::fatal_error_in_progress(), "too expensive");
 819 
 820   #endif
 821   // This might be sped up with a cache of the last generation that
 822   // answered yes.
 823   if (_young_gen->is_in(p) || _old_gen->is_in(p)) {
 824     return true;
 825   }
 826   // Otherwise...
 827   return false;
 828 }
 829 
 830 #ifdef ASSERT
 831 // Don't implement this by using is_in_young().  This method is used
 832 // in some cases to check that is_in_young() is correct.
 833 bool GenCollectedHeap::is_in_partial_collection(const void* p) {
 834   assert(is_in_reserved(p) || p == NULL,
 835     "Does not work if address is non-null and outside of the heap");
 836   return p < _young_gen->reserved().end() && p != NULL;
 837 }
 838 #endif
 839 
 840 void GenCollectedHeap::oop_iterate(ExtendedOopClosure* cl) {
 841   _young_gen->oop_iterate(cl);
 842   _old_gen->oop_iterate(cl);
 843 }
 844 
 845 void GenCollectedHeap::object_iterate(ObjectClosure* cl) {
 846   _young_gen->object_iterate(cl);
 847   _old_gen->object_iterate(cl);
 848 }
 849 
 850 void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) {
 851   _young_gen->safe_object_iterate(cl);
 852   _old_gen->safe_object_iterate(cl);
 853 }
 854 
 855 Space* GenCollectedHeap::space_containing(const void* addr) const {
 856   Space* res = _young_gen->space_containing(addr);
 857   if (res != NULL) {
 858     return res;
 859   }
 860   res = _old_gen->space_containing(addr);
 861   assert(res != NULL, "Could not find containing space");
 862   return res;
 863 }
 864 
 865 HeapWord* GenCollectedHeap::block_start(const void* addr) const {
 866   assert(is_in_reserved(addr), "block_start of address outside of heap");
 867   if (_young_gen->is_in_reserved(addr)) {
 868     assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
 869     return _young_gen->block_start(addr);
 870   }
 871 
 872   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
 873   assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
 874   return _old_gen->block_start(addr);
 875 }
 876 
 877 size_t GenCollectedHeap::block_size(const HeapWord* addr) const {
 878   assert(is_in_reserved(addr), "block_size of address outside of heap");
 879   if (_young_gen->is_in_reserved(addr)) {
 880     assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
 881     return _young_gen->block_size(addr);
 882   }
 883 
 884   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
 885   assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
 886   return _old_gen->block_size(addr);
 887 }
 888 
 889 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const {
 890   assert(is_in_reserved(addr), "block_is_obj of address outside of heap");
 891   assert(block_start(addr) == addr, "addr must be a block start");
 892   if (_young_gen->is_in_reserved(addr)) {
 893     return _young_gen->block_is_obj(addr);
 894   }
 895 
 896   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
 897   return _old_gen->block_is_obj(addr);
 898 }
 899 
 900 bool GenCollectedHeap::supports_tlab_allocation() const {
 901   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 902   return _young_gen->supports_tlab_allocation();
 903 }
 904 
 905 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const {
 906   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 907   if (_young_gen->supports_tlab_allocation()) {
 908     return _young_gen->tlab_capacity();
 909   }
 910   return 0;
 911 }
 912 
 913 size_t GenCollectedHeap::tlab_used(Thread* thr) const {
 914   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 915   if (_young_gen->supports_tlab_allocation()) {
 916     return _young_gen->tlab_used();
 917   }
 918   return 0;
 919 }
 920 
 921 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const {
 922   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 923   if (_young_gen->supports_tlab_allocation()) {
 924     return _young_gen->unsafe_max_tlab_alloc();
 925   }
 926   return 0;
 927 }
 928 
 929 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t size) {
 930   bool gc_overhead_limit_was_exceeded;
 931   return collector_policy()->mem_allocate_work(size /* size */,
 932                                                true /* is_tlab */,
 933                                                &gc_overhead_limit_was_exceeded);
 934 }
 935 
 936 // Requires "*prev_ptr" to be non-NULL.  Deletes and a block of minimal size
 937 // from the list headed by "*prev_ptr".
 938 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) {
 939   bool first = true;
 940   size_t min_size = 0;   // "first" makes this conceptually infinite.
 941   ScratchBlock **smallest_ptr, *smallest;
 942   ScratchBlock  *cur = *prev_ptr;
 943   while (cur) {
 944     assert(*prev_ptr == cur, "just checking");
 945     if (first || cur->num_words < min_size) {
 946       smallest_ptr = prev_ptr;
 947       smallest     = cur;
 948       min_size     = smallest->num_words;
 949       first        = false;
 950     }
 951     prev_ptr = &cur->next;
 952     cur     =  cur->next;
 953   }
 954   smallest      = *smallest_ptr;
 955   *smallest_ptr = smallest->next;
 956   return smallest;
 957 }
 958 
 959 // Sort the scratch block list headed by res into decreasing size order,
 960 // and set "res" to the result.
 961 static void sort_scratch_list(ScratchBlock*& list) {
 962   ScratchBlock* sorted = NULL;
 963   ScratchBlock* unsorted = list;
 964   while (unsorted) {
 965     ScratchBlock *smallest = removeSmallestScratch(&unsorted);
 966     smallest->next  = sorted;
 967     sorted          = smallest;
 968   }
 969   list = sorted;
 970 }
 971 
 972 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor,
 973                                                size_t max_alloc_words) {
 974   ScratchBlock* res = NULL;
 975   _young_gen->contribute_scratch(res, requestor, max_alloc_words);
 976   _old_gen->contribute_scratch(res, requestor, max_alloc_words);
 977   sort_scratch_list(res);
 978   return res;
 979 }
 980 
 981 void GenCollectedHeap::release_scratch() {
 982   _young_gen->reset_scratch();
 983   _old_gen->reset_scratch();
 984 }
 985 
 986 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure {
 987   void do_generation(Generation* gen) {
 988     gen->prepare_for_verify();
 989   }
 990 };
 991 
 992 void GenCollectedHeap::prepare_for_verify() {
 993   ensure_parsability(false);        // no need to retire TLABs
 994   GenPrepareForVerifyClosure blk;
 995   generation_iterate(&blk, false);
 996 }
 997 
 998 void GenCollectedHeap::generation_iterate(GenClosure* cl,
 999                                           bool old_to_young) {
1000   if (old_to_young) {
1001     cl->do_generation(_old_gen);
1002     cl->do_generation(_young_gen);
1003   } else {
1004     cl->do_generation(_young_gen);
1005     cl->do_generation(_old_gen);
1006   }
1007 }
1008 
1009 void GenCollectedHeap::space_iterate(SpaceClosure* cl) {
1010   _young_gen->space_iterate(cl, true);
1011   _old_gen->space_iterate(cl, true);
1012 }
1013 
1014 bool GenCollectedHeap::is_maximal_no_gc() const {
1015   return _young_gen->is_maximal_no_gc() && _old_gen->is_maximal_no_gc();
1016 }
1017 
1018 void GenCollectedHeap::save_marks() {
1019   _young_gen->save_marks();
1020   _old_gen->save_marks();
1021 }
1022 
1023 GenCollectedHeap* GenCollectedHeap::heap() {
1024   assert(_gch != NULL, "Uninitialized access to GenCollectedHeap::heap()");
1025   assert(_gch->kind() == CollectedHeap::GenCollectedHeap, "not a generational heap");
1026   return _gch;
1027 }
1028 
1029 
1030 void GenCollectedHeap::prepare_for_compaction() {
1031   guarantee(_n_gens = 2, "Wrong number of generations");
1032   // Start by compacting into same gen.
1033   CompactPoint cp(_old_gen);
1034   _old_gen->prepare_for_compaction(&cp);
1035   _young_gen->prepare_for_compaction(&cp);
1036 }
1037 
1038 void GenCollectedHeap::verify(bool silent, VerifyOption option /* ignored */) {
1039   if (!silent) {
1040     gclog_or_tty->print("%s", _old_gen->name());
1041     gclog_or_tty->print(" ");
1042   }
1043   _old_gen->verify();
1044 
1045   if (!silent) {
1046     gclog_or_tty->print("%s", _young_gen->name());
1047     gclog_or_tty->print(" ");
1048   }
1049   _young_gen->verify();
1050 
1051   if (!silent) {
1052     gclog_or_tty->print("remset ");
1053   }
1054   rem_set()->verify();
1055 }
1056 
1057 void GenCollectedHeap::print_on(outputStream* st) const {
1058   _young_gen->print_on(st);
1059   _old_gen->print_on(st);
1060   MetaspaceAux::print_on(st);
1061 }
1062 
1063 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const {
1064   if (workers() != NULL) {
1065     workers()->threads_do(tc);
1066   }
1067 #if INCLUDE_ALL_GCS
1068   if (UseConcMarkSweepGC) {
1069     ConcurrentMarkSweepThread::threads_do(tc);
1070   }
1071 #endif // INCLUDE_ALL_GCS
1072 }
1073 
1074 void GenCollectedHeap::print_gc_threads_on(outputStream* st) const {
1075 #if INCLUDE_ALL_GCS
1076   if (UseParNewGC) {
1077     workers()->print_worker_threads_on(st);
1078   }
1079   if (UseConcMarkSweepGC) {
1080     ConcurrentMarkSweepThread::print_all_on(st);
1081   }
1082 #endif // INCLUDE_ALL_GCS
1083 }
1084 
1085 void GenCollectedHeap::print_on_error(outputStream* st) const {
1086   this->CollectedHeap::print_on_error(st);
1087 
1088 #if INCLUDE_ALL_GCS
1089   if (UseConcMarkSweepGC) {
1090     st->cr();
1091     CMSCollector::print_on_error(st);
1092   }
1093 #endif // INCLUDE_ALL_GCS
1094 }
1095 
1096 void GenCollectedHeap::print_tracing_info() const {
1097   if (TraceYoungGenTime) {
1098     _young_gen->print_summary_info();
1099   }
1100   if (TraceOldGenTime) {
1101     _old_gen->print_summary_info();
1102   }
1103 }
1104 
1105 void GenCollectedHeap::print_heap_change(size_t prev_used) const {
1106   if (PrintGCDetails && Verbose) {
1107     gclog_or_tty->print(" "  SIZE_FORMAT
1108                         "->" SIZE_FORMAT
1109                         "("  SIZE_FORMAT ")",
1110                         prev_used, used(), capacity());
1111   } else {
1112     gclog_or_tty->print(" "  SIZE_FORMAT "K"
1113                         "->" SIZE_FORMAT "K"
1114                         "("  SIZE_FORMAT "K)",
1115                         prev_used / K, used() / K, capacity() / K);
1116   }
1117 }
1118 
1119 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure {
1120  private:
1121   bool _full;
1122  public:
1123   void do_generation(Generation* gen) {
1124     gen->gc_prologue(_full);
1125   }
1126   GenGCPrologueClosure(bool full) : _full(full) {};
1127 };
1128 
1129 void GenCollectedHeap::gc_prologue(bool full) {
1130   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
1131 
1132   always_do_update_barrier = false;
1133   // Fill TLAB's and such
1134   CollectedHeap::accumulate_statistics_all_tlabs();
1135   ensure_parsability(true);   // retire TLABs
1136 
1137   // Walk generations
1138   GenGCPrologueClosure blk(full);
1139   generation_iterate(&blk, false);  // not old-to-young.
1140 };
1141 
1142 class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure {
1143  private:
1144   bool _full;
1145  public:
1146   void do_generation(Generation* gen) {
1147     gen->gc_epilogue(_full);
1148   }
1149   GenGCEpilogueClosure(bool full) : _full(full) {};
1150 };
1151 
1152 void GenCollectedHeap::gc_epilogue(bool full) {
1153 #ifdef COMPILER2
1154   assert(DerivedPointerTable::is_empty(), "derived pointer present");
1155   size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr()));
1156   guarantee(actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps");
1157 #endif /* COMPILER2 */
1158 
1159   resize_all_tlabs();
1160 
1161   GenGCEpilogueClosure blk(full);
1162   generation_iterate(&blk, false);  // not old-to-young.
1163 
1164   if (!CleanChunkPoolAsync) {
1165     Chunk::clean_chunk_pool();
1166   }
1167 
1168   MetaspaceCounters::update_performance_counters();
1169   CompressedClassSpaceCounters::update_performance_counters();
1170 
1171   always_do_update_barrier = UseConcMarkSweepGC;
1172 };
1173 
1174 #ifndef PRODUCT
1175 class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure {
1176  private:
1177  public:
1178   void do_generation(Generation* gen) {
1179     gen->record_spaces_top();
1180   }
1181 };
1182 
1183 void GenCollectedHeap::record_gen_tops_before_GC() {
1184   if (ZapUnusedHeapArea) {
1185     GenGCSaveTopsBeforeGCClosure blk;
1186     generation_iterate(&blk, false);  // not old-to-young.
1187   }
1188 }
1189 #endif  // not PRODUCT
1190 
1191 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure {
1192  public:
1193   void do_generation(Generation* gen) {
1194     gen->ensure_parsability();
1195   }
1196 };
1197 
1198 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) {
1199   CollectedHeap::ensure_parsability(retire_tlabs);
1200   GenEnsureParsabilityClosure ep_cl;
1201   generation_iterate(&ep_cl, false);
1202 }
1203 
1204 oop GenCollectedHeap::handle_failed_promotion(Generation* old_gen,
1205                                               oop obj,
1206                                               size_t obj_size) {
1207   guarantee(old_gen->level() == 1, "We only get here with an old generation");
1208   assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
1209   HeapWord* result = NULL;
1210 
1211   result = old_gen->expand_and_allocate(obj_size, false);
1212 
1213   if (result != NULL) {
1214     Copy::aligned_disjoint_words((HeapWord*)obj, result, obj_size);
1215   }
1216   return oop(result);
1217 }
1218 
1219 class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure {
1220   jlong _time;   // in ms
1221   jlong _now;    // in ms
1222 
1223  public:
1224   GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { }
1225 
1226   jlong time() { return _time; }
1227 
1228   void do_generation(Generation* gen) {
1229     _time = MIN2(_time, gen->time_of_last_gc(_now));
1230   }
1231 };
1232 
1233 jlong GenCollectedHeap::millis_since_last_gc() {
1234   // We need a monotonically non-decreasing time in ms but
1235   // os::javaTimeMillis() does not guarantee monotonicity.
1236   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
1237   GenTimeOfLastGCClosure tolgc_cl(now);
1238   // iterate over generations getting the oldest
1239   // time that a generation was collected
1240   generation_iterate(&tolgc_cl, false);
1241 
1242   // javaTimeNanos() is guaranteed to be monotonically non-decreasing
1243   // provided the underlying platform provides such a time source
1244   // (and it is bug free). So we still have to guard against getting
1245   // back a time later than 'now'.
1246   jlong retVal = now - tolgc_cl.time();
1247   if (retVal < 0) {
1248     NOT_PRODUCT(warning("time warp: "INT64_FORMAT, (int64_t) retVal);)
1249     return 0;
1250   }
1251   return retVal;
1252 }