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