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