1 /*
   2  * Copyright (c) 2018, 2020, 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/shared/gcCause.hpp"
  27 #include "gc/shenandoah/shenandoahCollectionSet.inline.hpp"
  28 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  29 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  30 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  31 #include "gc/shenandoah/shenandoahHeuristics.hpp"
  32 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  33 #include "logging/log.hpp"
  34 #include "logging/logTag.hpp"
  35 
  36 int ShenandoahHeuristics::compare_by_garbage(RegionData a, RegionData b) {
  37   if (a._garbage > b._garbage)
  38     return -1;
  39   else if (a._garbage < b._garbage)
  40     return 1;
  41   else return 0;
  42 }
  43 
  44 ShenandoahHeuristics::ShenandoahHeuristics() :
  45   _region_data(NULL),
  46   _degenerated_cycles_in_a_row(0),
  47   _successful_cycles_in_a_row(0),
  48   _cycle_start(os::elapsedTime()),
  49   _last_cycle_end(0),
  50   _gc_times_learned(0),
  51   _gc_time_penalties(0),
  52   _gc_time_history(new TruncatedSeq(5)),
  53   _metaspace_oom()
  54 {
  55   // No unloading during concurrent mark? Communicate that to heuristics
  56   if (!ClassUnloadingWithConcurrentMark) {
  57     FLAG_SET_DEFAULT(ShenandoahUnloadClassesFrequency, 0);
  58   }
  59 
  60   size_t num_regions = ShenandoahHeap::heap()->num_regions();
  61   assert(num_regions > 0, "Sanity");
  62 
  63   _region_data = NEW_C_HEAP_ARRAY(RegionData, num_regions, mtGC);
  64 }
  65 
  66 ShenandoahHeuristics::~ShenandoahHeuristics() {
  67   FREE_C_HEAP_ARRAY(RegionGarbage, _region_data);
  68 }
  69 
  70 void ShenandoahHeuristics::choose_collection_set(ShenandoahCollectionSet* collection_set) {
  71   assert(collection_set->count() == 0, "Must be empty");
  72 
  73   ShenandoahHeap* heap = ShenandoahHeap::heap();
  74 
  75   // Check all pinned regions have updated status before choosing the collection set.
  76   heap->assert_pinned_region_status();
  77 
  78   // Step 1. Build up the region candidates we care about, rejecting losers and accepting winners right away.
  79 
  80   size_t num_regions = heap->num_regions();
  81 
  82   RegionData* candidates = _region_data;
  83 
  84   size_t cand_idx = 0;
  85 
  86   size_t total_garbage = 0;
  87 
  88   size_t immediate_garbage = 0;
  89   size_t immediate_regions = 0;
  90 
  91   size_t free = 0;
  92   size_t free_regions = 0;
  93 
  94   ShenandoahMarkingContext* const ctx = heap->complete_marking_context();
  95 
  96   for (size_t i = 0; i < num_regions; i++) {
  97     ShenandoahHeapRegion* region = heap->get_region(i);
  98 
  99     size_t garbage = region->garbage();
 100     total_garbage += garbage;
 101 
 102     if (region->is_empty()) {
 103       free_regions++;
 104       free += ShenandoahHeapRegion::region_size_bytes();
 105     } else if (region->is_regular()) {
 106       if (!region->has_live()) {
 107         // We can recycle it right away and put it in the free set.
 108         immediate_regions++;
 109         immediate_garbage += garbage;
 110         region->make_trash_immediate();
 111       } else {
 112         // This is our candidate for later consideration.
 113         candidates[cand_idx]._region = region;
 114         candidates[cand_idx]._garbage = garbage;
 115         cand_idx++;
 116       }
 117     } else if (region->is_humongous_start()) {
 118       // Reclaim humongous regions here, and count them as the immediate garbage
 119 #ifdef ASSERT
 120       bool reg_live = region->has_live();
 121       bool bm_live = ctx->is_marked(oop(region->bottom()));
 122       assert(reg_live == bm_live,
 123              "Humongous liveness and marks should agree. Region live: %s; Bitmap live: %s; Region Live Words: " SIZE_FORMAT,
 124              BOOL_TO_STR(reg_live), BOOL_TO_STR(bm_live), region->get_live_data_words());
 125 #endif
 126       if (!region->has_live()) {
 127         heap->trash_humongous_region_at(region);
 128 
 129         // Count only the start. Continuations would be counted on "trash" path
 130         immediate_regions++;
 131         immediate_garbage += garbage;
 132       }
 133     } else if (region->is_trash()) {
 134       // Count in just trashed collection set, during coalesced CM-with-UR
 135       immediate_regions++;
 136       immediate_garbage += garbage;
 137     }
 138   }
 139 
 140   // Step 2. Look back at garbage statistics, and decide if we want to collect anything,
 141   // given the amount of immediately reclaimable garbage. If we do, figure out the collection set.
 142 
 143   assert (immediate_garbage <= total_garbage,
 144           "Cannot have more immediate garbage than total garbage: " SIZE_FORMAT "%s vs " SIZE_FORMAT "%s",
 145           byte_size_in_proper_unit(immediate_garbage), proper_unit_for_byte_size(immediate_garbage),
 146           byte_size_in_proper_unit(total_garbage),     proper_unit_for_byte_size(total_garbage));
 147 
 148   size_t immediate_percent = (total_garbage == 0) ? 0 : (immediate_garbage * 100 / total_garbage);
 149 
 150   if (immediate_percent <= ShenandoahImmediateThreshold) {
 151     choose_collection_set_from_regiondata(collection_set, candidates, cand_idx, immediate_garbage + free);
 152   }
 153 
 154   size_t cset_percent = (total_garbage == 0) ? 0 : (collection_set->garbage() * 100 / total_garbage);
 155 
 156   size_t collectable_garbage = collection_set->garbage() + immediate_garbage;
 157   size_t collectable_garbage_percent = (total_garbage == 0) ? 0 : (collectable_garbage * 100 / total_garbage);
 158 
 159   log_info(gc, ergo)("Collectable Garbage: " SIZE_FORMAT "%s (" SIZE_FORMAT "%%), "
 160                      "Immediate: " SIZE_FORMAT "%s (" SIZE_FORMAT "%%), "
 161                      "CSet: " SIZE_FORMAT "%s (" SIZE_FORMAT "%%)",
 162 
 163                      byte_size_in_proper_unit(collectable_garbage),
 164                      proper_unit_for_byte_size(collectable_garbage),
 165                      collectable_garbage_percent,
 166 
 167                      byte_size_in_proper_unit(immediate_garbage),
 168                      proper_unit_for_byte_size(immediate_garbage),
 169                      immediate_percent,
 170 
 171                      byte_size_in_proper_unit(collection_set->garbage()),
 172                      proper_unit_for_byte_size(collection_set->garbage()),
 173                      cset_percent);
 174 }
 175 
 176 void ShenandoahHeuristics::record_cycle_start() {
 177   _cycle_start = os::elapsedTime();
 178 }
 179 
 180 void ShenandoahHeuristics::record_cycle_end() {
 181   _last_cycle_end = os::elapsedTime();
 182 }
 183 
 184 bool ShenandoahHeuristics::should_start_gc() const {
 185   // Perform GC to cleanup metaspace
 186   if (has_metaspace_oom()) {
 187     // Some of vmTestbase/metaspace tests depend on following line to count GC cycles
 188     log_info(gc)("Trigger: %s", GCCause::to_string(GCCause::_metadata_GC_threshold));
 189     return true;
 190   }
 191 
 192   if (ShenandoahGuaranteedGCInterval > 0) {
 193     double last_time_ms = (os::elapsedTime() - _last_cycle_end) * 1000;
 194     if (last_time_ms > ShenandoahGuaranteedGCInterval) {
 195       log_info(gc)("Trigger: Time since last GC (%.0f ms) is larger than guaranteed interval (" UINTX_FORMAT " ms)",
 196                    last_time_ms, ShenandoahGuaranteedGCInterval);
 197       return true;
 198     }
 199   }
 200 
 201   return false;
 202 }
 203 
 204 bool ShenandoahHeuristics::should_degenerate_cycle() {
 205   return _degenerated_cycles_in_a_row <= ShenandoahFullGCThreshold;
 206 }
 207 
 208 void ShenandoahHeuristics::adjust_penalty(intx step) {
 209   assert(0 <= _gc_time_penalties && _gc_time_penalties <= 100,
 210           "In range before adjustment: " INTX_FORMAT, _gc_time_penalties);
 211 
 212   intx new_val = _gc_time_penalties + step;
 213   if (new_val < 0) {
 214     new_val = 0;
 215   }
 216   if (new_val > 100) {
 217     new_val = 100;
 218   }
 219   _gc_time_penalties = new_val;
 220 
 221   assert(0 <= _gc_time_penalties && _gc_time_penalties <= 100,
 222           "In range after adjustment: " INTX_FORMAT, _gc_time_penalties);
 223 }
 224 
 225 void ShenandoahHeuristics::record_success_concurrent() {
 226   _degenerated_cycles_in_a_row = 0;
 227   _successful_cycles_in_a_row++;
 228 
 229   _gc_time_history->add(time_since_last_gc());
 230   _gc_times_learned++;
 231 
 232   adjust_penalty(Concurrent_Adjust);
 233 }
 234 
 235 void ShenandoahHeuristics::record_success_degenerated() {
 236   _degenerated_cycles_in_a_row++;
 237   _successful_cycles_in_a_row = 0;
 238 
 239   adjust_penalty(Degenerated_Penalty);
 240 }
 241 
 242 void ShenandoahHeuristics::record_success_full() {
 243   _degenerated_cycles_in_a_row = 0;
 244   _successful_cycles_in_a_row++;
 245 
 246   adjust_penalty(Full_Penalty);
 247 }
 248 
 249 void ShenandoahHeuristics::record_allocation_failure_gc() {
 250   // Do nothing.
 251 }
 252 
 253 void ShenandoahHeuristics::record_requested_gc() {
 254   // Assume users call System.gc() when external state changes significantly,
 255   // which forces us to re-learn the GC timings and allocation rates.
 256   _gc_times_learned = 0;
 257 }
 258 
 259 bool ShenandoahHeuristics::can_process_references() {
 260   if (ShenandoahRefProcFrequency == 0) return false;
 261   return true;
 262 }
 263 
 264 bool ShenandoahHeuristics::should_process_references() {
 265   if (!can_process_references()) return false;
 266   size_t cycle = ShenandoahHeap::heap()->shenandoah_policy()->cycle_counter();
 267   // Process references every Nth GC cycle.
 268   return cycle % ShenandoahRefProcFrequency == 0;
 269 }
 270 
 271 bool ShenandoahHeuristics::can_unload_classes() {
 272   if (!ClassUnloading) return false;
 273   return true;
 274 }
 275 
 276 bool ShenandoahHeuristics::can_unload_classes_normal() {
 277   if (!can_unload_classes()) return false;
 278   if (has_metaspace_oom()) return true;
 279   if (!ClassUnloadingWithConcurrentMark) return false;
 280   if (ShenandoahUnloadClassesFrequency == 0) return false;
 281   return true;
 282 }
 283 
 284 bool ShenandoahHeuristics::should_unload_classes() {
 285   if (!can_unload_classes_normal()) return false;
 286   if (has_metaspace_oom()) return true;
 287   size_t cycle = ShenandoahHeap::heap()->shenandoah_policy()->cycle_counter();
 288   // Unload classes every Nth GC cycle.
 289   // This should not happen in the same cycle as process_references to amortize costs.
 290   // Offsetting by one is enough to break the rendezvous when periods are equal.
 291   // When periods are not equal, offsetting by one is just as good as any other guess.
 292   return (cycle + 1) % ShenandoahUnloadClassesFrequency == 0;
 293 }
 294 
 295 void ShenandoahHeuristics::initialize() {
 296   // Nothing to do by default.
 297 }
 298 
 299 double ShenandoahHeuristics::time_since_last_gc() const {
 300   return os::elapsedTime() - _cycle_start;
 301 }