1 /*
  2  * Copyright Amazon.com Inc. or its affiliates. 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 
 27 #include "gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp"
 28 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
 29 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
 30 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp"
 31 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
 32 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
 33 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
 34 #include "logging/log.hpp"
 35 #include "utilities/quickSort.hpp"
 36 
 37 uint ShenandoahOldHeuristics::NOT_FOUND = -1U;
 38 
 39 // sort by increasing live (so least live comes first)
 40 int ShenandoahOldHeuristics::compare_by_live(RegionData a, RegionData b) {
 41   if (a.get_livedata() < b.get_livedata()) {
 42     return -1;
 43   } else if (a.get_livedata() > b.get_livedata()) {
 44     return 1;
 45   } else {
 46     return 0;
 47   }
 48 }
 49 
 50 // sort by increasing index
 51 int ShenandoahOldHeuristics::compare_by_index(RegionData a, RegionData b) {
 52   if (a.get_region()->index() < b.get_region()->index()) {
 53     return -1;
 54   } else if (a.get_region()->index() > b.get_region()->index()) {
 55     return 1;
 56   } else {
 57     // quicksort may compare to self during search for pivot
 58     return 0;
 59   }
 60 }
 61 
 62 ShenandoahOldHeuristics::ShenandoahOldHeuristics(ShenandoahOldGeneration* generation, ShenandoahGenerationalHeap* gen_heap) :
 63   ShenandoahHeuristics(generation),
 64   _heap(gen_heap),
 65   _old_gen(generation),
 66   _first_pinned_candidate(NOT_FOUND),
 67   _last_old_collection_candidate(0),
 68   _next_old_collection_candidate(0),
 69   _last_old_region(0),
 70   _live_bytes_in_unprocessed_candidates(0),
 71   _old_generation(generation),
 72   _cannot_expand_trigger(false),
 73   _fragmentation_trigger(false),
 74   _growth_trigger(false),
 75   _fragmentation_density(0.0),
 76   _fragmentation_first_old_region(0),
 77   _fragmentation_last_old_region(0)
 78 {
 79 }
 80 
 81 bool ShenandoahOldHeuristics::prime_collection_set(ShenandoahCollectionSet* collection_set) {
 82   if (unprocessed_old_collection_candidates() == 0) {
 83     return false;
 84   }
 85 
 86   if (_old_generation->is_preparing_for_mark()) {
 87     // We have unprocessed old collection candidates, but the heuristic has given up on evacuating them.
 88     // This is most likely because they were _all_ pinned at the time of the last mixed evacuation (and
 89     // this in turn is most likely because there are just one or two candidate regions remaining).
 90     log_info(gc, ergo)("Remaining " UINT32_FORMAT " old regions are being coalesced and filled", unprocessed_old_collection_candidates());
 91     return false;
 92   }
 93 
 94   _first_pinned_candidate = NOT_FOUND;
 95 
 96   uint included_old_regions = 0;
 97   size_t evacuated_old_bytes = 0;
 98   size_t collected_old_bytes = 0;
 99 
100   // If a region is put into the collection set, then this region's free (not yet used) bytes are no longer
101   // "available" to hold the results of other evacuations.  This may cause a decrease in the remaining amount
102   // of memory that can still be evacuated.  We address this by reducing the evacuation budget by the amount
103   // of live memory in that region and by the amount of unallocated memory in that region if the evacuation
104   // budget is constrained by availability of free memory.
105   const size_t old_evacuation_reserve = _old_generation->get_evacuation_reserve();
106   const size_t old_evacuation_budget = (size_t) ((double) old_evacuation_reserve / ShenandoahOldEvacWaste);
107   size_t unfragmented_available = _old_generation->free_unaffiliated_regions() * ShenandoahHeapRegion::region_size_bytes();
108   size_t fragmented_available;
109   size_t excess_fragmented_available;
110 
111   if (unfragmented_available > old_evacuation_budget) {
112     unfragmented_available = old_evacuation_budget;
113     fragmented_available = 0;
114     excess_fragmented_available = 0;
115   } else {
116     assert(_old_generation->available() >= old_evacuation_budget, "Cannot budget more than is available");
117     fragmented_available = _old_generation->available() - unfragmented_available;
118     assert(fragmented_available + unfragmented_available >= old_evacuation_budget, "Budgets do not add up");
119     if (fragmented_available + unfragmented_available > old_evacuation_budget) {
120       excess_fragmented_available = (fragmented_available + unfragmented_available) - old_evacuation_budget;
121       fragmented_available -= excess_fragmented_available;
122     }
123   }
124 
125   size_t remaining_old_evacuation_budget = old_evacuation_budget;
126   log_debug(gc)("Choose old regions for mixed collection: old evacuation budget: " SIZE_FORMAT "%s, candidates: %u",
127                 byte_size_in_proper_unit(old_evacuation_budget), proper_unit_for_byte_size(old_evacuation_budget),
128                 unprocessed_old_collection_candidates());
129 
130   size_t lost_evacuation_capacity = 0;
131 
132   // The number of old-gen regions that were selected as candidates for collection at the end of the most recent old-gen
133   // concurrent marking phase and have not yet been collected is represented by unprocessed_old_collection_candidates().
134   // Candidate regions are ordered according to increasing amount of live data.  If there is not sufficient room to
135   // evacuate region N, then there is no need to even consider evacuating region N+1.
136   while (unprocessed_old_collection_candidates() > 0) {
137     // Old collection candidates are sorted in order of decreasing garbage contained therein.
138     ShenandoahHeapRegion* r = next_old_collection_candidate();
139     if (r == nullptr) {
140       break;
141     }
142     assert(r->is_regular(), "There should be no humongous regions in the set of mixed-evac candidates");
143 
144     // If region r is evacuated to fragmented memory (to free memory within a partially used region), then we need
145     // to decrease the capacity of the fragmented memory by the scaled loss.
146 
147     size_t live_data_for_evacuation = r->get_live_data_bytes();
148     size_t lost_available = r->free();
149 
150     if ((lost_available > 0) && (excess_fragmented_available > 0)) {
151       if (lost_available < excess_fragmented_available) {
152         excess_fragmented_available -= lost_available;
153         lost_evacuation_capacity -= lost_available;
154         lost_available  = 0;
155       } else {
156         lost_available -= excess_fragmented_available;
157         lost_evacuation_capacity -= excess_fragmented_available;
158         excess_fragmented_available = 0;
159       }
160     }
161     size_t scaled_loss = (size_t) ((double) lost_available / ShenandoahOldEvacWaste);
162     if ((lost_available > 0) && (fragmented_available > 0)) {
163       if (scaled_loss + live_data_for_evacuation < fragmented_available) {
164         fragmented_available -= scaled_loss;
165         scaled_loss = 0;
166       } else {
167         // We will have to allocate this region's evacuation memory from unfragmented memory, so don't bother
168         // to decrement scaled_loss
169       }
170     }
171     if (scaled_loss > 0) {
172       // We were not able to account for the lost free memory within fragmented memory, so we need to take this
173       // allocation out of unfragmented memory.  Unfragmented memory does not need to account for loss of free.
174       if (live_data_for_evacuation > unfragmented_available) {
175         // There is not room to evacuate this region or any that come after it in within the candidates array.
176         break;
177       } else {
178         unfragmented_available -= live_data_for_evacuation;
179       }
180     } else {
181       // Since scaled_loss == 0, we have accounted for the loss of free memory, so we can allocate from either
182       // fragmented or unfragmented available memory.  Use up the fragmented memory budget first.
183       size_t evacuation_need = live_data_for_evacuation;
184 
185       if (evacuation_need > fragmented_available) {
186         evacuation_need -= fragmented_available;
187         fragmented_available = 0;
188       } else {
189         fragmented_available -= evacuation_need;
190         evacuation_need = 0;
191       }
192       if (evacuation_need > unfragmented_available) {
193         // There is not room to evacuate this region or any that come after it in within the candidates array.
194         break;
195       } else {
196         unfragmented_available -= evacuation_need;
197         // dead code: evacuation_need == 0;
198       }
199     }
200     collection_set->add_region(r);
201     included_old_regions++;
202     evacuated_old_bytes += live_data_for_evacuation;
203     collected_old_bytes += r->garbage();
204     consume_old_collection_candidate();
205   }
206 
207   if (_first_pinned_candidate != NOT_FOUND) {
208     // Need to deal with pinned regions
209     slide_pinned_regions_to_front();
210   }
211   decrease_unprocessed_old_collection_candidates_live_memory(evacuated_old_bytes);
212   if (included_old_regions > 0) {
213     log_info(gc, ergo)("Old-gen piggyback evac (" UINT32_FORMAT " regions, evacuating " PROPERFMT ", reclaiming: " PROPERFMT ")",
214                   included_old_regions, PROPERFMTARGS(evacuated_old_bytes), PROPERFMTARGS(collected_old_bytes));
215   }
216 
217   if (unprocessed_old_collection_candidates() == 0) {
218     // We have added the last of our collection candidates to a mixed collection.
219     // Any triggers that occurred during mixed evacuations may no longer be valid.  They can retrigger if appropriate.
220     clear_triggers();
221 
222     _old_generation->complete_mixed_evacuations();
223   } else if (included_old_regions == 0) {
224     // We have candidates, but none were included for evacuation - are they all pinned?
225     // or did we just not have enough room for any of them in this collection set?
226     // We don't want a region with a stuck pin to prevent subsequent old collections, so
227     // if they are all pinned we transition to a state that will allow us to make these uncollected
228     // (pinned) regions parsable.
229     if (all_candidates_are_pinned()) {
230       log_info(gc, ergo)("All candidate regions " UINT32_FORMAT " are pinned", unprocessed_old_collection_candidates());
231       _old_generation->abandon_mixed_evacuations();
232     } else {
233       log_info(gc, ergo)("No regions selected for mixed collection. "
234                          "Old evacuation budget: " PROPERFMT ", Remaining evacuation budget: " PROPERFMT
235                          ", Lost capacity: " PROPERFMT
236                          ", Next candidate: " UINT32_FORMAT ", Last candidate: " UINT32_FORMAT,
237                          PROPERFMTARGS(old_evacuation_reserve),
238                          PROPERFMTARGS(remaining_old_evacuation_budget),
239                          PROPERFMTARGS(lost_evacuation_capacity),
240                          _next_old_collection_candidate, _last_old_collection_candidate);
241     }
242   }
243 
244   return (included_old_regions > 0);
245 }
246 
247 bool ShenandoahOldHeuristics::all_candidates_are_pinned() {
248 #ifdef ASSERT
249   if (uint(os::random()) % 100 < ShenandoahCoalesceChance) {
250     return true;
251   }
252 #endif
253 
254   for (uint i = _next_old_collection_candidate; i < _last_old_collection_candidate; ++i) {
255     ShenandoahHeapRegion* region = _region_data[i].get_region();
256     if (!region->is_pinned()) {
257       return false;
258     }
259   }
260   return true;
261 }
262 
263 void ShenandoahOldHeuristics::slide_pinned_regions_to_front() {
264   // Find the first unpinned region to the left of the next region that
265   // will be added to the collection set. These regions will have been
266   // added to the cset, so we can use them to hold pointers to regions
267   // that were pinned when the cset was chosen.
268   // [ r p r p p p r r ]
269   //     ^         ^ ^
270   //     |         | | pointer to next region to add to a mixed collection is here.
271   //     |         | first r to the left should be in the collection set now.
272   //     | first pinned region, we don't need to look past this
273   uint write_index = NOT_FOUND;
274   for (uint search = _next_old_collection_candidate - 1; search > _first_pinned_candidate; --search) {
275     ShenandoahHeapRegion* region = _region_data[search].get_region();
276     if (!region->is_pinned()) {
277       write_index = search;
278       assert(region->is_cset(), "Expected unpinned region to be added to the collection set.");
279       break;
280     }
281   }
282 
283   // If we could not find an unpinned region, it means there are no slots available
284   // to move up the pinned regions. In this case, we just reset our next index in the
285   // hopes that some of these regions will become unpinned before the next mixed
286   // collection. We may want to bailout of here instead, as it should be quite
287   // rare to have so many pinned regions and may indicate something is wrong.
288   if (write_index == NOT_FOUND) {
289     assert(_first_pinned_candidate != NOT_FOUND, "Should only be here if there are pinned regions.");
290     _next_old_collection_candidate = _first_pinned_candidate;
291     return;
292   }
293 
294   // Find pinned regions to the left and move their pointer into a slot
295   // that was pointing at a region that has been added to the cset (or was pointing
296   // to a pinned region that we've already moved up). We are done when the leftmost
297   // pinned region has been slid up.
298   // [ r p r x p p p r ]
299   //         ^       ^
300   //         |       | next region for mixed collections
301   //         | Write pointer is here. We know this region is already in the cset
302   //         | so we can clobber it with the next pinned region we find.
303   for (int32_t search = (int32_t)write_index - 1; search >= (int32_t)_first_pinned_candidate; --search) {
304     RegionData& skipped = _region_data[search];
305     if (skipped.get_region()->is_pinned()) {
306       RegionData& available_slot = _region_data[write_index];
307       available_slot.set_region_and_livedata(skipped.get_region(), skipped.get_livedata());
308       --write_index;
309     }
310   }
311 
312   // Update to read from the leftmost pinned region. Plus one here because we decremented
313   // the write index to hold the next found pinned region. We are just moving it back now
314   // to point to the first pinned region.
315   _next_old_collection_candidate = write_index + 1;
316 }
317 
318 void ShenandoahOldHeuristics::prepare_for_old_collections() {
319   ShenandoahHeap* heap = ShenandoahHeap::heap();
320 
321   const size_t num_regions = heap->num_regions();
322   size_t cand_idx = 0;
323   size_t immediate_garbage = 0;
324   size_t immediate_regions = 0;
325   size_t live_data = 0;
326 
327   RegionData* candidates = _region_data;
328   for (size_t i = 0; i < num_regions; i++) {
329     ShenandoahHeapRegion* region = heap->get_region(i);
330     if (!region->is_old()) {
331       continue;
332     }
333 
334     size_t garbage = region->garbage();
335     size_t live_bytes = region->get_live_data_bytes();
336     live_data += live_bytes;
337 
338     if (region->is_regular() || region->is_regular_pinned()) {
339         // Only place regular or pinned regions with live data into the candidate set.
340         // Pinned regions cannot be evacuated, but we are not actually choosing candidates
341         // for the collection set here. That happens later during the next young GC cycle,
342         // by which time, the pinned region may no longer be pinned.
343       if (!region->has_live()) {
344         assert(!region->is_pinned(), "Pinned region should have live (pinned) objects.");
345         region->make_trash_immediate();
346         immediate_regions++;
347         immediate_garbage += garbage;
348       } else {
349         region->begin_preemptible_coalesce_and_fill();
350         candidates[cand_idx].set_region_and_livedata(region, live_bytes);
351         cand_idx++;
352       }
353     } else if (region->is_humongous_start()) {
354       // This will handle humongous start regions whether they are also pinned, or not.
355       // If they are pinned, we expect them to hold live data, so they will not be
356       // turned into immediate garbage.
357       if (!region->has_live()) {
358         assert(!region->is_pinned(), "Pinned region should have live (pinned) objects.");
359         // The humongous object is dead, we can just return this region and the continuations
360         // immediately to the freeset - no evacuations are necessary here. The continuations
361         // will be made into trash by this method, so they'll be skipped by the 'is_regular'
362         // check above, but we still need to count the start region.
363         immediate_regions++;
364         immediate_garbage += garbage;
365         size_t region_count = heap->trash_humongous_region_at(region);
366         log_debug(gc)("Trashed " SIZE_FORMAT " regions for humongous object.", region_count);
367       }
368     } else if (region->is_trash()) {
369       // Count humongous objects made into trash here.
370       immediate_regions++;
371       immediate_garbage += garbage;
372     }
373   }
374 
375   _old_generation->set_live_bytes_after_last_mark(live_data);
376 
377   // Unlike young, we are more interested in efficiently packing OLD-gen than in reclaiming garbage first.  We sort by live-data.
378   // Some regular regions may have been promoted in place with no garbage but also with very little live data.  When we "compact"
379   // old-gen, we want to pack these underutilized regions together so we can have more unaffiliated (unfragmented) free regions
380   // in old-gen.
381 
382   QuickSort::sort<RegionData>(candidates, cand_idx, compare_by_live, false);
383 
384   const size_t region_size_bytes = ShenandoahHeapRegion::region_size_bytes();
385 
386   // The convention is to collect regions that have more than this amount of garbage.
387   const size_t garbage_threshold = region_size_bytes * ShenandoahOldGarbageThreshold / 100;
388 
389   // Enlightened interpretation: collect regions that have less than this amount of live.
390   const size_t live_threshold = region_size_bytes - garbage_threshold;
391 
392   _last_old_region = (uint)cand_idx;
393   _last_old_collection_candidate = (uint)cand_idx;
394   _next_old_collection_candidate = 0;
395 
396   size_t unfragmented = 0;
397   size_t candidates_garbage = 0;
398 
399   for (size_t i = 0; i < cand_idx; i++) {
400     size_t live = candidates[i].get_livedata();
401     if (live > live_threshold) {
402       // Candidates are sorted in increasing order of live data, so no regions after this will be below the threshold.
403       _last_old_collection_candidate = (uint)i;
404       break;
405     }
406     ShenandoahHeapRegion* r = candidates[i].get_region();
407     size_t region_garbage = r->garbage();
408     size_t region_free = r->free();
409     candidates_garbage += region_garbage;
410     unfragmented += region_free;
411   }
412 
413   // defrag_count represents regions that are placed into the old collection set in order to defragment the memory
414   // that we try to "reserve" for humongous allocations.
415   size_t defrag_count = 0;
416   size_t total_uncollected_old_regions = _last_old_region - _last_old_collection_candidate;
417 
418   if (cand_idx > _last_old_collection_candidate) {
419     // Above, we have added into the set of mixed-evacuation candidates all old-gen regions for which the live memory
420     // that they contain is below a particular old-garbage threshold.  Regions that were not selected for the collection
421     // set hold enough live memory that it is not considered efficient (by "garbage-first standards") to compact these
422     // at the current time.
423     //
424     // However, if any of these regions that were rejected from the collection set reside within areas of memory that
425     // might interfere with future humongous allocation requests, we will prioritize them for evacuation at this time.
426     // Humongous allocations target the bottom of the heap.  We want old-gen regions to congregate at the top of the
427     // heap.
428     //
429     // Sort the regions that were initially rejected from the collection set in order of index.  This allows us to
430     // focus our attention on the regions that have low index value (i.e. the old-gen regions at the bottom of the heap).
431     QuickSort::sort<RegionData>(candidates + _last_old_collection_candidate, cand_idx - _last_old_collection_candidate,
432                                 compare_by_index, false);
433 
434     const size_t first_unselected_old_region = candidates[_last_old_collection_candidate].get_region()->index();
435     const size_t last_unselected_old_region = candidates[cand_idx - 1].get_region()->index();
436     size_t span_of_uncollected_regions = 1 + last_unselected_old_region - first_unselected_old_region;
437 
438     // Add no more than 1/8 of the existing old-gen regions to the set of mixed evacuation candidates.
439     const int MAX_FRACTION_OF_HUMONGOUS_DEFRAG_REGIONS = 8;
440     const size_t bound_on_additional_regions = cand_idx / MAX_FRACTION_OF_HUMONGOUS_DEFRAG_REGIONS;
441 
442     // The heuristic old_is_fragmented trigger may be seeking to achieve up to 75% density.  Allow ourselves to overshoot
443     // that target (at 7/8) so we will not have to do another defragmenting old collection right away.
444     while ((defrag_count < bound_on_additional_regions) &&
445            (total_uncollected_old_regions < 7 * span_of_uncollected_regions / 8)) {
446       ShenandoahHeapRegion* r = candidates[_last_old_collection_candidate].get_region();
447       assert(r->is_regular() || r->is_regular_pinned(), "Region " SIZE_FORMAT " has wrong state for collection: %s",
448              r->index(), ShenandoahHeapRegion::region_state_to_string(r->state()));
449       const size_t region_garbage = r->garbage();
450       const size_t region_free = r->free();
451       candidates_garbage += region_garbage;
452       unfragmented += region_free;
453       defrag_count++;
454       _last_old_collection_candidate++;
455 
456       // We now have one fewer uncollected regions, and our uncollected span shrinks because we have removed its first region.
457       total_uncollected_old_regions--;
458       span_of_uncollected_regions =
459         1 + last_unselected_old_region - candidates[_last_old_collection_candidate].get_region()->index();
460     }
461   }
462 
463   // Note that we do not coalesce and fill occupied humongous regions
464   // HR: humongous regions, RR: regular regions, CF: coalesce and fill regions
465   const size_t collectable_garbage = immediate_garbage + candidates_garbage;
466   const size_t old_candidates = _last_old_collection_candidate;
467   const size_t mixed_evac_live = old_candidates * region_size_bytes - (candidates_garbage + unfragmented);
468   set_unprocessed_old_collection_candidates_live_memory(mixed_evac_live);
469 
470   log_info(gc, ergo)("Old-Gen Collectable Garbage: " PROPERFMT " consolidated with free: " PROPERFMT ", over " SIZE_FORMAT " regions",
471                      PROPERFMTARGS(collectable_garbage), PROPERFMTARGS(unfragmented), old_candidates);
472   log_info(gc, ergo)("Old-Gen Immediate Garbage: " PROPERFMT " over " SIZE_FORMAT " regions",
473                      PROPERFMTARGS(immediate_garbage), immediate_regions);
474   log_info(gc, ergo)("Old regions selected for defragmentation: " SIZE_FORMAT, defrag_count);
475   log_info(gc, ergo)("Old regions not selected: " SIZE_FORMAT, total_uncollected_old_regions);
476 
477   if (unprocessed_old_collection_candidates() > 0) {
478     _old_generation->transition_to(ShenandoahOldGeneration::EVACUATING);
479   } else if (has_coalesce_and_fill_candidates()) {
480     _old_generation->transition_to(ShenandoahOldGeneration::FILLING);
481   } else {
482     _old_generation->transition_to(ShenandoahOldGeneration::WAITING_FOR_BOOTSTRAP);
483   }
484 }
485 
486 size_t ShenandoahOldHeuristics::unprocessed_old_collection_candidates_live_memory() const {
487   return _live_bytes_in_unprocessed_candidates;
488 }
489 
490 void ShenandoahOldHeuristics::set_unprocessed_old_collection_candidates_live_memory(size_t initial_live) {
491   _live_bytes_in_unprocessed_candidates = initial_live;
492 }
493 
494 void ShenandoahOldHeuristics::decrease_unprocessed_old_collection_candidates_live_memory(size_t evacuated_live) {
495   assert(evacuated_live <= _live_bytes_in_unprocessed_candidates, "Cannot evacuate more than was present");
496   _live_bytes_in_unprocessed_candidates -= evacuated_live;
497 }
498 
499 // Used by unit test: test_shenandoahOldHeuristic.cpp
500 uint ShenandoahOldHeuristics::last_old_collection_candidate_index() const {
501   return _last_old_collection_candidate;
502 }
503 
504 uint ShenandoahOldHeuristics::unprocessed_old_collection_candidates() const {
505   return _last_old_collection_candidate - _next_old_collection_candidate;
506 }
507 
508 ShenandoahHeapRegion* ShenandoahOldHeuristics::next_old_collection_candidate() {
509   while (_next_old_collection_candidate < _last_old_collection_candidate) {
510     ShenandoahHeapRegion* next = _region_data[_next_old_collection_candidate].get_region();
511     if (!next->is_pinned()) {
512       return next;
513     } else {
514       assert(next->is_pinned(), "sanity");
515       if (_first_pinned_candidate == NOT_FOUND) {
516         _first_pinned_candidate = _next_old_collection_candidate;
517       }
518     }
519 
520     _next_old_collection_candidate++;
521   }
522   return nullptr;
523 }
524 
525 void ShenandoahOldHeuristics::consume_old_collection_candidate() {
526   _next_old_collection_candidate++;
527 }
528 
529 unsigned int ShenandoahOldHeuristics::get_coalesce_and_fill_candidates(ShenandoahHeapRegion** buffer) {
530   uint end = _last_old_region;
531   uint index = _next_old_collection_candidate;
532   while (index < end) {
533     *buffer++ = _region_data[index++].get_region();
534   }
535   return (_last_old_region - _next_old_collection_candidate);
536 }
537 
538 void ShenandoahOldHeuristics::abandon_collection_candidates() {
539   _last_old_collection_candidate = 0;
540   _next_old_collection_candidate = 0;
541   _last_old_region = 0;
542 }
543 
544 void ShenandoahOldHeuristics::record_cycle_end() {
545   this->ShenandoahHeuristics::record_cycle_end();
546   clear_triggers();
547 }
548 
549 void ShenandoahOldHeuristics::clear_triggers() {
550   // Clear any triggers that were set during mixed evacuations.  Conditions may be different now that this phase has finished.
551   _cannot_expand_trigger = false;
552   _fragmentation_trigger = false;
553   _growth_trigger = false;
554 }
555 
556 // This triggers old-gen collection if the number of regions "dedicated" to old generation is much larger than
557 // is required to represent the memory currently used within the old generation.  This trigger looks specifically
558 // at density of the old-gen spanned region.  A different mechanism triggers old-gen GC if the total number of
559 // old-gen regions (regardless of how close the regions are to one another) grows beyond an anticipated growth target.
560 void ShenandoahOldHeuristics::set_trigger_if_old_is_fragmented(size_t first_old_region, size_t last_old_region,
561                                                                size_t old_region_count, size_t num_regions) {
562   if (ShenandoahGenerationalHumongousReserve > 0) {
563     // Our intent is to pack old-gen memory into the highest-numbered regions of the heap.  Count all memory
564     // above first_old_region as the "span" of old generation.
565     size_t old_region_span = (first_old_region <= last_old_region)? (num_regions - first_old_region): 0;
566     // Given that memory at the bottom of the heap is reserved to represent humongous objects, the number of
567     // regions that old_gen is "allowed" to consume is less than the total heap size.  The restriction on allowed
568     // span is not strictly enforced.  This is a heuristic designed to reduce the likelihood that a humongous
569     // allocation request will require a STW full GC.
570     size_t allowed_old_gen_span = num_regions - (ShenandoahGenerationalHumongousReserve * num_regions) / 100;
571 
572     size_t old_available = _old_gen->available() / HeapWordSize;
573     size_t region_size_words = ShenandoahHeapRegion::region_size_words();
574     size_t old_unaffiliated_available = _old_gen->free_unaffiliated_regions() * region_size_words;
575     assert(old_available >= old_unaffiliated_available, "sanity");
576     size_t old_fragmented_available = old_available - old_unaffiliated_available;
577 
578     size_t old_words_consumed = old_region_count * region_size_words - old_fragmented_available;
579     size_t old_words_spanned = old_region_span * region_size_words;
580     double old_density = ((double) old_words_consumed) / old_words_spanned;
581 
582     double old_span_percent = ((double) old_region_span) / allowed_old_gen_span;
583     if (old_span_percent > 0.50) {
584       // Squaring old_span_percent in the denominator below allows more aggressive triggering when we are
585       // above desired maximum span and less aggressive triggering when we are far below the desired maximum span.
586       double old_span_percent_squared = old_span_percent * old_span_percent;
587       if (old_density / old_span_percent_squared < 0.75) {
588         // We trigger old defragmentation, for example, if:
589         //  old_span_percent is 110% and old_density is below 90.8%, or
590         //  old_span_percent is 100% and old_density is below 75.0%, or
591         //  old_span_percent is  90% and old_density is below 60.8%, or
592         //  old_span_percent is  80% and old_density is below 48.0%, or
593         //  old_span_percent is  70% and old_density is below 36.8%, or
594         //  old_span_percent is  60% and old_density is below 27.0%, or
595         //  old_span_percent is  50% and old_density is below 18.8%.
596 
597         // Set the fragmentation trigger and related attributes
598         _fragmentation_trigger = true;
599         _fragmentation_density = old_density;
600         _fragmentation_first_old_region = first_old_region;
601         _fragmentation_last_old_region = last_old_region;
602       }
603     }
604   }
605 }
606 
607 void ShenandoahOldHeuristics::set_trigger_if_old_is_overgrown() {
608   size_t old_used = _old_gen->used() + _old_gen->get_humongous_waste();
609   size_t trigger_threshold = _old_gen->usage_trigger_threshold();
610   // Detects unsigned arithmetic underflow
611   assert(old_used <= _heap->capacity(),
612          "Old used (" SIZE_FORMAT ", " SIZE_FORMAT") must not be more than heap capacity (" SIZE_FORMAT ")",
613          _old_gen->used(), _old_gen->get_humongous_waste(), _heap->capacity());
614   if (old_used > trigger_threshold) {
615     _growth_trigger = true;
616   }
617 }
618 
619 void ShenandoahOldHeuristics::evaluate_triggers(size_t first_old_region, size_t last_old_region,
620                                                 size_t old_region_count, size_t num_regions) {
621   set_trigger_if_old_is_fragmented(first_old_region, last_old_region, old_region_count, num_regions);
622   set_trigger_if_old_is_overgrown();
623 }
624 
625 bool ShenandoahOldHeuristics::should_start_gc() {
626   // Cannot start a new old-gen GC until previous one has finished.
627   //
628   // Future refinement: under certain circumstances, we might be more sophisticated about this choice.
629   // For example, we could choose to abandon the previous old collection before it has completed evacuations.
630   ShenandoahHeap* heap = ShenandoahHeap::heap();
631   if (!_old_generation->can_start_gc() || heap->collection_set()->has_old_regions()) {
632     return false;
633   }
634 
635   if (_cannot_expand_trigger) {
636     const size_t old_gen_capacity = _old_generation->max_capacity();
637     const size_t heap_capacity = heap->capacity();
638     const double percent = percent_of(old_gen_capacity, heap_capacity);
639     log_trigger("Expansion failure, current size: " SIZE_FORMAT "%s which is %.1f%% of total heap size",
640                  byte_size_in_proper_unit(old_gen_capacity), proper_unit_for_byte_size(old_gen_capacity), percent);
641     return true;
642   }
643 
644   if (_fragmentation_trigger) {
645     const size_t used = _old_generation->used();
646     const size_t used_regions_size = _old_generation->used_regions_size();
647 
648     // used_regions includes humongous regions
649     const size_t used_regions = _old_generation->used_regions();
650     assert(used_regions_size > used_regions, "Cannot have more used than used regions");
651 
652     size_t first_old_region, last_old_region;
653     double density;
654     get_fragmentation_trigger_reason_for_log_message(density, first_old_region, last_old_region);
655     const size_t span_of_old_regions = (last_old_region >= first_old_region)? last_old_region + 1 - first_old_region: 0;
656     const size_t fragmented_free = used_regions_size - used;
657 
658     log_trigger("Old has become fragmented: "
659                 SIZE_FORMAT "%s available bytes spread between range spanned from "
660                 SIZE_FORMAT " to " SIZE_FORMAT " (" SIZE_FORMAT "), density: %.1f%%",
661                 byte_size_in_proper_unit(fragmented_free), proper_unit_for_byte_size(fragmented_free),
662                 first_old_region, last_old_region, span_of_old_regions, density * 100);
663     return true;
664   }
665 
666   if (_growth_trigger) {
667     // Growth may be falsely triggered during mixed evacuations, before the mixed-evacuation candidates have been
668     // evacuated.  Before acting on a false trigger, we check to confirm the trigger condition is still satisfied.
669     const size_t current_usage = _old_generation->used() + _old_generation->get_humongous_waste();
670     const size_t trigger_threshold = _old_generation->usage_trigger_threshold();
671     const size_t heap_size = heap->capacity();
672     const size_t ignore_threshold = (ShenandoahIgnoreOldGrowthBelowPercentage * heap_size) / 100;
673     size_t consecutive_young_cycles;
674     if ((current_usage < ignore_threshold) &&
675         ((consecutive_young_cycles = heap->shenandoah_policy()->consecutive_young_gc_count())
676          < ShenandoahDoNotIgnoreGrowthAfterYoungCycles)) {
677       log_debug(gc)("Ignoring Trigger: Old has overgrown: usage (" SIZE_FORMAT "%s) is below threshold ("
678                     SIZE_FORMAT "%s) after " SIZE_FORMAT " consecutive completed young GCs",
679                     byte_size_in_proper_unit(current_usage), proper_unit_for_byte_size(current_usage),
680                     byte_size_in_proper_unit(ignore_threshold), proper_unit_for_byte_size(ignore_threshold),
681                     consecutive_young_cycles);
682       _growth_trigger = false;
683     } else if (current_usage > trigger_threshold) {
684       const size_t live_at_previous_old = _old_generation->get_live_bytes_after_last_mark();
685       const double percent_growth = percent_of(current_usage - live_at_previous_old, live_at_previous_old);
686       log_trigger("Old has overgrown, live at end of previous OLD marking: "
687                   SIZE_FORMAT "%s, current usage: " SIZE_FORMAT "%s, percent growth: %.1f%%",
688                   byte_size_in_proper_unit(live_at_previous_old), proper_unit_for_byte_size(live_at_previous_old),
689                   byte_size_in_proper_unit(current_usage), proper_unit_for_byte_size(current_usage), percent_growth);
690       return true;
691     } else {
692       // Mixed evacuations have decreased current_usage such that old-growth trigger is no longer relevant.
693       _growth_trigger = false;
694     }
695   }
696 
697   // Otherwise, defer to inherited heuristic for gc trigger.
698   return this->ShenandoahHeuristics::should_start_gc();
699 }
700 
701 void ShenandoahOldHeuristics::record_success_concurrent() {
702   // Forget any triggers that occurred while OLD GC was ongoing.  If we really need to start another, it will retrigger.
703   clear_triggers();
704   this->ShenandoahHeuristics::record_success_concurrent();
705 }
706 
707 void ShenandoahOldHeuristics::record_success_degenerated() {
708   // Forget any triggers that occurred while OLD GC was ongoing.  If we really need to start another, it will retrigger.
709   clear_triggers();
710   this->ShenandoahHeuristics::record_success_degenerated();
711 }
712 
713 void ShenandoahOldHeuristics::record_success_full() {
714   // Forget any triggers that occurred while OLD GC was ongoing.  If we really need to start another, it will retrigger.
715   clear_triggers();
716   this->ShenandoahHeuristics::record_success_full();
717 }
718 
719 const char* ShenandoahOldHeuristics::name() {
720   return "Old";
721 }
722 
723 bool ShenandoahOldHeuristics::is_diagnostic() {
724   return false;
725 }
726 
727 bool ShenandoahOldHeuristics::is_experimental() {
728   return true;
729 }
730 
731 void ShenandoahOldHeuristics::choose_collection_set_from_regiondata(ShenandoahCollectionSet* set,
732                                                                     ShenandoahHeuristics::RegionData* data,
733                                                                     size_t data_size, size_t free) {
734   ShouldNotReachHere();
735 }