1 /*
   2  * Copyright (c) 2018, Red Hat, Inc. and/or its affiliates.
   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 #include "gc_implementation/shenandoah/heuristics/shenandoahAdaptiveHeuristics.hpp"
  26 #include "gc_implementation/shenandoah/shenandoahCollectionSet.hpp"
  27 #include "gc_implementation/shenandoah/shenandoahFreeSet.hpp"
  28 #include "gc_implementation/shenandoah/shenandoahHeapRegion.hpp"
  29 #include "gc_implementation/shenandoah/shenandoahLogging.hpp"
  30 #include "utilities/quickSort.hpp"
  31 
  32 ShenandoahAdaptiveHeuristics::ShenandoahAdaptiveHeuristics() :
  33   ShenandoahHeuristics(),
  34   _cycle_gap_history(new TruncatedSeq(5)),
  35   _conc_mark_duration_history(new TruncatedSeq(5)),
  36   _conc_uprefs_duration_history(new TruncatedSeq(5)) {
  37 }
  38 
  39 ShenandoahAdaptiveHeuristics::~ShenandoahAdaptiveHeuristics() {}
  40 
  41 void ShenandoahAdaptiveHeuristics::choose_collection_set_from_regiondata(ShenandoahCollectionSet* cset,
  42                                                                          RegionData* data, size_t size,
  43                                                                          size_t actual_free) {
  44   size_t garbage_threshold = ShenandoahHeapRegion::region_size_bytes() * ShenandoahGarbageThreshold / 100;
  45 
  46   // The logic for cset selection in adaptive is as follows:
  47   //
  48   //   1. We cannot get cset larger than available free space. Otherwise we guarantee OOME
  49   //      during evacuation, and thus guarantee full GC. In practice, we also want to let
  50   //      application to allocate something. This is why we limit CSet to some fraction of
  51   //      available space. In non-overloaded heap, max_cset would contain all plausible candidates
  52   //      over garbage threshold.
  53   //
  54   //   2. We should not get cset too low so that free threshold would not be met right
  55   //      after the cycle. Otherwise we get back-to-back cycles for no reason if heap is
  56   //      too fragmented. In non-overloaded non-fragmented heap min_garbage would be around zero.
  57   //
  58   // Therefore, we start by sorting the regions by garbage. Then we unconditionally add the best candidates
  59   // before we meet min_garbage. Then we add all candidates that fit with a garbage threshold before
  60   // we hit max_cset. When max_cset is hit, we terminate the cset selection. Note that in this scheme,
  61   // ShenandoahGarbageThreshold is the soft threshold which would be ignored until min_garbage is hit.
  62 
  63   size_t capacity    = ShenandoahHeap::heap()->capacity();
  64   size_t free_target = ShenandoahMinFreeThreshold * capacity / 100;
  65   size_t min_garbage = free_target > actual_free ? (free_target - actual_free) : 0;
  66   size_t max_cset    = (size_t)(1.0 * ShenandoahEvacReserve * capacity / 100 / ShenandoahEvacWaste);
  67 
  68   log_info(gc, ergo)("Adaptive CSet Selection. Target Free: " SIZE_FORMAT "M, Actual Free: "
  69                      SIZE_FORMAT "M, Max CSet: " SIZE_FORMAT "M, Min Garbage: " SIZE_FORMAT "M",
  70                      free_target / M, actual_free / M, max_cset / M, min_garbage / M);
  71 
  72   // Better select garbage-first regions
  73   QuickSort::sort<RegionData>(data, (int)size, compare_by_garbage, false);
  74 
  75   size_t cur_cset = 0;
  76   size_t cur_garbage = 0;
  77   _bytes_in_cset = 0;
  78 
  79   for (size_t idx = 0; idx < size; idx++) {
  80     ShenandoahHeapRegion* r = data[idx]._region;
  81 
  82     size_t new_cset    = cur_cset + r->get_live_data_bytes();
  83     size_t new_garbage = cur_garbage + r->garbage();
  84 
  85     if (new_cset > max_cset) {
  86       break;
  87     }
  88 
  89     if ((new_garbage < min_garbage) || (r->garbage() > garbage_threshold)) {
  90       cset->add_region(r);
  91       _bytes_in_cset += r->used();
  92       cur_cset = new_cset;
  93       cur_garbage = new_garbage;
  94     }
  95   }
  96 }
  97 
  98 void ShenandoahAdaptiveHeuristics::record_cycle_start() {
  99   ShenandoahHeuristics::record_cycle_start();
 100   double last_cycle_gap = (_cycle_start - _last_cycle_end);
 101   _cycle_gap_history->add(last_cycle_gap);
 102 }
 103 
 104 void ShenandoahAdaptiveHeuristics::record_phase_time(ShenandoahPhaseTimings::Phase phase, double secs) {
 105   if (phase == ShenandoahPhaseTimings::conc_mark) {
 106     _conc_mark_duration_history->add(secs);
 107   } else if (phase == ShenandoahPhaseTimings::conc_update_refs) {
 108     _conc_uprefs_duration_history->add(secs);
 109   } // Else ignore
 110 }
 111 
 112 bool ShenandoahAdaptiveHeuristics::should_start_normal_gc() const {
 113   ShenandoahHeap* heap = ShenandoahHeap::heap();
 114   size_t capacity = heap->capacity();
 115   size_t available = heap->free_set()->available();
 116 
 117   // Check if we are falling below the worst limit, time to trigger the GC, regardless of
 118   // anything else.
 119   size_t min_threshold = ShenandoahMinFreeThreshold * heap->capacity() / 100;
 120   if (available < min_threshold) {
 121     log_info(gc)("Trigger: Free (" SIZE_FORMAT "M) is below minimum threshold (" SIZE_FORMAT "M)",
 122                  available / M, min_threshold / M);
 123     return true;
 124   }
 125 
 126   // Check if are need to learn a bit about the application
 127   const size_t max_learn = ShenandoahLearningSteps;
 128   if (_gc_times_learned < max_learn) {
 129     size_t init_threshold = ShenandoahInitFreeThreshold * heap->capacity() / 100;
 130     if (available < init_threshold) {
 131       log_info(gc)("Trigger: Learning " SIZE_FORMAT " of " SIZE_FORMAT ". Free (" SIZE_FORMAT "M) is below initial threshold (" SIZE_FORMAT "M)",
 132                    _gc_times_learned + 1, max_learn, available / M, init_threshold / M);
 133       return true;
 134     }
 135   }
 136 
 137   // Check if allocation headroom is still okay. This also factors in:
 138   //   1. Some space to absorb allocation spikes
 139   //   2. Accumulated penalties from Degenerated and Full GC
 140 
 141   size_t allocation_headroom = available;
 142 
 143   size_t spike_headroom = ShenandoahAllocSpikeFactor * capacity / 100;
 144   size_t penalties      = _gc_time_penalties         * capacity / 100;
 145 
 146   allocation_headroom -= MIN2(allocation_headroom, spike_headroom);
 147   allocation_headroom -= MIN2(allocation_headroom, penalties);
 148 
 149   // TODO: Allocation rate is way too averaged to be useful during state changes
 150 
 151   double average_gc = _gc_time_history->avg();
 152   double time_since_last = os::elapsedTime() - _cycle_start;
 153   double allocation_rate = heap->bytes_allocated_since_gc_start() / time_since_last;
 154 
 155   if (average_gc > allocation_headroom / allocation_rate) {
 156     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)",
 157                  average_gc * 1000, allocation_rate / M, allocation_headroom / M);
 158     log_info(gc, ergo)("Free headroom: " SIZE_FORMAT "M (free) - " SIZE_FORMAT "M (spike) - " SIZE_FORMAT "M (penalties) = " SIZE_FORMAT "M",
 159                        available / M, spike_headroom / M, penalties / M, allocation_headroom / M);
 160     return true;
 161   }
 162 
 163   return ShenandoahHeuristics::should_start_normal_gc();
 164 }
 165 
 166 bool ShenandoahAdaptiveHeuristics::should_start_update_refs() {
 167   if (! _update_refs_adaptive) {
 168     return _update_refs_early;
 169   }
 170 
 171   double cycle_gap_avg = _cycle_gap_history->avg();
 172   double conc_mark_avg = _conc_mark_duration_history->avg();
 173   double conc_uprefs_avg = _conc_uprefs_duration_history->avg();
 174 
 175   if (_update_refs_early) {
 176     double threshold = ShenandoahMergeUpdateRefsMinGap / 100.0;
 177     if (conc_mark_avg + conc_uprefs_avg > cycle_gap_avg * threshold) {
 178       _update_refs_early = false;
 179     }
 180   } else {
 181     double threshold = ShenandoahMergeUpdateRefsMaxGap / 100.0;
 182     if (conc_mark_avg + conc_uprefs_avg < cycle_gap_avg * threshold) {
 183       _update_refs_early = true;
 184     }
 185   }
 186   return _update_refs_early;
 187 }
 188 
 189 const char* ShenandoahAdaptiveHeuristics::name() {
 190   return "adaptive";
 191 }
 192 
 193 bool ShenandoahAdaptiveHeuristics::is_diagnostic() {
 194   return false;
 195 }
 196 
 197 bool ShenandoahAdaptiveHeuristics::is_experimental() {
 198   return false;
 199 }