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