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