1 /*
   2  * Copyright (c) 2000, 2019, 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 "aot/aotLoader.hpp"
  27 #include "classfile/classLoaderDataGraph.hpp"
  28 #include "classfile/symbolTable.hpp"
  29 #include "classfile/stringTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "code/codeCache.hpp"
  33 #include "code/icBuffer.hpp"
  34 #include "gc/serial/defNewGeneration.hpp"
  35 #include "gc/shared/adaptiveSizePolicy.hpp"
  36 #include "gc/shared/cardTableBarrierSet.hpp"
  37 #include "gc/shared/cardTableRS.hpp"
  38 #include "gc/shared/collectedHeap.inline.hpp"
  39 #include "gc/shared/collectorCounters.hpp"
  40 #include "gc/shared/gcId.hpp"
  41 #include "gc/shared/gcLocker.hpp"
  42 #include "gc/shared/gcPolicyCounters.hpp"
  43 #include "gc/shared/gcTrace.hpp"
  44 #include "gc/shared/gcTraceTime.inline.hpp"
  45 #include "gc/shared/gcVMOperations.hpp"
  46 #include "gc/shared/genCollectedHeap.hpp"
  47 #include "gc/shared/genOopClosures.inline.hpp"
  48 #include "gc/shared/generationSpec.hpp"
  49 #include "gc/shared/oopStorageParState.inline.hpp"
  50 #include "gc/shared/scavengableNMethods.hpp"
  51 #include "gc/shared/space.hpp"
  52 #include "gc/shared/strongRootsScope.hpp"
  53 #include "gc/shared/weakProcessor.hpp"
  54 #include "gc/shared/workgroup.hpp"
  55 #include "memory/filemap.hpp"
  56 #include "memory/metaspaceCounters.hpp"
  57 #include "memory/resourceArea.hpp"
  58 #include "oops/oop.inline.hpp"
  59 #include "runtime/biasedLocking.hpp"
  60 #include "runtime/flags/flagSetting.hpp"
  61 #include "runtime/handles.hpp"
  62 #include "runtime/handles.inline.hpp"
  63 #include "runtime/java.hpp"
  64 #include "runtime/vmThread.hpp"
  65 #include "services/management.hpp"
  66 #include "services/memoryService.hpp"
  67 #include "utilities/debug.hpp"
  68 #include "utilities/formatBuffer.hpp"
  69 #include "utilities/macros.hpp"
  70 #include "utilities/stack.inline.hpp"
  71 #include "utilities/vmError.hpp"
  72 
  73 GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy,
  74                                    Generation::Name young,
  75                                    Generation::Name old,
  76                                    const char* policy_counters_name) :
  77   CollectedHeap(),
  78   _young_gen_spec(new GenerationSpec(young,
  79                                      policy->initial_young_size(),
  80                                      policy->max_young_size(),
  81                                      policy->gen_alignment())),
  82   _old_gen_spec(new GenerationSpec(old,
  83                                    policy->initial_old_size(),
  84                                    policy->max_old_size(),
  85                                    policy->gen_alignment())),
  86   _rem_set(NULL),
  87   _gen_policy(policy),
  88   _soft_ref_gen_policy(),
  89   _gc_policy_counters(new GCPolicyCounters(policy_counters_name, 2, 2)),
  90   _full_collections_completed(0),
  91   _process_strong_tasks(new SubTasksDone(GCH_PS_NumElements)) {
  92 }
  93 
  94 jint GenCollectedHeap::initialize() {
  95   // While there are no constraints in the GC code that HeapWordSize
  96   // be any particular value, there are multiple other areas in the
  97   // system which believe this to be true (e.g. oop->object_size in some
  98   // cases incorrectly returns the size in wordSize units rather than
  99   // HeapWordSize).
 100   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
 101 
 102   // Allocate space for the heap.
 103 
 104   char* heap_address;
 105   ReservedSpace heap_rs;
 106 
 107   size_t heap_alignment = collector_policy()->heap_alignment();
 108 
 109   heap_address = allocate(heap_alignment, &heap_rs);
 110 
 111   if (!heap_rs.is_reserved()) {
 112     vm_shutdown_during_initialization(
 113       "Could not reserve enough space for object heap");
 114     return JNI_ENOMEM;
 115   }
 116 
 117   initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*)(heap_rs.base() + heap_rs.size()));
 118 
 119   _rem_set = create_rem_set(reserved_region());
 120   _rem_set->initialize();
 121   CardTableBarrierSet *bs = new CardTableBarrierSet(_rem_set);
 122   bs->initialize();
 123   BarrierSet::set_barrier_set(bs);
 124 
 125   ReservedSpace young_rs = heap_rs.first_part(_young_gen_spec->max_size(), false, false);
 126   _young_gen = _young_gen_spec->init(young_rs, rem_set());
 127   heap_rs = heap_rs.last_part(_young_gen_spec->max_size());
 128 
 129   ReservedSpace old_rs = heap_rs.first_part(_old_gen_spec->max_size(), false, false);
 130   _old_gen = _old_gen_spec->init(old_rs, rem_set());
 131   clear_incremental_collection_failed();
 132 
 133   return JNI_OK;
 134 }
 135 
 136 CardTableRS* GenCollectedHeap::create_rem_set(const MemRegion& reserved_region) {
 137   return new CardTableRS(reserved_region, false /* scan_concurrently */);
 138 }
 139 
 140 void GenCollectedHeap::initialize_size_policy(size_t init_eden_size,
 141                                               size_t init_promo_size,
 142                                               size_t init_survivor_size) {
 143   const double max_gc_pause_sec = ((double) MaxGCPauseMillis) / 1000.0;
 144   _size_policy = new AdaptiveSizePolicy(init_eden_size,
 145                                         init_promo_size,
 146                                         init_survivor_size,
 147                                         max_gc_pause_sec,
 148                                         GCTimeRatio);
 149 }
 150 
 151 char* GenCollectedHeap::allocate(size_t alignment,
 152                                  ReservedSpace* heap_rs){
 153   // Now figure out the total size.
 154   const size_t pageSize = UseLargePages ? os::large_page_size() : os::vm_page_size();
 155   assert(alignment % pageSize == 0, "Must be");
 156 
 157   // Check for overflow.
 158   size_t total_reserved = _young_gen_spec->max_size() + _old_gen_spec->max_size();
 159   if (total_reserved < _young_gen_spec->max_size()) {
 160     vm_exit_during_initialization("The size of the object heap + VM data exceeds "
 161                                   "the maximum representable size");
 162   }
 163   assert(total_reserved % alignment == 0,
 164          "Gen size; total_reserved=" SIZE_FORMAT ", alignment="
 165          SIZE_FORMAT, total_reserved, alignment);
 166 
 167   *heap_rs = Universe::reserve_heap(total_reserved, alignment);
 168 
 169   os::trace_page_sizes("Heap",
 170                        collector_policy()->min_heap_byte_size(),
 171                        total_reserved,
 172                        alignment,
 173                        heap_rs->base(),
 174                        heap_rs->size());
 175 
 176   return heap_rs->base();
 177 }
 178 
 179 namespace {
 180   class GenIsScavengable : public BoolObjectClosure {
 181   public:
 182     bool do_object_b(oop obj) {
 183       return GenCollectedHeap::heap()->is_in_young(obj);
 184     }
 185   };
 186 
 187   GenIsScavengable _is_scavengable;
 188 }
 189 
 190 void GenCollectedHeap::post_initialize() {
 191   CollectedHeap::post_initialize();
 192   ref_processing_init();
 193 
 194   DefNewGeneration* def_new_gen = (DefNewGeneration*)_young_gen;
 195 
 196   initialize_size_policy(def_new_gen->eden()->capacity(),
 197                          _old_gen->capacity(),
 198                          def_new_gen->from()->capacity());
 199 
 200   MarkSweep::initialize();
 201 
 202   ScavengableNMethods::initialize(&_is_scavengable);
 203 }
 204 
 205 void GenCollectedHeap::ref_processing_init() {
 206   _young_gen->ref_processor_init();
 207   _old_gen->ref_processor_init();
 208 }
 209 
 210 GenerationSpec* GenCollectedHeap::young_gen_spec() const {
 211   return _young_gen_spec;
 212 }
 213 
 214 GenerationSpec* GenCollectedHeap::old_gen_spec() const {
 215   return _old_gen_spec;
 216 }
 217 
 218 size_t GenCollectedHeap::capacity() const {
 219   return _young_gen->capacity() + _old_gen->capacity();
 220 }
 221 
 222 size_t GenCollectedHeap::used() const {
 223   return _young_gen->used() + _old_gen->used();
 224 }
 225 
 226 void GenCollectedHeap::save_used_regions() {
 227   _old_gen->save_used_region();
 228   _young_gen->save_used_region();
 229 }
 230 
 231 size_t GenCollectedHeap::max_capacity() const {
 232   return _young_gen->max_capacity() + _old_gen->max_capacity();
 233 }
 234 
 235 // Update the _full_collections_completed counter
 236 // at the end of a stop-world full GC.
 237 unsigned int GenCollectedHeap::update_full_collections_completed() {
 238   MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
 239   assert(_full_collections_completed <= _total_full_collections,
 240          "Can't complete more collections than were started");
 241   _full_collections_completed = _total_full_collections;
 242   ml.notify_all();
 243   return _full_collections_completed;
 244 }
 245 
 246 // Update the _full_collections_completed counter, as appropriate,
 247 // at the end of a concurrent GC cycle. Note the conditional update
 248 // below to allow this method to be called by a concurrent collector
 249 // without synchronizing in any manner with the VM thread (which
 250 // may already have initiated a STW full collection "concurrently").
 251 unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) {
 252   MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);
 253   assert((_full_collections_completed <= _total_full_collections) &&
 254          (count <= _total_full_collections),
 255          "Can't complete more collections than were started");
 256   if (count > _full_collections_completed) {
 257     _full_collections_completed = count;
 258     ml.notify_all();
 259   }
 260   return _full_collections_completed;
 261 }
 262 
 263 // Return true if any of the following is true:
 264 // . the allocation won't fit into the current young gen heap
 265 // . gc locker is occupied (jni critical section)
 266 // . heap memory is tight -- the most recent previous collection
 267 //   was a full collection because a partial collection (would
 268 //   have) failed and is likely to fail again
 269 bool GenCollectedHeap::should_try_older_generation_allocation(size_t word_size) const {
 270   size_t young_capacity = _young_gen->capacity_before_gc();
 271   return    (word_size > heap_word_size(young_capacity))
 272          || GCLocker::is_active_and_needs_gc()
 273          || incremental_collection_failed();
 274 }
 275 
 276 HeapWord* GenCollectedHeap::expand_heap_and_allocate(size_t size, bool   is_tlab) {
 277   HeapWord* result = NULL;
 278   if (_old_gen->should_allocate(size, is_tlab)) {
 279     result = _old_gen->expand_and_allocate(size, is_tlab);
 280   }
 281   if (result == NULL) {
 282     if (_young_gen->should_allocate(size, is_tlab)) {
 283       result = _young_gen->expand_and_allocate(size, is_tlab);
 284     }
 285   }
 286   assert(result == NULL || is_in_reserved(result), "result not in heap");
 287   return result;
 288 }
 289 
 290 HeapWord* GenCollectedHeap::mem_allocate_work(size_t size,
 291                                               bool is_tlab,
 292                                               bool* gc_overhead_limit_was_exceeded) {
 293   // In general gc_overhead_limit_was_exceeded should be false so
 294   // set it so here and reset it to true only if the gc time
 295   // limit is being exceeded as checked below.
 296   *gc_overhead_limit_was_exceeded = false;
 297 
 298   HeapWord* result = NULL;
 299 
 300   // Loop until the allocation is satisfied, or unsatisfied after GC.
 301   for (uint try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) {
 302     HandleMark hm; // Discard any handles allocated in each iteration.
 303 
 304     // First allocation attempt is lock-free.
 305     Generation *young = _young_gen;
 306     assert(young->supports_inline_contig_alloc(),
 307       "Otherwise, must do alloc within heap lock");
 308     if (young->should_allocate(size, is_tlab)) {
 309       result = young->par_allocate(size, is_tlab);
 310       if (result != NULL) {
 311         assert(is_in_reserved(result), "result not in heap");
 312         return result;
 313       }
 314     }
 315     uint gc_count_before;  // Read inside the Heap_lock locked region.
 316     {
 317       MutexLocker ml(Heap_lock);
 318       log_trace(gc, alloc)("GenCollectedHeap::mem_allocate_work: attempting locked slow path allocation");
 319       // Note that only large objects get a shot at being
 320       // allocated in later generations.
 321       bool first_only = !should_try_older_generation_allocation(size);
 322 
 323       result = attempt_allocation(size, is_tlab, first_only);
 324       if (result != NULL) {
 325         assert(is_in_reserved(result), "result not in heap");
 326         return result;
 327       }
 328 
 329       if (GCLocker::is_active_and_needs_gc()) {
 330         if (is_tlab) {
 331           return NULL;  // Caller will retry allocating individual object.
 332         }
 333         if (!is_maximal_no_gc()) {
 334           // Try and expand heap to satisfy request.
 335           result = expand_heap_and_allocate(size, is_tlab);
 336           // Result could be null if we are out of space.
 337           if (result != NULL) {
 338             return result;
 339           }
 340         }
 341 
 342         if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
 343           return NULL; // We didn't get to do a GC and we didn't get any memory.
 344         }
 345 
 346         // If this thread is not in a jni critical section, we stall
 347         // the requestor until the critical section has cleared and
 348         // GC allowed. When the critical section clears, a GC is
 349         // initiated by the last thread exiting the critical section; so
 350         // we retry the allocation sequence from the beginning of the loop,
 351         // rather than causing more, now probably unnecessary, GC attempts.
 352         JavaThread* jthr = JavaThread::current();
 353         if (!jthr->in_critical()) {
 354           MutexUnlocker mul(Heap_lock);
 355           // Wait for JNI critical section to be exited
 356           GCLocker::stall_until_clear();
 357           gclocker_stalled_count += 1;
 358           continue;
 359         } else {
 360           if (CheckJNICalls) {
 361             fatal("Possible deadlock due to allocating while"
 362                   " in jni critical section");
 363           }
 364           return NULL;
 365         }
 366       }
 367 
 368       // Read the gc count while the heap lock is held.
 369       gc_count_before = total_collections();
 370     }
 371 
 372     VM_GenCollectForAllocation op(size, is_tlab, gc_count_before);
 373     VMThread::execute(&op);
 374     if (op.prologue_succeeded()) {
 375       result = op.result();
 376       if (op.gc_locked()) {
 377          assert(result == NULL, "must be NULL if gc_locked() is true");
 378          continue;  // Retry and/or stall as necessary.
 379       }
 380 
 381       // Allocation has failed and a collection
 382       // has been done.  If the gc time limit was exceeded the
 383       // this time, return NULL so that an out-of-memory
 384       // will be thrown.  Clear gc_overhead_limit_exceeded
 385       // so that the overhead exceeded does not persist.
 386 
 387       const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
 388       const bool softrefs_clear = soft_ref_policy()->all_soft_refs_clear();
 389 
 390       if (limit_exceeded && softrefs_clear) {
 391         *gc_overhead_limit_was_exceeded = true;
 392         size_policy()->set_gc_overhead_limit_exceeded(false);
 393         if (op.result() != NULL) {
 394           CollectedHeap::fill_with_object(op.result(), size);
 395         }
 396         return NULL;
 397       }
 398       assert(result == NULL || is_in_reserved(result),
 399              "result not in heap");
 400       return result;
 401     }
 402 
 403     // Give a warning if we seem to be looping forever.
 404     if ((QueuedAllocationWarningCount > 0) &&
 405         (try_count % QueuedAllocationWarningCount == 0)) {
 406           log_warning(gc, ergo)("GenCollectedHeap::mem_allocate_work retries %d times,"
 407                                 " size=" SIZE_FORMAT " %s", try_count, size, is_tlab ? "(TLAB)" : "");
 408     }
 409   }
 410 }
 411 
 412 #ifndef PRODUCT
 413 // Override of memory state checking method in CollectedHeap:
 414 // Some collectors (CMS for example) can't have badHeapWordVal written
 415 // in the first two words of an object. (For instance , in the case of
 416 // CMS these words hold state used to synchronize between certain
 417 // (concurrent) GC steps and direct allocating mutators.)
 418 // The skip_header_HeapWords() method below, allows us to skip
 419 // over the requisite number of HeapWord's. Note that (for
 420 // generational collectors) this means that those many words are
 421 // skipped in each object, irrespective of the generation in which
 422 // that object lives. The resultant loss of precision seems to be
 423 // harmless and the pain of avoiding that imprecision appears somewhat
 424 // higher than we are prepared to pay for such rudimentary debugging
 425 // support.
 426 void GenCollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr,
 427                                                          size_t size) {
 428   if (CheckMemoryInitialization && ZapUnusedHeapArea) {
 429     // We are asked to check a size in HeapWords,
 430     // but the memory is mangled in juint words.
 431     juint* start = (juint*) (addr + skip_header_HeapWords());
 432     juint* end   = (juint*) (addr + size);
 433     for (juint* slot = start; slot < end; slot += 1) {
 434       assert(*slot == badHeapWordVal,
 435              "Found non badHeapWordValue in pre-allocation check");
 436     }
 437   }
 438 }
 439 #endif
 440 
 441 HeapWord* GenCollectedHeap::attempt_allocation(size_t size,
 442                                                bool is_tlab,
 443                                                bool first_only) {
 444   HeapWord* res = NULL;
 445 
 446   if (_young_gen->should_allocate(size, is_tlab)) {
 447     res = _young_gen->allocate(size, is_tlab);
 448     if (res != NULL || first_only) {
 449       return res;
 450     }
 451   }
 452 
 453   if (_old_gen->should_allocate(size, is_tlab)) {
 454     res = _old_gen->allocate(size, is_tlab);
 455   }
 456 
 457   return res;
 458 }
 459 
 460 HeapWord* GenCollectedHeap::mem_allocate(size_t size,
 461                                          bool* gc_overhead_limit_was_exceeded) {
 462   return mem_allocate_work(size,
 463                            false /* is_tlab */,
 464                            gc_overhead_limit_was_exceeded);
 465 }
 466 
 467 bool GenCollectedHeap::must_clear_all_soft_refs() {
 468   return _gc_cause == GCCause::_metadata_GC_clear_soft_refs ||
 469          _gc_cause == GCCause::_wb_full_gc;
 470 }
 471 
 472 void GenCollectedHeap::collect_generation(Generation* gen, bool full, size_t size,
 473                                           bool is_tlab, bool run_verification, bool clear_soft_refs,
 474                                           bool restore_marks_for_biased_locking) {
 475   FormatBuffer<> title("Collect gen: %s", gen->short_name());
 476   GCTraceTime(Trace, gc, phases) t1(title);
 477   TraceCollectorStats tcs(gen->counters());
 478   TraceMemoryManagerStats tmms(gen->gc_manager(), gc_cause());
 479 
 480   gen->stat_record()->invocations++;
 481   gen->stat_record()->accumulated_time.start();
 482 
 483   // Must be done anew before each collection because
 484   // a previous collection will do mangling and will
 485   // change top of some spaces.
 486   record_gen_tops_before_GC();
 487 
 488   log_trace(gc)("%s invoke=%d size=" SIZE_FORMAT, heap()->is_young_gen(gen) ? "Young" : "Old", gen->stat_record()->invocations, size * HeapWordSize);
 489 
 490   if (run_verification && VerifyBeforeGC) {
 491     HandleMark hm;  // Discard invalid handles created during verification
 492     Universe::verify("Before GC");
 493   }
 494   COMPILER2_PRESENT(DerivedPointerTable::clear());
 495 
 496   if (restore_marks_for_biased_locking) {
 497     // We perform this mark word preservation work lazily
 498     // because it's only at this point that we know whether we
 499     // absolutely have to do it; we want to avoid doing it for
 500     // scavenge-only collections where it's unnecessary
 501     BiasedLocking::preserve_marks();
 502   }
 503 
 504   // Do collection work
 505   {
 506     // Note on ref discovery: For what appear to be historical reasons,
 507     // GCH enables and disabled (by enqueing) refs discovery.
 508     // In the future this should be moved into the generation's
 509     // collect method so that ref discovery and enqueueing concerns
 510     // are local to a generation. The collect method could return
 511     // an appropriate indication in the case that notification on
 512     // the ref lock was needed. This will make the treatment of
 513     // weak refs more uniform (and indeed remove such concerns
 514     // from GCH). XXX
 515 
 516     HandleMark hm;  // Discard invalid handles created during gc
 517     save_marks();   // save marks for all gens
 518     // We want to discover references, but not process them yet.
 519     // This mode is disabled in process_discovered_references if the
 520     // generation does some collection work, or in
 521     // enqueue_discovered_references if the generation returns
 522     // without doing any work.
 523     ReferenceProcessor* rp = gen->ref_processor();
 524     // If the discovery of ("weak") refs in this generation is
 525     // atomic wrt other collectors in this configuration, we
 526     // are guaranteed to have empty discovered ref lists.
 527     if (rp->discovery_is_atomic()) {
 528       rp->enable_discovery();
 529       rp->setup_policy(clear_soft_refs);
 530     } else {
 531       // collect() below will enable discovery as appropriate
 532     }
 533     gen->collect(full, clear_soft_refs, size, is_tlab);
 534     if (!rp->enqueuing_is_done()) {
 535       rp->disable_discovery();
 536     } else {
 537       rp->set_enqueuing_is_done(false);
 538     }
 539     rp->verify_no_references_recorded();
 540   }
 541 
 542   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
 543 
 544   gen->stat_record()->accumulated_time.stop();
 545 
 546   update_gc_stats(gen, full);
 547 
 548   if (run_verification && VerifyAfterGC) {
 549     HandleMark hm;  // Discard invalid handles created during verification
 550     Universe::verify("After GC");
 551   }
 552 }
 553 
 554 void GenCollectedHeap::do_collection(bool           full,
 555                                      bool           clear_all_soft_refs,
 556                                      size_t         size,
 557                                      bool           is_tlab,
 558                                      GenerationType max_generation) {
 559   ResourceMark rm;
 560   DEBUG_ONLY(Thread* my_thread = Thread::current();)
 561 
 562   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 563   assert(my_thread->is_VM_thread() ||
 564          my_thread->is_ConcurrentGC_thread(),
 565          "incorrect thread type capability");
 566   assert(Heap_lock->is_locked(),
 567          "the requesting thread should have the Heap_lock");
 568   guarantee(!is_gc_active(), "collection is not reentrant");
 569 
 570   if (GCLocker::check_active_before_gc()) {
 571     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
 572   }
 573 
 574   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
 575                           soft_ref_policy()->should_clear_all_soft_refs();
 576 
 577   ClearedAllSoftRefs casr(do_clear_all_soft_refs, soft_ref_policy());
 578 
 579   const size_t metadata_prev_used = MetaspaceUtils::used_bytes();
 580 
 581 
 582   FlagSetting fl(_is_gc_active, true);
 583 
 584   bool complete = full && (max_generation == OldGen);
 585   bool old_collects_young = complete && !ScavengeBeforeFullGC;
 586   bool do_young_collection = !old_collects_young && _young_gen->should_collect(full, size, is_tlab);
 587 
 588   size_t young_prev_used = _young_gen->used();
 589   size_t old_prev_used = _old_gen->used();
 590 
 591   bool run_verification = total_collections() >= VerifyGCStartAt;
 592   bool prepared_for_verification = false;
 593   bool do_full_collection = false;
 594 
 595   if (do_young_collection) {
 596     GCIdMark gc_id_mark;
 597     GCTraceCPUTime tcpu;
 598     GCTraceTime(Info, gc) t("Pause Young", NULL, gc_cause(), true);
 599 
 600     print_heap_before_gc();
 601 
 602     if (run_verification && VerifyGCLevel <= 0 && VerifyBeforeGC) {
 603       prepare_for_verify();
 604       prepared_for_verification = true;
 605     }
 606 
 607     gc_prologue(complete);
 608     increment_total_collections(complete);
 609 
 610     collect_generation(_young_gen,
 611                        full,
 612                        size,
 613                        is_tlab,
 614                        run_verification && VerifyGCLevel <= 0,
 615                        do_clear_all_soft_refs,
 616                        false);
 617 
 618     if (size > 0 && (!is_tlab || _young_gen->supports_tlab_allocation()) &&
 619         size * HeapWordSize <= _young_gen->unsafe_max_alloc_nogc()) {
 620       // Allocation request was met by young GC.
 621       size = 0;
 622     }
 623 
 624     // Ask if young collection is enough. If so, do the final steps for young collection,
 625     // and fallthrough to the end.
 626     do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation);
 627     if (!do_full_collection) {
 628       // Adjust generation sizes.
 629       _young_gen->compute_new_size();
 630 
 631       print_heap_change(young_prev_used, old_prev_used);
 632       MetaspaceUtils::print_metaspace_change(metadata_prev_used);
 633 
 634       // Track memory usage and detect low memory after GC finishes
 635       MemoryService::track_memory_usage();
 636 
 637       gc_epilogue(complete);
 638     }
 639 
 640     print_heap_after_gc();
 641 
 642   } else {
 643     // No young collection, ask if we need to perform Full collection.
 644     do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation);
 645   }
 646 
 647   if (do_full_collection) {
 648     GCIdMark gc_id_mark;
 649     GCTraceCPUTime tcpu;
 650     GCTraceTime(Info, gc) t("Pause Full", NULL, gc_cause(), true);
 651 
 652     print_heap_before_gc();
 653 
 654     if (!prepared_for_verification && run_verification &&
 655         VerifyGCLevel <= 1 && VerifyBeforeGC) {
 656       prepare_for_verify();
 657     }
 658 
 659     if (!do_young_collection) {
 660       gc_prologue(complete);
 661       increment_total_collections(complete);
 662     }
 663 
 664     // Accounting quirk: total full collections would be incremented when "complete"
 665     // is set, by calling increment_total_collections above. However, we also need to
 666     // account Full collections that had "complete" unset.
 667     if (!complete) {
 668       increment_total_full_collections();
 669     }
 670 
 671     collect_generation(_old_gen,
 672                        full,
 673                        size,
 674                        is_tlab,
 675                        run_verification && VerifyGCLevel <= 1,
 676                        do_clear_all_soft_refs,
 677                        true);
 678 
 679     // Adjust generation sizes.
 680     _old_gen->compute_new_size();
 681     _young_gen->compute_new_size();
 682 
 683     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
 684     ClassLoaderDataGraph::purge();
 685     MetaspaceUtils::verify_metrics();
 686     // Resize the metaspace capacity after full collections
 687     MetaspaceGC::compute_new_size();
 688     update_full_collections_completed();
 689 
 690     print_heap_change(young_prev_used, old_prev_used);
 691     MetaspaceUtils::print_metaspace_change(metadata_prev_used);
 692 
 693     // Track memory usage and detect low memory after GC finishes
 694     MemoryService::track_memory_usage();
 695 
 696     // Need to tell the epilogue code we are done with Full GC, regardless what was
 697     // the initial value for "complete" flag.
 698     gc_epilogue(true);
 699 
 700     BiasedLocking::restore_marks();
 701 
 702     print_heap_after_gc();
 703   }
 704 
 705 #ifdef TRACESPINNING
 706   ParallelTaskTerminator::print_termination_counts();
 707 #endif
 708 }
 709 
 710 bool GenCollectedHeap::should_do_full_collection(size_t size, bool full, bool is_tlab,
 711                                                  GenCollectedHeap::GenerationType max_gen) const {
 712   return max_gen == OldGen && _old_gen->should_collect(full, size, is_tlab);
 713 }
 714 
 715 void GenCollectedHeap::register_nmethod(nmethod* nm) {
 716   ScavengableNMethods::register_nmethod(nm);
 717 }
 718 
 719 void GenCollectedHeap::unregister_nmethod(nmethod* nm) {
 720   ScavengableNMethods::unregister_nmethod(nm);
 721 }
 722 
 723 void GenCollectedHeap::verify_nmethod(nmethod* nm) {
 724   ScavengableNMethods::verify_nmethod(nm);
 725 }
 726 
 727 void GenCollectedHeap::flush_nmethod(nmethod* nm) {
 728   ScavengableNMethods::flush_nmethod(nm);
 729 }
 730 
 731 void GenCollectedHeap::prune_nmethods() {
 732   ScavengableNMethods::prune_nmethods();
 733 }
 734 
 735 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {
 736   GCCauseSetter x(this, GCCause::_allocation_failure);
 737   HeapWord* result = NULL;
 738 
 739   assert(size != 0, "Precondition violated");
 740   if (GCLocker::is_active_and_needs_gc()) {
 741     // GC locker is active; instead of a collection we will attempt
 742     // to expand the heap, if there's room for expansion.
 743     if (!is_maximal_no_gc()) {
 744       result = expand_heap_and_allocate(size, is_tlab);
 745     }
 746     return result;   // Could be null if we are out of space.
 747   } else if (!incremental_collection_will_fail(false /* don't consult_young */)) {
 748     // Do an incremental collection.
 749     do_collection(false,                     // full
 750                   false,                     // clear_all_soft_refs
 751                   size,                      // size
 752                   is_tlab,                   // is_tlab
 753                   GenCollectedHeap::OldGen); // max_generation
 754   } else {
 755     log_trace(gc)(" :: Trying full because partial may fail :: ");
 756     // Try a full collection; see delta for bug id 6266275
 757     // for the original code and why this has been simplified
 758     // with from-space allocation criteria modified and
 759     // such allocation moved out of the safepoint path.
 760     do_collection(true,                      // full
 761                   false,                     // clear_all_soft_refs
 762                   size,                      // size
 763                   is_tlab,                   // is_tlab
 764                   GenCollectedHeap::OldGen); // max_generation
 765   }
 766 
 767   result = attempt_allocation(size, is_tlab, false /*first_only*/);
 768 
 769   if (result != NULL) {
 770     assert(is_in_reserved(result), "result not in heap");
 771     return result;
 772   }
 773 
 774   // OK, collection failed, try expansion.
 775   result = expand_heap_and_allocate(size, is_tlab);
 776   if (result != NULL) {
 777     return result;
 778   }
 779 
 780   // If we reach this point, we're really out of memory. Try every trick
 781   // we can to reclaim memory. Force collection of soft references. Force
 782   // a complete compaction of the heap. Any additional methods for finding
 783   // free memory should be here, especially if they are expensive. If this
 784   // attempt fails, an OOM exception will be thrown.
 785   {
 786     UIntFlagSetting flag_change(MarkSweepAlwaysCompactCount, 1); // Make sure the heap is fully compacted
 787 
 788     do_collection(true,                      // full
 789                   true,                      // clear_all_soft_refs
 790                   size,                      // size
 791                   is_tlab,                   // is_tlab
 792                   GenCollectedHeap::OldGen); // max_generation
 793   }
 794 
 795   result = attempt_allocation(size, is_tlab, false /* first_only */);
 796   if (result != NULL) {
 797     assert(is_in_reserved(result), "result not in heap");
 798     return result;
 799   }
 800 
 801   assert(!soft_ref_policy()->should_clear_all_soft_refs(),
 802     "Flag should have been handled and cleared prior to this point");
 803 
 804   // What else?  We might try synchronous finalization later.  If the total
 805   // space available is large enough for the allocation, then a more
 806   // complete compaction phase than we've tried so far might be
 807   // appropriate.
 808   return NULL;
 809 }
 810 
 811 #ifdef ASSERT
 812 class AssertNonScavengableClosure: public OopClosure {
 813 public:
 814   virtual void do_oop(oop* p) {
 815     assert(!GenCollectedHeap::heap()->is_in_partial_collection(*p),
 816       "Referent should not be scavengable.");  }
 817   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
 818 };
 819 static AssertNonScavengableClosure assert_is_non_scavengable_closure;
 820 #endif
 821 
 822 void GenCollectedHeap::process_roots(StrongRootsScope* scope,
 823                                      ScanningOption so,
 824                                      OopClosure* strong_roots,
 825                                      CLDClosure* strong_cld_closure,
 826                                      CLDClosure* weak_cld_closure,
 827                                      CodeBlobToOopClosure* code_roots) {
 828   // General roots.
 829   assert(Threads::thread_claim_parity() != 0, "must have called prologue code");
 830   assert(code_roots != NULL, "code root closure should always be set");
 831   // _n_termination for _process_strong_tasks should be set up stream
 832   // in a method not running in a GC worker.  Otherwise the GC worker
 833   // could be trying to change the termination condition while the task
 834   // is executing in another GC worker.
 835 
 836   if (_process_strong_tasks->try_claim_task(GCH_PS_ClassLoaderDataGraph_oops_do)) {
 837     ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure);
 838   }
 839 
 840   // Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway
 841   CodeBlobToOopClosure* roots_from_code_p = (so & SO_AllCodeCache) ? NULL : code_roots;
 842 
 843   bool is_par = scope->n_threads() > 1;
 844   Threads::possibly_parallel_oops_do(is_par, strong_roots, roots_from_code_p);
 845 
 846   if (_process_strong_tasks->try_claim_task(GCH_PS_Universe_oops_do)) {
 847     Universe::oops_do(strong_roots);
 848   }
 849   // Global (strong) JNI handles
 850   if (_process_strong_tasks->try_claim_task(GCH_PS_JNIHandles_oops_do)) {
 851     JNIHandles::oops_do(strong_roots);
 852   }
 853 
 854   if (_process_strong_tasks->try_claim_task(GCH_PS_ObjectSynchronizer_oops_do)) {
 855     ObjectSynchronizer::oops_do(strong_roots);
 856   }
 857   if (_process_strong_tasks->try_claim_task(GCH_PS_Management_oops_do)) {
 858     Management::oops_do(strong_roots);
 859   }
 860   if (_process_strong_tasks->try_claim_task(GCH_PS_jvmti_oops_do)) {
 861     JvmtiExport::oops_do(strong_roots);
 862   }
 863   if (UseAOT && _process_strong_tasks->try_claim_task(GCH_PS_aot_oops_do)) {
 864     AOTLoader::oops_do(strong_roots);
 865   }
 866 
 867   if (_process_strong_tasks->try_claim_task(GCH_PS_SystemDictionary_oops_do)) {
 868     SystemDictionary::oops_do(strong_roots);
 869   }
 870 
 871   if (_process_strong_tasks->try_claim_task(GCH_PS_CodeCache_oops_do)) {
 872     if (so & SO_ScavengeCodeCache) {
 873       assert(code_roots != NULL, "must supply closure for code cache");
 874 
 875       // We only visit parts of the CodeCache when scavenging.
 876       ScavengableNMethods::scavengable_nmethods_do(code_roots);
 877     }
 878     if (so & SO_AllCodeCache) {
 879       assert(code_roots != NULL, "must supply closure for code cache");
 880 
 881       // CMSCollector uses this to do intermediate-strength collections.
 882       // We scan the entire code cache, since CodeCache::do_unloading is not called.
 883       CodeCache::blobs_do(code_roots);
 884     }
 885     // Verify that the code cache contents are not subject to
 886     // movement by a scavenging collection.
 887     DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, !CodeBlobToOopClosure::FixRelocations));
 888     DEBUG_ONLY(ScavengableNMethods::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable));
 889   }
 890 }
 891 
 892 void GenCollectedHeap::young_process_roots(StrongRootsScope* scope,
 893                                            OopsInGenClosure* root_closure,
 894                                            OopsInGenClosure* old_gen_closure,
 895                                            CLDClosure* cld_closure) {
 896   MarkingCodeBlobClosure mark_code_closure(root_closure, CodeBlobToOopClosure::FixRelocations);
 897 
 898   process_roots(scope, SO_ScavengeCodeCache, root_closure,
 899                 cld_closure, cld_closure, &mark_code_closure);
 900 
 901   if (_process_strong_tasks->try_claim_task(GCH_PS_younger_gens)) {
 902     root_closure->reset_generation();
 903   }
 904 
 905   // When collection is parallel, all threads get to cooperate to do
 906   // old generation scanning.
 907   old_gen_closure->set_generation(_old_gen);
 908   rem_set()->younger_refs_iterate(_old_gen, old_gen_closure, scope->n_threads());
 909   old_gen_closure->reset_generation();
 910 
 911   _process_strong_tasks->all_tasks_completed(scope->n_threads());
 912 }
 913 
 914 void GenCollectedHeap::full_process_roots(StrongRootsScope* scope,
 915                                           bool is_adjust_phase,
 916                                           ScanningOption so,
 917                                           bool only_strong_roots,
 918                                           OopsInGenClosure* root_closure,
 919                                           CLDClosure* cld_closure) {
 920   MarkingCodeBlobClosure mark_code_closure(root_closure, is_adjust_phase);
 921   CLDClosure* weak_cld_closure = only_strong_roots ? NULL : cld_closure;
 922 
 923   process_roots(scope, so, root_closure, cld_closure, weak_cld_closure, &mark_code_closure);
 924   _process_strong_tasks->all_tasks_completed(scope->n_threads());
 925 }
 926 
 927 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) {
 928   WeakProcessor::oops_do(root_closure);
 929   _young_gen->ref_processor()->weak_oops_do(root_closure);
 930   _old_gen->ref_processor()->weak_oops_do(root_closure);
 931 }
 932 
 933 bool GenCollectedHeap::no_allocs_since_save_marks() {
 934   return _young_gen->no_allocs_since_save_marks() &&
 935          _old_gen->no_allocs_since_save_marks();
 936 }
 937 
 938 bool GenCollectedHeap::supports_inline_contig_alloc() const {
 939   return _young_gen->supports_inline_contig_alloc();
 940 }
 941 
 942 HeapWord* volatile* GenCollectedHeap::top_addr() const {
 943   return _young_gen->top_addr();
 944 }
 945 
 946 HeapWord** GenCollectedHeap::end_addr() const {
 947   return _young_gen->end_addr();
 948 }
 949 
 950 // public collection interfaces
 951 
 952 void GenCollectedHeap::collect(GCCause::Cause cause) {
 953   if (cause == GCCause::_wb_young_gc) {
 954     // Young collection for the WhiteBox API.
 955     collect(cause, YoungGen);
 956   } else {
 957 #ifdef ASSERT
 958   if (cause == GCCause::_scavenge_alot) {
 959     // Young collection only.
 960     collect(cause, YoungGen);
 961   } else {
 962     // Stop-the-world full collection.
 963     collect(cause, OldGen);
 964   }
 965 #else
 966     // Stop-the-world full collection.
 967     collect(cause, OldGen);
 968 #endif
 969   }
 970 }
 971 
 972 void GenCollectedHeap::collect(GCCause::Cause cause, GenerationType max_generation) {
 973   // The caller doesn't have the Heap_lock
 974   assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
 975   MutexLocker ml(Heap_lock);
 976   collect_locked(cause, max_generation);
 977 }
 978 
 979 void GenCollectedHeap::collect_locked(GCCause::Cause cause) {
 980   // The caller has the Heap_lock
 981   assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock");
 982   collect_locked(cause, OldGen);
 983 }
 984 
 985 // this is the private collection interface
 986 // The Heap_lock is expected to be held on entry.
 987 
 988 void GenCollectedHeap::collect_locked(GCCause::Cause cause, GenerationType max_generation) {
 989   // Read the GC count while holding the Heap_lock
 990   unsigned int gc_count_before      = total_collections();
 991   unsigned int full_gc_count_before = total_full_collections();
 992   {
 993     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
 994     VM_GenCollectFull op(gc_count_before, full_gc_count_before,
 995                          cause, max_generation);
 996     VMThread::execute(&op);
 997   }
 998 }
 999 
1000 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1001    do_full_collection(clear_all_soft_refs, OldGen);
1002 }
1003 
1004 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs,
1005                                           GenerationType last_generation) {
1006   GenerationType local_last_generation;
1007   if (!incremental_collection_will_fail(false /* don't consult_young */) &&
1008       gc_cause() == GCCause::_gc_locker) {
1009     local_last_generation = YoungGen;
1010   } else {
1011     local_last_generation = last_generation;
1012   }
1013 
1014   do_collection(true,                   // full
1015                 clear_all_soft_refs,    // clear_all_soft_refs
1016                 0,                      // size
1017                 false,                  // is_tlab
1018                 local_last_generation); // last_generation
1019   // Hack XXX FIX ME !!!
1020   // A scavenge may not have been attempted, or may have
1021   // been attempted and failed, because the old gen was too full
1022   if (local_last_generation == YoungGen && gc_cause() == GCCause::_gc_locker &&
1023       incremental_collection_will_fail(false /* don't consult_young */)) {
1024     log_debug(gc, jni)("GC locker: Trying a full collection because scavenge failed");
1025     // This time allow the old gen to be collected as well
1026     do_collection(true,                // full
1027                   clear_all_soft_refs, // clear_all_soft_refs
1028                   0,                   // size
1029                   false,               // is_tlab
1030                   OldGen);             // last_generation
1031   }
1032 }
1033 
1034 bool GenCollectedHeap::is_in_young(oop p) {
1035   bool result = ((HeapWord*)p) < _old_gen->reserved().start();
1036   assert(result == _young_gen->is_in_reserved(p),
1037          "incorrect test - result=%d, p=" INTPTR_FORMAT, result, p2i((void*)p));
1038   return result;
1039 }
1040 
1041 // Returns "TRUE" iff "p" points into the committed areas of the heap.
1042 bool GenCollectedHeap::is_in(const void* p) const {
1043   return _young_gen->is_in(p) || _old_gen->is_in(p);
1044 }
1045 
1046 #ifdef ASSERT
1047 // Don't implement this by using is_in_young().  This method is used
1048 // in some cases to check that is_in_young() is correct.
1049 bool GenCollectedHeap::is_in_partial_collection(const void* p) {
1050   assert(is_in_reserved(p) || p == NULL,
1051     "Does not work if address is non-null and outside of the heap");
1052   return p < _young_gen->reserved().end() && p != NULL;
1053 }
1054 #endif
1055 
1056 void GenCollectedHeap::oop_iterate(OopIterateClosure* cl) {
1057   _young_gen->oop_iterate(cl);
1058   _old_gen->oop_iterate(cl);
1059 }
1060 
1061 void GenCollectedHeap::object_iterate(ObjectClosure* cl) {
1062   _young_gen->object_iterate(cl);
1063   _old_gen->object_iterate(cl);
1064 }
1065 
1066 void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) {
1067   _young_gen->safe_object_iterate(cl);
1068   _old_gen->safe_object_iterate(cl);
1069 }
1070 
1071 Space* GenCollectedHeap::space_containing(const void* addr) const {
1072   Space* res = _young_gen->space_containing(addr);
1073   if (res != NULL) {
1074     return res;
1075   }
1076   res = _old_gen->space_containing(addr);
1077   assert(res != NULL, "Could not find containing space");
1078   return res;
1079 }
1080 
1081 HeapWord* GenCollectedHeap::block_start(const void* addr) const {
1082   assert(is_in_reserved(addr), "block_start of address outside of heap");
1083   if (_young_gen->is_in_reserved(addr)) {
1084     assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
1085     return _young_gen->block_start(addr);
1086   }
1087 
1088   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
1089   assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
1090   return _old_gen->block_start(addr);
1091 }
1092 
1093 size_t GenCollectedHeap::block_size(const HeapWord* addr) const {
1094   assert(is_in_reserved(addr), "block_size of address outside of heap");
1095   if (_young_gen->is_in_reserved(addr)) {
1096     assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
1097     return _young_gen->block_size(addr);
1098   }
1099 
1100   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
1101   assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
1102   return _old_gen->block_size(addr);
1103 }
1104 
1105 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const {
1106   assert(is_in_reserved(addr), "block_is_obj of address outside of heap");
1107   assert(block_start(addr) == addr, "addr must be a block start");
1108   if (_young_gen->is_in_reserved(addr)) {
1109     return _young_gen->block_is_obj(addr);
1110   }
1111 
1112   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
1113   return _old_gen->block_is_obj(addr);
1114 }
1115 
1116 bool GenCollectedHeap::supports_tlab_allocation() const {
1117   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
1118   return _young_gen->supports_tlab_allocation();
1119 }
1120 
1121 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const {
1122   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
1123   if (_young_gen->supports_tlab_allocation()) {
1124     return _young_gen->tlab_capacity();
1125   }
1126   return 0;
1127 }
1128 
1129 size_t GenCollectedHeap::tlab_used(Thread* thr) const {
1130   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
1131   if (_young_gen->supports_tlab_allocation()) {
1132     return _young_gen->tlab_used();
1133   }
1134   return 0;
1135 }
1136 
1137 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const {
1138   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
1139   if (_young_gen->supports_tlab_allocation()) {
1140     return _young_gen->unsafe_max_tlab_alloc();
1141   }
1142   return 0;
1143 }
1144 
1145 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t min_size,
1146                                               size_t requested_size,
1147                                               size_t* actual_size) {
1148   bool gc_overhead_limit_was_exceeded;
1149   HeapWord* result = mem_allocate_work(requested_size /* size */,
1150                                        true /* is_tlab */,
1151                                        &gc_overhead_limit_was_exceeded);
1152   if (result != NULL) {
1153     *actual_size = requested_size;
1154   }
1155 
1156   return result;
1157 }
1158 
1159 // Requires "*prev_ptr" to be non-NULL.  Deletes and a block of minimal size
1160 // from the list headed by "*prev_ptr".
1161 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) {
1162   bool first = true;
1163   size_t min_size = 0;   // "first" makes this conceptually infinite.
1164   ScratchBlock **smallest_ptr, *smallest;
1165   ScratchBlock  *cur = *prev_ptr;
1166   while (cur) {
1167     assert(*prev_ptr == cur, "just checking");
1168     if (first || cur->num_words < min_size) {
1169       smallest_ptr = prev_ptr;
1170       smallest     = cur;
1171       min_size     = smallest->num_words;
1172       first        = false;
1173     }
1174     prev_ptr = &cur->next;
1175     cur     =  cur->next;
1176   }
1177   smallest      = *smallest_ptr;
1178   *smallest_ptr = smallest->next;
1179   return smallest;
1180 }
1181 
1182 // Sort the scratch block list headed by res into decreasing size order,
1183 // and set "res" to the result.
1184 static void sort_scratch_list(ScratchBlock*& list) {
1185   ScratchBlock* sorted = NULL;
1186   ScratchBlock* unsorted = list;
1187   while (unsorted) {
1188     ScratchBlock *smallest = removeSmallestScratch(&unsorted);
1189     smallest->next  = sorted;
1190     sorted          = smallest;
1191   }
1192   list = sorted;
1193 }
1194 
1195 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor,
1196                                                size_t max_alloc_words) {
1197   ScratchBlock* res = NULL;
1198   _young_gen->contribute_scratch(res, requestor, max_alloc_words);
1199   _old_gen->contribute_scratch(res, requestor, max_alloc_words);
1200   sort_scratch_list(res);
1201   return res;
1202 }
1203 
1204 void GenCollectedHeap::release_scratch() {
1205   _young_gen->reset_scratch();
1206   _old_gen->reset_scratch();
1207 }
1208 
1209 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure {
1210   void do_generation(Generation* gen) {
1211     gen->prepare_for_verify();
1212   }
1213 };
1214 
1215 void GenCollectedHeap::prepare_for_verify() {
1216   ensure_parsability(false);        // no need to retire TLABs
1217   GenPrepareForVerifyClosure blk;
1218   generation_iterate(&blk, false);
1219 }
1220 
1221 void GenCollectedHeap::generation_iterate(GenClosure* cl,
1222                                           bool old_to_young) {
1223   if (old_to_young) {
1224     cl->do_generation(_old_gen);
1225     cl->do_generation(_young_gen);
1226   } else {
1227     cl->do_generation(_young_gen);
1228     cl->do_generation(_old_gen);
1229   }
1230 }
1231 
1232 bool GenCollectedHeap::is_maximal_no_gc() const {
1233   return _young_gen->is_maximal_no_gc() && _old_gen->is_maximal_no_gc();
1234 }
1235 
1236 void GenCollectedHeap::save_marks() {
1237   _young_gen->save_marks();
1238   _old_gen->save_marks();
1239 }
1240 
1241 GenCollectedHeap* GenCollectedHeap::heap() {
1242   CollectedHeap* heap = Universe::heap();
1243   assert(heap != NULL, "Uninitialized access to GenCollectedHeap::heap()");
1244   assert(heap->kind() == CollectedHeap::Serial ||
1245          heap->kind() == CollectedHeap::CMS, "Invalid name");
1246   return (GenCollectedHeap*) heap;
1247 }
1248 
1249 #if INCLUDE_SERIALGC
1250 void GenCollectedHeap::prepare_for_compaction() {
1251   // Start by compacting into same gen.
1252   CompactPoint cp(_old_gen);
1253   _old_gen->prepare_for_compaction(&cp);
1254   _young_gen->prepare_for_compaction(&cp);
1255 }
1256 #endif // INCLUDE_SERIALGC
1257 
1258 void GenCollectedHeap::verify(VerifyOption option /* ignored */) {
1259   log_debug(gc, verify)("%s", _old_gen->name());
1260   _old_gen->verify();
1261 
1262   log_debug(gc, verify)("%s", _old_gen->name());
1263   _young_gen->verify();
1264 
1265   log_debug(gc, verify)("RemSet");
1266   rem_set()->verify();
1267 }
1268 
1269 void GenCollectedHeap::print_on(outputStream* st) const {
1270   _young_gen->print_on(st);
1271   _old_gen->print_on(st);
1272   MetaspaceUtils::print_on(st);
1273 }
1274 
1275 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const {
1276 }
1277 
1278 void GenCollectedHeap::print_gc_threads_on(outputStream* st) const {
1279 }
1280 
1281 void GenCollectedHeap::print_tracing_info() const {
1282   if (log_is_enabled(Debug, gc, heap, exit)) {
1283     LogStreamHandle(Debug, gc, heap, exit) lsh;
1284     _young_gen->print_summary_info_on(&lsh);
1285     _old_gen->print_summary_info_on(&lsh);
1286   }
1287 }
1288 
1289 void GenCollectedHeap::print_heap_change(size_t young_prev_used, size_t old_prev_used) const {
1290   log_info(gc, heap)("%s: " SIZE_FORMAT "K->" SIZE_FORMAT "K("  SIZE_FORMAT "K)",
1291                      _young_gen->short_name(), young_prev_used / K, _young_gen->used() /K, _young_gen->capacity() /K);
1292   log_info(gc, heap)("%s: " SIZE_FORMAT "K->" SIZE_FORMAT "K("  SIZE_FORMAT "K)",
1293                      _old_gen->short_name(), old_prev_used / K, _old_gen->used() /K, _old_gen->capacity() /K);
1294 }
1295 
1296 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure {
1297  private:
1298   bool _full;
1299  public:
1300   void do_generation(Generation* gen) {
1301     gen->gc_prologue(_full);
1302   }
1303   GenGCPrologueClosure(bool full) : _full(full) {};
1304 };
1305 
1306 void GenCollectedHeap::gc_prologue(bool full) {
1307   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
1308 
1309   // Fill TLAB's and such
1310   ensure_parsability(true);   // retire TLABs
1311 
1312   // Walk generations
1313   GenGCPrologueClosure blk(full);
1314   generation_iterate(&blk, false);  // not old-to-young.
1315 };
1316 
1317 class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure {
1318  private:
1319   bool _full;
1320  public:
1321   void do_generation(Generation* gen) {
1322     gen->gc_epilogue(_full);
1323   }
1324   GenGCEpilogueClosure(bool full) : _full(full) {};
1325 };
1326 
1327 void GenCollectedHeap::gc_epilogue(bool full) {
1328 #if COMPILER2_OR_JVMCI
1329   assert(DerivedPointerTable::is_empty(), "derived pointer present");
1330   size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr()));
1331   guarantee(is_client_compilation_mode_vm() || actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps");
1332 #endif // COMPILER2_OR_JVMCI
1333 
1334   resize_all_tlabs();
1335 
1336   GenGCEpilogueClosure blk(full);
1337   generation_iterate(&blk, false);  // not old-to-young.
1338 
1339   if (!CleanChunkPoolAsync) {
1340     Chunk::clean_chunk_pool();
1341   }
1342 
1343   MetaspaceCounters::update_performance_counters();
1344   CompressedClassSpaceCounters::update_performance_counters();
1345 };
1346 
1347 #ifndef PRODUCT
1348 class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure {
1349  private:
1350  public:
1351   void do_generation(Generation* gen) {
1352     gen->record_spaces_top();
1353   }
1354 };
1355 
1356 void GenCollectedHeap::record_gen_tops_before_GC() {
1357   if (ZapUnusedHeapArea) {
1358     GenGCSaveTopsBeforeGCClosure blk;
1359     generation_iterate(&blk, false);  // not old-to-young.
1360   }
1361 }
1362 #endif  // not PRODUCT
1363 
1364 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure {
1365  public:
1366   void do_generation(Generation* gen) {
1367     gen->ensure_parsability();
1368   }
1369 };
1370 
1371 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) {
1372   CollectedHeap::ensure_parsability(retire_tlabs);
1373   GenEnsureParsabilityClosure ep_cl;
1374   generation_iterate(&ep_cl, false);
1375 }
1376 
1377 oop GenCollectedHeap::handle_failed_promotion(Generation* old_gen,
1378                                               oop obj,
1379                                               size_t obj_size) {
1380   guarantee(old_gen == _old_gen, "We only get here with an old generation");
1381   assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
1382   HeapWord* result = NULL;
1383 
1384   result = old_gen->expand_and_allocate(obj_size, false);
1385 
1386   if (result != NULL) {
1387     Copy::aligned_disjoint_words((HeapWord*)obj, result, obj_size);
1388   }
1389   return oop(result);
1390 }
1391 
1392 class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure {
1393   jlong _time;   // in ms
1394   jlong _now;    // in ms
1395 
1396  public:
1397   GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { }
1398 
1399   jlong time() { return _time; }
1400 
1401   void do_generation(Generation* gen) {
1402     _time = MIN2(_time, gen->time_of_last_gc(_now));
1403   }
1404 };
1405 
1406 jlong GenCollectedHeap::millis_since_last_gc() {
1407   // javaTimeNanos() is guaranteed to be monotonically non-decreasing
1408   // provided the underlying platform provides such a time source
1409   // (and it is bug free). So we still have to guard against getting
1410   // back a time later than 'now'.
1411   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
1412   GenTimeOfLastGCClosure tolgc_cl(now);
1413   // iterate over generations getting the oldest
1414   // time that a generation was collected
1415   generation_iterate(&tolgc_cl, false);
1416 
1417   jlong retVal = now - tolgc_cl.time();
1418   if (retVal < 0) {
1419     log_warning(gc)("millis_since_last_gc() would return : " JLONG_FORMAT
1420        ". returning zero instead.", retVal);
1421     return 0;
1422   }
1423   return retVal;
1424 }