rev 49945 : imported patch 8191471-g1-varying-tlab-allocation
rev 49949 : imported patch 8191471-tschatzl-comments-open
rev 49950 : [mq]: 8191471-pliden-comments

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