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