1 /*
   2  * Copyright (c) 2018, 2019, 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 
  27 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  28 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  29 #include "gc/shenandoah/shenandoahPacer.hpp"
  30 #include "runtime/atomic.hpp"
  31 
  32 /*
  33  * In normal concurrent cycle, we have to pace the application to let GC finish.
  34  *
  35  * Here, we do not know how large would be the collection set, and what are the
  36  * relative performances of the each stage in the concurrent cycle, and so we have to
  37  * make some assumptions.
  38  *
  39  * For concurrent mark, there is no clear notion of progress. The moderately accurate
  40  * and easy to get metric is the amount of live objects the mark had encountered. But,
  41  * that does directly correlate with the used heap, because the heap might be fully
  42  * dead or fully alive. We cannot assume either of the extremes: we would either allow
  43  * application to run out of memory if we assume heap is fully dead but it is not, and,
  44  * conversely, we would pacify application excessively if we assume heap is fully alive
  45  * but it is not. So we need to guesstimate the particular expected value for heap liveness.
  46  * The best way to do this is apparently recording the past history.
  47  *
  48  * For concurrent evac and update-refs, we are walking the heap per-region, and so the
  49  * notion of progress is clear: we get reported the "used" size from the processed regions
  50  * and use the global heap-used as the baseline.
  51  *
  52  * The allocatable space when GC is running is "free" at the start of cycle, but the
  53  * accounted budget is based on "used". So, we need to adjust the tax knowing that.
  54  * Also, since we effectively count the used space three times (mark, evac, update-refs),
  55  * we need to multiply the tax by 3. Example: for 10 MB free and 90 MB used, GC would
  56  * come back with 3*90 MB budget, and thus for each 1 MB of allocation, we have to pay
  57  * 3*90 / 10 MBs. In the end, we would pay back the entire budget.
  58  */
  59 
  60 void ShenandoahPacer::setup_for_mark() {
  61   assert(ShenandoahPacing, "Only be here when pacing is enabled");
  62 
  63   size_t live = update_and_get_progress_history();
  64   size_t free = _heap->free_set()->available();
  65 
  66   size_t non_taxable = free * ShenandoahPacingCycleSlack / 100;
  67   size_t taxable = free - non_taxable;
  68 
  69   double tax = 1.0 * live / taxable; // base tax for available free space
  70   tax *= 3;                          // mark is phase 1 of 3, claim 1/3 of free for it
  71   tax *= ShenandoahPacingSurcharge;  // additional surcharge to help unclutter heap
  72 
  73   restart_with(non_taxable, tax);
  74 
  75   log_info(gc, ergo)("Pacer for Mark. Expected Live: " SIZE_FORMAT "%s, Free: " SIZE_FORMAT "%s, "
  76                      "Non-Taxable: " SIZE_FORMAT "%s, Alloc Tax Rate: %.1fx",
  77                      byte_size_in_proper_unit(live),        proper_unit_for_byte_size(live),
  78                      byte_size_in_proper_unit(free),        proper_unit_for_byte_size(free),
  79                      byte_size_in_proper_unit(non_taxable), proper_unit_for_byte_size(non_taxable),
  80                      tax);
  81 }
  82 
  83 void ShenandoahPacer::setup_for_evac() {
  84   assert(ShenandoahPacing, "Only be here when pacing is enabled");
  85 
  86   size_t used = _heap->collection_set()->used();
  87   size_t free = _heap->free_set()->available();
  88 
  89   size_t non_taxable = free * ShenandoahPacingCycleSlack / 100;
  90   size_t taxable = free - non_taxable;
  91 
  92   double tax = 1.0 * used / taxable; // base tax for available free space
  93   tax *= 2;                          // evac is phase 2 of 3, claim 1/2 of remaining free
  94   tax = MAX2<double>(1, tax);        // never allocate more than GC processes during the phase
  95   tax *= ShenandoahPacingSurcharge;  // additional surcharge to help unclutter heap
  96 
  97   restart_with(non_taxable, tax);
  98 
  99   log_info(gc, ergo)("Pacer for Evacuation. Used CSet: " SIZE_FORMAT "%s, Free: " SIZE_FORMAT "%s, "
 100                      "Non-Taxable: " SIZE_FORMAT "%s, Alloc Tax Rate: %.1fx",
 101                      byte_size_in_proper_unit(used),        proper_unit_for_byte_size(used),
 102                      byte_size_in_proper_unit(free),        proper_unit_for_byte_size(free),
 103                      byte_size_in_proper_unit(non_taxable), proper_unit_for_byte_size(non_taxable),
 104                      tax);
 105 }
 106 
 107 void ShenandoahPacer::setup_for_updaterefs() {
 108   assert(ShenandoahPacing, "Only be here when pacing is enabled");
 109 
 110   size_t used = _heap->used();
 111   size_t free = _heap->free_set()->available();
 112 
 113   size_t non_taxable = free * ShenandoahPacingCycleSlack / 100;
 114   size_t taxable = free - non_taxable;
 115 
 116   double tax = 1.0 * used / taxable; // base tax for available free space
 117   tax *= 1;                          // update-refs is phase 3 of 3, claim the remaining free
 118   tax = MAX2<double>(1, tax);        // never allocate more than GC processes during the phase
 119   tax *= ShenandoahPacingSurcharge;  // additional surcharge to help unclutter heap
 120 
 121   restart_with(non_taxable, tax);
 122 
 123   log_info(gc, ergo)("Pacer for Update Refs. Used: " SIZE_FORMAT "%s, Free: " SIZE_FORMAT "%s, "
 124                      "Non-Taxable: " SIZE_FORMAT "%s, Alloc Tax Rate: %.1fx",
 125                      byte_size_in_proper_unit(used),        proper_unit_for_byte_size(used),
 126                      byte_size_in_proper_unit(free),        proper_unit_for_byte_size(free),
 127                      byte_size_in_proper_unit(non_taxable), proper_unit_for_byte_size(non_taxable),
 128                      tax);
 129 }
 130 
 131 /*
 132  * In idle phase, we have to pace the application to let control thread react with GC start.
 133  *
 134  * Here, we have rendezvous with concurrent thread that adds up the budget as it acknowledges
 135  * it had seen recent allocations. It will naturally pace the allocations if control thread is
 136  * not catching up. To bootstrap this feedback cycle, we need to start with some initial budget
 137  * for applications to allocate at.
 138  */
 139 
 140 void ShenandoahPacer::setup_for_idle() {
 141   assert(ShenandoahPacing, "Only be here when pacing is enabled");
 142 
 143   size_t initial = _heap->max_capacity() / 100 * ShenandoahPacingIdleSlack;
 144   double tax = 1;
 145 
 146   restart_with(initial, tax);
 147 
 148   log_info(gc, ergo)("Pacer for Idle. Initial: " SIZE_FORMAT "%s, Alloc Tax Rate: %.1fx",
 149                      byte_size_in_proper_unit(initial), proper_unit_for_byte_size(initial),
 150                      tax);
 151 }
 152 
 153 /*
 154  * There is no useful notion of progress for these operations. To avoid stalling
 155  * the allocators unnecessarily, allow them to run unimpeded.
 156  */
 157 
 158 void ShenandoahPacer::setup_for_preclean() {
 159   assert(ShenandoahPacing, "Only be here when pacing is enabled");
 160 
 161   size_t initial = _heap->max_capacity();
 162   restart_with(initial, 1.0);
 163 
 164   log_info(gc, ergo)("Pacer for Precleaning. Non-Taxable: " SIZE_FORMAT "%s",
 165                      byte_size_in_proper_unit(initial), proper_unit_for_byte_size(initial));
 166 }
 167 
 168 void ShenandoahPacer::setup_for_reset() {
 169   assert(ShenandoahPacing, "Only be here when pacing is enabled");
 170 
 171   size_t initial = _heap->max_capacity();
 172   restart_with(initial, 1.0);
 173 
 174   log_info(gc, ergo)("Pacer for Reset. Non-Taxable: " SIZE_FORMAT "%s",
 175                      byte_size_in_proper_unit(initial), proper_unit_for_byte_size(initial));
 176 }
 177 
 178 size_t ShenandoahPacer::update_and_get_progress_history() {
 179   if (_progress == -1) {
 180     // First initialization, report some prior
 181     Atomic::store(&_progress, (intptr_t)PACING_PROGRESS_ZERO);
 182     return (size_t) (_heap->max_capacity() * 0.1);
 183   } else {
 184     // Record history, and reply historical data
 185     _progress_history->add(_progress);
 186     Atomic::store(&_progress, (intptr_t)PACING_PROGRESS_ZERO);
 187     return (size_t) (_progress_history->avg() * HeapWordSize);
 188   }
 189 }
 190 
 191 void ShenandoahPacer::restart_with(size_t non_taxable_bytes, double tax_rate) {
 192   size_t initial = (size_t)(non_taxable_bytes * tax_rate) >> LogHeapWordSize;
 193   STATIC_ASSERT(sizeof(size_t) <= sizeof(intptr_t));
 194   Atomic::xchg(&_budget, (intptr_t)initial);
 195   Atomic::store(&_tax_rate, tax_rate);
 196   Atomic::inc(&_epoch);
 197 }
 198 
 199 bool ShenandoahPacer::claim_for_alloc(size_t words, bool force) {
 200   assert(ShenandoahPacing, "Only be here when pacing is enabled");
 201 
 202   intptr_t tax = MAX2<intptr_t>(1, words * Atomic::load(&_tax_rate));
 203 
 204   intptr_t cur = 0;
 205   intptr_t new_val = 0;
 206   do {
 207     cur = Atomic::load(&_budget);
 208     if (cur < tax && !force) {
 209       // Progress depleted, alas.
 210       return false;
 211     }
 212     new_val = cur - tax;
 213   } while (Atomic::cmpxchg(&_budget, cur, new_val) != cur);
 214   return true;
 215 }
 216 
 217 void ShenandoahPacer::unpace_for_alloc(intptr_t epoch, size_t words) {
 218   assert(ShenandoahPacing, "Only be here when pacing is enabled");
 219 
 220   if (_epoch != epoch) {
 221     // Stale ticket, no need to unpace.
 222     return;
 223   }
 224 
 225   intptr_t tax = MAX2<intptr_t>(1, words * Atomic::load(&_tax_rate));
 226   Atomic::add(&_budget, tax);
 227 }
 228 
 229 intptr_t ShenandoahPacer::epoch() {
 230   return Atomic::load(&_epoch);
 231 }
 232 
 233 void ShenandoahPacer::pace_for_alloc(size_t words) {
 234   assert(ShenandoahPacing, "Only be here when pacing is enabled");
 235 
 236   // Fast path: try to allocate right away
 237   if (claim_for_alloc(words, false)) {
 238     return;
 239   }
 240 
 241   // Threads that are attaching should not block at all: they are not
 242   // fully initialized yet. Calling sleep() on them would be awkward.
 243   // This is probably the path that allocates the thread oop itself.
 244   // Forcefully claim without waiting.
 245   if (JavaThread::current()->is_attaching_via_jni()) {
 246     claim_for_alloc(words, true);
 247     return;
 248   }
 249 
 250   size_t max = ShenandoahPacingMaxDelay;
 251   double start = os::elapsedTime();
 252 
 253   size_t total = 0;
 254   size_t cur = 0;
 255 
 256   while (true) {
 257     // We could instead assist GC, but this would suffice for now.
 258     // This code should also participate in safepointing.
 259     // Perform the exponential backoff, limited by max.
 260 
 261     cur = cur * 2;
 262     if (total + cur > max) {
 263       cur = (max > total) ? (max - total) : 0;
 264     }
 265     cur = MAX2<size_t>(1, cur);
 266 
 267     JavaThread::current()->sleep(cur);
 268 
 269     double end = os::elapsedTime();
 270     total = (size_t)((end - start) * 1000);
 271 
 272     if (total > max) {
 273       // Spent local time budget to wait for enough GC progress.
 274       // Breaking out and allocating anyway, which may mean we outpace GC,
 275       // and start Degenerated GC cycle.
 276       _delays.add(total);
 277 
 278       // Forcefully claim the budget: it may go negative at this point, and
 279       // GC should replenish for this and subsequent allocations
 280       claim_for_alloc(words, true);
 281       break;
 282     }
 283 
 284     if (claim_for_alloc(words, false)) {
 285       // Acquired enough permit, nice. Can allocate now.
 286       _delays.add(total);
 287       break;
 288     }
 289   }
 290 }
 291 
 292 void ShenandoahPacer::print_on(outputStream* out) const {
 293   out->print_cr("ALLOCATION PACING:");
 294   out->cr();
 295 
 296   out->print_cr("Max pacing delay is set for " UINTX_FORMAT " ms.", ShenandoahPacingMaxDelay);
 297   out->cr();
 298 
 299   out->print_cr("Higher delay would prevent application outpacing the GC, but it will hide the GC latencies");
 300   out->print_cr("from the STW pause times. Pacing affects the individual threads, and so it would also be");
 301   out->print_cr("invisible to the usual profiling tools, but would add up to end-to-end application latency.");
 302   out->print_cr("Raise max pacing delay with care.");
 303   out->cr();
 304 
 305   out->print_cr("Actual pacing delays histogram:");
 306   out->cr();
 307 
 308   out->print_cr("%10s - %10s  %12s%12s", "From", "To", "Count", "Sum");
 309 
 310   size_t total_count = 0;
 311   size_t total_sum = 0;
 312   for (int c = _delays.min_level(); c <= _delays.max_level(); c++) {
 313     int l = (c == 0) ? 0 : 1 << (c - 1);
 314     int r = 1 << c;
 315     size_t count = _delays.level(c);
 316     size_t sum   = count * (r - l) / 2;
 317     total_count += count;
 318     total_sum   += sum;
 319 
 320     out->print_cr("%7d ms - %7d ms: " SIZE_FORMAT_W(12) SIZE_FORMAT_W(12) " ms", l, r, count, sum);
 321   }
 322   out->print_cr("%23s: " SIZE_FORMAT_W(12) SIZE_FORMAT_W(12) " ms", "Total", total_count, total_sum);
 323   out->cr();
 324   out->print_cr("Pacing delays are measured from entering the pacing code till exiting it. Therefore,");
 325   out->print_cr("observed pacing delays may be higher than the threshold when paced thread spent more");
 326   out->print_cr("time in the pacing code. It usually happens when thread is de-scheduled while paced,");
 327   out->print_cr("OS takes longer to unblock the thread, or JVM experiences an STW pause.");
 328   out->cr();
 329 }