1 /*
   2  * Copyright (c) 2018, 2019, 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/shenandoahTraversalHeuristics.hpp"
  27 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  28 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  29 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  30 #include "gc/shenandoah/shenandoahHeuristics.hpp"
  31 #include "gc/shenandoah/shenandoahTraversalGC.hpp"
  32 #include "logging/log.hpp"
  33 #include "logging/logTag.hpp"
  34 #include "utilities/quickSort.hpp"
  35 
  36 ShenandoahTraversalHeuristics::ShenandoahTraversalHeuristics() : ShenandoahHeuristics(),
  37   _last_cset_select(0) {}
  38 
  39 bool ShenandoahTraversalHeuristics::is_experimental() {
  40   return true;
  41 }
  42 
  43 bool ShenandoahTraversalHeuristics::is_diagnostic() {
  44   return false;
  45 }
  46 
  47 const char* ShenandoahTraversalHeuristics::name() {
  48   return "traversal";
  49 }
  50 
  51 void ShenandoahTraversalHeuristics::choose_collection_set(ShenandoahCollectionSet* collection_set) {
  52   ShenandoahHeap* heap = ShenandoahHeap::heap();
  53 
  54   ShenandoahTraversalGC* traversal_gc = heap->traversal_gc();
  55 
  56   ShenandoahHeapRegionSet* traversal_set = traversal_gc->traversal_set();
  57   traversal_set->clear();
  58 
  59   RegionData *data = get_region_data_cache(heap->num_regions());
  60   size_t cnt = 0;
  61 
  62   // Step 0. Prepare all regions
  63 
  64   for (size_t i = 0; i < heap->num_regions(); i++) {
  65     ShenandoahHeapRegion* r = heap->get_region(i);
  66     if (r->used() > 0) {
  67       if (r->is_regular()) {
  68         data[cnt]._region = r;
  69         data[cnt]._garbage = r->garbage();
  70         data[cnt]._seqnum_last_alloc = r->seqnum_last_alloc_mutator();
  71         cnt++;
  72       }
  73       traversal_set->add_region(r);
  74     }
  75   }
  76 
  77   // The logic for cset selection is similar to that of adaptive:
  78   //
  79   //   1. We cannot get cset larger than available free space. Otherwise we guarantee OOME
  80   //      during evacuation, and thus guarantee full GC. In practice, we also want to let
  81   //      application to allocate something. This is why we limit CSet to some fraction of
  82   //      available space. In non-overloaded heap, max_cset would contain all plausible candidates
  83   //      over garbage threshold.
  84   //
  85   //   2. We should not get cset too low so that free threshold would not be met right
  86   //      after the cycle. Otherwise we get back-to-back cycles for no reason if heap is
  87   //      too fragmented. In non-overloaded non-fragmented heap min_garbage would be around zero.
  88   //
  89   // Therefore, we start by sorting the regions by garbage. Then we unconditionally add the best candidates
  90   // before we meet min_garbage. Then we add all candidates that fit with a garbage threshold before
  91   // we hit max_cset. When max_cset is hit, we terminate the cset selection. Note that in this scheme,
  92   // ShenandoahGarbageThreshold is the soft threshold which would be ignored until min_garbage is hit.
  93   //
  94   // The significant complication is that liveness data was collected at the previous cycle, and only
  95   // for those regions that were allocated before previous cycle started.
  96 
  97   size_t capacity    = heap->max_capacity();
  98   size_t actual_free = heap->free_set()->available();
  99   size_t free_target = capacity / 100 * ShenandoahMinFreeThreshold;
 100   size_t min_garbage = free_target > actual_free ? (free_target - actual_free) : 0;
 101   size_t max_cset    = (size_t)((1.0 * capacity / 100 * ShenandoahEvacReserve) / ShenandoahEvacWaste);
 102 
 103   log_info(gc, ergo)("Adaptive CSet Selection. Target Free: " SIZE_FORMAT "M, Actual Free: "
 104                      SIZE_FORMAT "M, Max CSet: " SIZE_FORMAT "M, Min Garbage: " SIZE_FORMAT "M",
 105                      free_target / M, actual_free / M, max_cset / M, min_garbage / M);
 106 
 107   // Better select garbage-first regions, and then older ones
 108   QuickSort::sort<RegionData>(data, (int) cnt, compare_by_garbage_then_alloc_seq_ascending, false);
 109 
 110   size_t cur_cset = 0;
 111   size_t cur_garbage = 0;
 112 
 113   size_t garbage_threshold = ShenandoahHeapRegion::region_size_bytes() / 100 * ShenandoahGarbageThreshold;
 114 
 115   // Step 1. Add trustworthy regions to collection set.
 116   //
 117   // We can trust live/garbage data from regions that were fully traversed during
 118   // previous cycle. Even if actual liveness is different now, we can only have _less_
 119   // live objects, because dead objects are not resurrected. Which means we can undershoot
 120   // the collection set, but not overshoot it.
 121 
 122   for (size_t i = 0; i < cnt; i++) {
 123     if (data[i]._seqnum_last_alloc > _last_cset_select) continue;
 124 
 125     ShenandoahHeapRegion* r = data[i]._region;
 126     assert (r->is_regular(), "should have been filtered before");
 127 
 128     size_t new_garbage = cur_garbage + r->garbage();
 129     size_t new_cset    = cur_cset    + r->get_live_data_bytes();
 130 
 131     if (new_cset > max_cset) {
 132       break;
 133     }
 134 
 135     if ((new_garbage < min_garbage) || (r->garbage() > garbage_threshold)) {
 136       assert(!collection_set->is_in(r), "must not yet be in cset");
 137       collection_set->add_region(r);
 138       cur_cset = new_cset;
 139       cur_garbage = new_garbage;
 140     }
 141   }
 142 
 143   // Step 2. Try to catch some recently allocated regions for evacuation ride.
 144   //
 145   // Pessimistically assume we are going to evacuate the entire region. While this
 146   // is very pessimistic and in most cases undershoots the collection set when regions
 147   // are mostly dead, it also provides more safety against running into allocation
 148   // failure when newly allocated regions are fully live.
 149 
 150   for (size_t i = 0; i < cnt; i++) {
 151     if (data[i]._seqnum_last_alloc <= _last_cset_select) continue;
 152 
 153     ShenandoahHeapRegion* r = data[i]._region;
 154     assert (r->is_regular(), "should have been filtered before");
 155 
 156     // size_t new_garbage = cur_garbage + 0; (implied)
 157     size_t new_cset = cur_cset + r->used();
 158 
 159     if (new_cset > max_cset) {
 160       break;
 161     }
 162 
 163     assert(!collection_set->is_in(r), "must not yet be in cset");
 164     collection_set->add_region(r);
 165     cur_cset = new_cset;
 166   }
 167 
 168   // Step 3. Clear liveness data
 169   // TODO: Merge it with step 0, but save live data in RegionData before.
 170   for (size_t i = 0; i < heap->num_regions(); i++) {
 171     ShenandoahHeapRegion* r = heap->get_region(i);
 172     if (r->used() > 0) {
 173       r->clear_live_data();
 174     }
 175   }
 176 
 177   collection_set->update_region_status();
 178 
 179   _last_cset_select = ShenandoahHeapRegion::seqnum_current_alloc();
 180 }
 181 
 182 bool ShenandoahTraversalHeuristics::should_start_gc() const {
 183   ShenandoahHeap* heap = ShenandoahHeap::heap();
 184   assert(!heap->has_forwarded_objects(), "no forwarded objects here");
 185 
 186   size_t capacity = heap->max_capacity();
 187   size_t available = heap->free_set()->available();
 188 
 189   // Check if we are falling below the worst limit, time to trigger the GC, regardless of
 190   // anything else.
 191   size_t min_threshold = capacity / 100 * ShenandoahMinFreeThreshold;
 192   if (available < min_threshold) {
 193     log_info(gc)("Trigger: Free (" SIZE_FORMAT "M) is below minimum threshold (" SIZE_FORMAT "M)",
 194                  available / M, min_threshold / M);
 195     return true;
 196   }
 197 
 198   // Check if are need to learn a bit about the application
 199   const size_t max_learn = ShenandoahLearningSteps;
 200   if (_gc_times_learned < max_learn) {
 201     size_t init_threshold = capacity / 100 * ShenandoahInitFreeThreshold;
 202     if (available < init_threshold) {
 203       log_info(gc)("Trigger: Learning " SIZE_FORMAT " of " SIZE_FORMAT ". Free (" SIZE_FORMAT "M) is below initial threshold (" SIZE_FORMAT "M)",
 204                    _gc_times_learned + 1, max_learn, available / M, init_threshold / M);
 205       return true;
 206     }
 207   }
 208 
 209   // Check if allocation headroom is still okay. This also factors in:
 210   //   1. Some space to absorb allocation spikes
 211   //   2. Accumulated penalties from Degenerated and Full GC
 212 
 213   size_t allocation_headroom = available;
 214 
 215   size_t spike_headroom = capacity / 100 * ShenandoahAllocSpikeFactor;
 216   size_t penalties      = capacity / 100 * _gc_time_penalties;
 217 
 218   allocation_headroom -= MIN2(allocation_headroom, spike_headroom);
 219   allocation_headroom -= MIN2(allocation_headroom, penalties);
 220 
 221   double average_gc = _gc_time_history->avg();
 222   double time_since_last = time_since_last_gc();
 223   double allocation_rate = heap->bytes_allocated_since_gc_start() / time_since_last;
 224 
 225   if (average_gc > allocation_headroom / allocation_rate) {
 226     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)",
 227                  average_gc * 1000, allocation_rate / M, allocation_headroom / M);
 228     log_info(gc, ergo)("Free headroom: " SIZE_FORMAT "M (free) - " SIZE_FORMAT "M (spike) - " SIZE_FORMAT "M (penalties) = " SIZE_FORMAT "M",
 229                        available / M, spike_headroom / M, penalties / M, allocation_headroom / M);
 230     return true;
 231   } else if (ShenandoahHeuristics::should_start_gc()) {
 232     return true;
 233   }
 234 
 235   return false;
 236 }
 237 
 238 void ShenandoahTraversalHeuristics::choose_collection_set_from_regiondata(ShenandoahCollectionSet* set,
 239                                                                           RegionData* data, size_t data_size,
 240                                                                           size_t free) {
 241   ShouldNotReachHere();
 242 }