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