1 /*
  2  * Copyright (c) 2018, 2021, Red Hat, Inc. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "gc/shared/gcCause.hpp"
 27 #include "gc/shenandoah/shenandoahAllocRequest.hpp"
 28 #include "gc/shenandoah/shenandoahCollectionSet.inline.hpp"
 29 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
 30 #include "gc/shenandoah/shenandoahGeneration.hpp"
 31 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 32 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
 33 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
 34 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
 35 #include "gc/shenandoah/mode/shenandoahMode.hpp"
 36 #include "logging/log.hpp"
 37 #include "logging/logTag.hpp"
 38 #include "runtime/globals_extension.hpp"
 39 
 40 int ShenandoahHeuristics::compare_by_garbage(RegionData a, RegionData b) {
 41   if (a._garbage > b._garbage)
 42     return -1;
 43   else if (a._garbage < b._garbage)
 44     return 1;
 45   else return 0;
 46 }
 47 
 48 ShenandoahHeuristics::ShenandoahHeuristics(ShenandoahGeneration* generation) :
 49   _generation(generation),
 50   _region_data(NULL),
 51   _degenerated_cycles_in_a_row(0),
 52   _successful_cycles_in_a_row(0),
 53   _guaranteed_gc_interval(0),
 54   _cycle_start(os::elapsedTime()),
 55   _last_cycle_end(0),
 56   _gc_times_learned(0),
 57   _gc_time_penalties(0),
 58   _gc_time_history(new TruncatedSeq(10, ShenandoahAdaptiveDecayFactor)),
 59   _metaspace_oom()
 60 {
 61   // No unloading during concurrent mark? Communicate that to heuristics
 62   if (!ClassUnloadingWithConcurrentMark) {
 63     FLAG_SET_DEFAULT(ShenandoahUnloadClassesFrequency, 0);
 64   }
 65 
 66   size_t num_regions = ShenandoahHeap::heap()->num_regions();
 67   assert(num_regions > 0, "Sanity");
 68 
 69   _region_data = NEW_C_HEAP_ARRAY(RegionData, num_regions, mtGC);
 70 }
 71 
 72 ShenandoahHeuristics::~ShenandoahHeuristics() {
 73   FREE_C_HEAP_ARRAY(RegionGarbage, _region_data);
 74 }
 75 
 76 // Returns true iff the chosen collection set includes old-gen regions
 77 bool ShenandoahHeuristics::choose_collection_set(ShenandoahCollectionSet* collection_set, ShenandoahOldHeuristics* old_heuristics) {
 78   bool result = false;
 79   ShenandoahHeap* heap = ShenandoahHeap::heap();
 80 
 81   assert(collection_set->count() == 0, "Must be empty");
 82   assert(_generation->generation_mode() != OLD, "Old GC invokes ShenandoahOldHeuristics::choose_collection_set()");
 83 
 84   // Check all pinned regions have updated status before choosing the collection set.
 85   heap->assert_pinned_region_status();
 86 
 87   // Step 1. Build up the region candidates we care about, rejecting losers and accepting winners right away.
 88 
 89   size_t num_regions = heap->num_regions();
 90 
 91   RegionData* candidates = _region_data;
 92 
 93   size_t cand_idx = 0;
 94 
 95   size_t total_garbage = 0;
 96 
 97   size_t immediate_garbage = 0;
 98   size_t immediate_regions = 0;
 99 
100   size_t free = 0;
101   size_t free_regions = 0;
102 
103   ShenandoahMarkingContext* const ctx = _generation->complete_marking_context();
104 
105   for (size_t i = 0; i < num_regions; i++) {
106     ShenandoahHeapRegion* region = heap->get_region(i);
107     if (!in_generation(region)) {
108       continue;
109     }
110 
111     size_t garbage = region->garbage();
112     total_garbage += garbage;
113 
114     if (region->is_empty()) {
115       free_regions++;
116       free += ShenandoahHeapRegion::region_size_bytes();
117     } else if (region->is_regular()) {
118       if (!region->has_live()) {
119         // We can recycle it right away and put it in the free set.
120         immediate_regions++;
121         immediate_garbage += garbage;
122         region->make_trash_immediate();
123       } else {
124         assert (_generation->generation_mode() != OLD, "OLD is handled elsewhere");
125 
126         // This is our candidate for later consideration.
127         candidates[cand_idx]._region = region;
128         if (heap->mode()->is_generational() && (region->age() >= InitialTenuringThreshold)) {
129           // Bias selection of regions that have reached tenure age
130           for (int i = region->age() - InitialTenuringThreshold; i >= 0; i--) {
131             // Avoid floating-point math with integer multiply and shift.
132             garbage = (garbage * ShenandoahTenuredRegionUsageBias) >> ShenandoahTenuredRegionUsageBiasLogBase2;
133           }
134         }
135         candidates[cand_idx]._garbage = garbage;
136         cand_idx++;
137       }
138     } else if (region->is_humongous_start()) {
139 
140       // Reclaim humongous regions here, and count them as the immediate garbage
141 #ifdef ASSERT
142       bool reg_live = region->has_live();
143       bool bm_live = ctx->is_marked(cast_to_oop(region->bottom()));
144       assert(reg_live == bm_live,
145              "Humongous liveness and marks should agree. Region live: %s; Bitmap live: %s; Region Live Words: " SIZE_FORMAT,
146              BOOL_TO_STR(reg_live), BOOL_TO_STR(bm_live), region->get_live_data_words());
147 #endif
148       if (!region->has_live()) {
149         heap->trash_humongous_region_at(region);
150 
151         // Count only the start. Continuations would be counted on "trash" path
152         immediate_regions++;
153         immediate_garbage += garbage;
154       }
155     } else if (region->is_trash()) {
156       // Count in just trashed collection set, during coalesced CM-with-UR
157       immediate_regions++;
158       immediate_garbage += garbage;
159     }
160   }
161 
162   // Step 2. Look back at garbage statistics, and decide if we want to collect anything,
163   // given the amount of immediately reclaimable garbage. If we do, figure out the collection set.
164 
165   assert (immediate_garbage <= total_garbage,
166           "Cannot have more immediate garbage than total garbage: " SIZE_FORMAT "%s vs " SIZE_FORMAT "%s",
167           byte_size_in_proper_unit(immediate_garbage), proper_unit_for_byte_size(immediate_garbage),
168           byte_size_in_proper_unit(total_garbage),     proper_unit_for_byte_size(total_garbage));
169 
170   size_t immediate_percent = (total_garbage == 0) ? 0 : (immediate_garbage * 100 / total_garbage);
171 
172   if (immediate_percent <= ShenandoahImmediateThreshold) {
173 
174     if (old_heuristics != NULL) {
175       if (old_heuristics->prime_collection_set(collection_set)) {
176         result = true;
177       }
178     }
179     // else, this is global collection and doesn't need to prime_collection_set
180 
181     // Add young-gen regions into the collection set.  This is a virtual call, implemented differently by each
182     // of the heuristics subclasses.
183     choose_collection_set_from_regiondata(collection_set, candidates, cand_idx, immediate_garbage + free);
184   }
185 
186   size_t cset_percent = (total_garbage == 0) ? 0 : (collection_set->garbage() * 100 / total_garbage);
187 
188   size_t collectable_garbage = collection_set->garbage() + immediate_garbage;
189   size_t collectable_garbage_percent = (total_garbage == 0) ? 0 : (collectable_garbage * 100 / total_garbage);
190 
191   log_info(gc, ergo)("Collectable Garbage: " SIZE_FORMAT "%s (" SIZE_FORMAT "%%), "
192                      "Immediate: " SIZE_FORMAT "%s (" SIZE_FORMAT "%%), "
193                      "CSet: " SIZE_FORMAT "%s (" SIZE_FORMAT "%%)",
194 
195                      byte_size_in_proper_unit(collectable_garbage),
196                      proper_unit_for_byte_size(collectable_garbage),
197                      collectable_garbage_percent,
198 
199                      byte_size_in_proper_unit(immediate_garbage),
200                      proper_unit_for_byte_size(immediate_garbage),
201                      immediate_percent,
202 
203                      byte_size_in_proper_unit(collection_set->garbage()),
204                      proper_unit_for_byte_size(collection_set->garbage()),
205                      cset_percent);
206   return result;
207 }
208 
209 void ShenandoahHeuristics::record_cycle_start() {
210   _cycle_start = os::elapsedTime();
211 }
212 
213 void ShenandoahHeuristics::record_cycle_end() {
214   _last_cycle_end = os::elapsedTime();
215 }
216 
217 bool ShenandoahHeuristics::should_start_gc() {
218   // Perform GC to cleanup metaspace
219   if (has_metaspace_oom()) {
220     // Some of vmTestbase/metaspace tests depend on following line to count GC cycles
221     log_info(gc)("Trigger: %s", GCCause::to_string(GCCause::_metadata_GC_threshold));
222     return true;
223   }
224 
225   if (_guaranteed_gc_interval > 0) {
226     double last_time_ms = (os::elapsedTime() - _last_cycle_end) * 1000;
227     if (last_time_ms > _guaranteed_gc_interval) {
228       log_info(gc)("Trigger (%s): Time since last GC (%.0f ms) is larger than guaranteed interval (" UINTX_FORMAT " ms)",
229                    _generation->name(), last_time_ms, _guaranteed_gc_interval);
230       return true;
231     }
232   }
233 
234   return false;
235 }
236 
237 bool ShenandoahHeuristics::should_degenerate_cycle() {
238   return _degenerated_cycles_in_a_row <= ShenandoahFullGCThreshold;
239 }
240 
241 void ShenandoahHeuristics::adjust_penalty(intx step) {
242   assert(0 <= _gc_time_penalties && _gc_time_penalties <= 100,
243          "In range before adjustment: " INTX_FORMAT, _gc_time_penalties);
244 
245   intx new_val = _gc_time_penalties + step;
246   if (new_val < 0) {
247     new_val = 0;
248   }
249   if (new_val > 100) {
250     new_val = 100;
251   }
252   _gc_time_penalties = new_val;
253 
254   assert(0 <= _gc_time_penalties && _gc_time_penalties <= 100,
255          "In range after adjustment: " INTX_FORMAT, _gc_time_penalties);
256 }
257 
258 void ShenandoahHeuristics::record_success_concurrent() {
259   _degenerated_cycles_in_a_row = 0;
260   _successful_cycles_in_a_row++;
261 
262   _gc_time_history->add(time_since_last_gc());
263   _gc_times_learned++;
264 
265   adjust_penalty(Concurrent_Adjust);
266 }
267 
268 void ShenandoahHeuristics::record_success_degenerated() {
269   _degenerated_cycles_in_a_row++;
270   _successful_cycles_in_a_row = 0;
271 
272   adjust_penalty(Degenerated_Penalty);
273 }
274 
275 void ShenandoahHeuristics::record_success_full() {
276   _degenerated_cycles_in_a_row = 0;
277   _successful_cycles_in_a_row++;
278 
279   adjust_penalty(Full_Penalty);
280 }
281 
282 void ShenandoahHeuristics::record_allocation_failure_gc() {
283   // Do nothing.
284 }
285 
286 void ShenandoahHeuristics::record_requested_gc() {
287   // Assume users call System.gc() when external state changes significantly,
288   // which forces us to re-learn the GC timings and allocation rates.
289   _gc_times_learned = 0;
290 }
291 
292 bool ShenandoahHeuristics::can_unload_classes() {
293   if (!ClassUnloading) return false;
294   return true;
295 }
296 
297 bool ShenandoahHeuristics::can_unload_classes_normal() {
298   if (!can_unload_classes()) return false;
299   if (has_metaspace_oom()) return true;
300   if (!ClassUnloadingWithConcurrentMark) return false;
301   if (ShenandoahUnloadClassesFrequency == 0) return false;
302   return true;
303 }
304 
305 bool ShenandoahHeuristics::should_unload_classes() {
306   if (!can_unload_classes_normal()) return false;
307   if (has_metaspace_oom()) return true;
308   size_t cycle = ShenandoahHeap::heap()->shenandoah_policy()->cycle_counter();
309   // Unload classes every Nth GC cycle.
310   // This should not happen in the same cycle as process_references to amortize costs.
311   // Offsetting by one is enough to break the rendezvous when periods are equal.
312   // When periods are not equal, offsetting by one is just as good as any other guess.
313   return (cycle + 1) % ShenandoahUnloadClassesFrequency == 0;
314 }
315 
316 void ShenandoahHeuristics::initialize() {
317   // Nothing to do by default.
318 }
319 
320 double ShenandoahHeuristics::time_since_last_gc() const {
321   return os::elapsedTime() - _cycle_start;
322 }
323 
324 bool ShenandoahHeuristics::in_generation(ShenandoahHeapRegion* region) {
325   return ((_generation->generation_mode() == GLOBAL)
326           || (_generation->generation_mode() == YOUNG && region->affiliation() == YOUNG_GENERATION)
327           || (_generation->generation_mode() == OLD && region->affiliation() == OLD_GENERATION));
328 }
329