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