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