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