1 /*
   2  * Copyright (c) 2018, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 
  26 #include "gc/shenandoah/heuristics/shenandoahAdaptiveHeuristics.hpp"
  27 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  28 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  29 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  30 #include "logging/log.hpp"
  31 #include "logging/logTag.hpp"
  32 #include "utilities/quickSort.hpp"
  33 
  34 ShenandoahAdaptiveHeuristics::ShenandoahAdaptiveHeuristics() :
  35   ShenandoahHeuristics(),
  36   _cycle_gap_history(new TruncatedSeq(5)),
  37   _conc_mark_duration_history(new TruncatedSeq(5)),
  38   _conc_uprefs_duration_history(new TruncatedSeq(5)) {
  39 
  40   SHENANDOAH_ERGO_ENABLE_FLAG(ExplicitGCInvokesConcurrent);
  41   SHENANDOAH_ERGO_ENABLE_FLAG(ShenandoahImplicitGCInvokesConcurrent);
  42 
  43   // Final configuration checks
  44   SHENANDOAH_CHECK_FLAG_SET(ShenandoahSATBBarrier);
  45   SHENANDOAH_CHECK_FLAG_SET(ShenandoahReadBarrier);
  46   SHENANDOAH_CHECK_FLAG_SET(ShenandoahWriteBarrier);
  47   SHENANDOAH_CHECK_FLAG_SET(ShenandoahStoreValReadBarrier);
  48   SHENANDOAH_CHECK_FLAG_SET(ShenandoahKeepAliveBarrier);
  49   SHENANDOAH_CHECK_FLAG_SET(ShenandoahCASBarrier);
  50   SHENANDOAH_CHECK_FLAG_SET(ShenandoahAcmpBarrier);
  51   SHENANDOAH_CHECK_FLAG_SET(ShenandoahCloneBarrier);
  52 }
  53 
  54 ShenandoahAdaptiveHeuristics::~ShenandoahAdaptiveHeuristics() {}
  55 
  56 void ShenandoahAdaptiveHeuristics::choose_collection_set_from_regiondata(ShenandoahCollectionSet* cset,
  57                                                                          RegionData* data, size_t size,
  58                                                                          size_t actual_free) {
  59   size_t garbage_threshold = ShenandoahHeapRegion::region_size_bytes() * ShenandoahGarbageThreshold / 100;
  60 
  61   // The logic for cset selection in adaptive is as follows:
  62   //
  63   //   1. We cannot get cset larger than available free space. Otherwise we guarantee OOME
  64   //      during evacuation, and thus guarantee full GC. In practice, we also want to let
  65   //      application to allocate something. This is why we limit CSet to some fraction of
  66   //      available space. In non-overloaded heap, max_cset would contain all plausible candidates
  67   //      over garbage threshold.
  68   //
  69   //   2. We should not get cset too low so that free threshold would not be met right
  70   //      after the cycle. Otherwise we get back-to-back cycles for no reason if heap is
  71   //      too fragmented. In non-overloaded non-fragmented heap min_garbage would be around zero.
  72   //
  73   // Therefore, we start by sorting the regions by garbage. Then we unconditionally add the best candidates
  74   // before we meet min_garbage. Then we add all candidates that fit with a garbage threshold before
  75   // we hit max_cset. When max_cset is hit, we terminate the cset selection. Note that in this scheme,
  76   // ShenandoahGarbageThreshold is the soft threshold which would be ignored until min_garbage is hit.
  77 
  78   size_t capacity    = ShenandoahHeap::heap()->capacity();
  79   size_t free_target = ShenandoahMinFreeThreshold * capacity / 100;
  80   size_t min_garbage = free_target > actual_free ? (free_target - actual_free) : 0;
  81   size_t max_cset    = (size_t)(1.0 * ShenandoahEvacReserve * capacity / 100 / ShenandoahEvacWaste);
  82 
  83   log_info(gc, ergo)("Adaptive CSet Selection. Target Free: " SIZE_FORMAT "M, Actual Free: "
  84                      SIZE_FORMAT "M, Max CSet: " SIZE_FORMAT "M, Min Garbage: " SIZE_FORMAT "M",
  85                      free_target / M, actual_free / M, max_cset / M, min_garbage / M);
  86 
  87   // Better select garbage-first regions
  88   QuickSort::sort<RegionData>(data, (int)size, compare_by_garbage, false);
  89 
  90   size_t cur_cset = 0;
  91   size_t cur_garbage = 0;
  92   _bytes_in_cset = 0;
  93 
  94   for (size_t idx = 0; idx < size; idx++) {
  95     ShenandoahHeapRegion* r = data[idx]._region;
  96 
  97     size_t new_cset    = cur_cset + r->get_live_data_bytes();
  98     size_t new_garbage = cur_garbage + r->garbage();
  99 
 100     if (new_cset > max_cset) {
 101       break;
 102     }
 103 
 104     if ((new_garbage < min_garbage) || (r->garbage() > garbage_threshold)) {
 105       cset->add_region(r);
 106       _bytes_in_cset += r->used();
 107       cur_cset = new_cset;
 108       cur_garbage = new_garbage;
 109     }
 110   }
 111 }
 112 
 113 void ShenandoahAdaptiveHeuristics::record_cycle_start() {
 114   ShenandoahHeuristics::record_cycle_start();
 115   double last_cycle_gap = (_cycle_start - _last_cycle_end);
 116   _cycle_gap_history->add(last_cycle_gap);
 117 }
 118 
 119 void ShenandoahAdaptiveHeuristics::record_phase_time(ShenandoahPhaseTimings::Phase phase, double secs) {
 120   if (phase == ShenandoahPhaseTimings::conc_mark) {
 121     _conc_mark_duration_history->add(secs);
 122   } else if (phase == ShenandoahPhaseTimings::conc_update_refs) {
 123     _conc_uprefs_duration_history->add(secs);
 124   } // Else ignore
 125 }
 126 
 127 bool ShenandoahAdaptiveHeuristics::should_start_normal_gc() const {
 128   ShenandoahHeap* heap = ShenandoahHeap::heap();
 129   size_t capacity = heap->capacity();
 130   size_t available = heap->free_set()->available();
 131 
 132   // Check if we are falling below the worst limit, time to trigger the GC, regardless of
 133   // anything else.
 134   size_t min_threshold = ShenandoahMinFreeThreshold * heap->capacity() / 100;
 135   if (available < min_threshold) {
 136     log_info(gc)("Trigger: Free (" SIZE_FORMAT "M) is below minimum threshold (" SIZE_FORMAT "M)",
 137                  available / M, min_threshold / M);
 138     return true;
 139   }
 140 
 141   // Check if are need to learn a bit about the application
 142   const size_t max_learn = ShenandoahLearningSteps;
 143   if (_gc_times_learned < max_learn) {
 144     size_t init_threshold = ShenandoahInitFreeThreshold * heap->capacity() / 100;
 145     if (available < init_threshold) {
 146       log_info(gc)("Trigger: Learning " SIZE_FORMAT " of " SIZE_FORMAT ". Free (" SIZE_FORMAT "M) is below initial threshold (" SIZE_FORMAT "M)",
 147                    _gc_times_learned + 1, max_learn, available / M, init_threshold / M);
 148       return true;
 149     }
 150   }
 151 
 152   // Check if allocation headroom is still okay. This also factors in:
 153   //   1. Some space to absorb allocation spikes
 154   //   2. Accumulated penalties from Degenerated and Full GC
 155 
 156   size_t allocation_headroom = available;
 157 
 158   size_t spike_headroom = ShenandoahAllocSpikeFactor * capacity / 100;
 159   size_t penalties      = _gc_time_penalties         * capacity / 100;
 160 
 161   allocation_headroom -= MIN2(allocation_headroom, spike_headroom);
 162   allocation_headroom -= MIN2(allocation_headroom, penalties);
 163 
 164   // TODO: Allocation rate is way too averaged to be useful during state changes
 165 
 166   double average_gc = _gc_time_history->avg();
 167   double time_since_last = time_since_last_gc();
 168   double allocation_rate = heap->bytes_allocated_since_gc_start() / time_since_last;
 169 
 170   if (average_gc > allocation_headroom / allocation_rate) {
 171     log_info(gc)("Trigger: Average GC time (%.2f ms) is above the time for allocation rate (%.2f MB/s) to deplete free headroom (" SIZE_FORMAT "M)",
 172                  average_gc * 1000, allocation_rate / M, allocation_headroom / M);
 173     log_info(gc, ergo)("Free headroom: " SIZE_FORMAT "M (free) - " SIZE_FORMAT "M (spike) - " SIZE_FORMAT "M (penalties) = " SIZE_FORMAT "M",
 174                        available / M, spike_headroom / M, penalties / M, allocation_headroom / M);
 175     return true;
 176   }
 177 
 178   return ShenandoahHeuristics::should_start_normal_gc();
 179 }
 180 
 181 bool ShenandoahAdaptiveHeuristics::should_start_update_refs() {
 182   if (! _update_refs_adaptive) {
 183     return _update_refs_early;
 184   }
 185 
 186   double cycle_gap_avg = _cycle_gap_history->avg();
 187   double conc_mark_avg = _conc_mark_duration_history->avg();
 188   double conc_uprefs_avg = _conc_uprefs_duration_history->avg();
 189 
 190   if (_update_refs_early) {
 191     double threshold = ShenandoahMergeUpdateRefsMinGap / 100.0;
 192     if (conc_mark_avg + conc_uprefs_avg > cycle_gap_avg * threshold) {
 193       _update_refs_early = false;
 194     }
 195   } else {
 196     double threshold = ShenandoahMergeUpdateRefsMaxGap / 100.0;
 197     if (conc_mark_avg + conc_uprefs_avg < cycle_gap_avg * threshold) {
 198       _update_refs_early = true;
 199     }
 200   }
 201   return _update_refs_early;
 202 }
 203 
 204 const char* ShenandoahAdaptiveHeuristics::name() {
 205   return "adaptive";
 206 }
 207 
 208 bool ShenandoahAdaptiveHeuristics::is_diagnostic() {
 209   return false;
 210 }
 211 
 212 bool ShenandoahAdaptiveHeuristics::is_experimental() {
 213   return false;
 214 }