xref: /openbmc/qemu/util/throttle.c (revision b917da4c)
1 /*
2  * QEMU throttling infrastructure
3  *
4  * Copyright (C) Nodalink, EURL. 2013-2014
5  * Copyright (C) Igalia, S.L. 2015
6  *
7  * Authors:
8  *   Benoît Canet <benoit.canet@nodalink.com>
9  *   Alberto Garcia <berto@igalia.com>
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License as
13  * published by the Free Software Foundation; either version 2 or
14  * (at your option) version 3 of the License.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, see <http://www.gnu.org/licenses/>.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qemu/throttle.h"
27 #include "qemu/timer.h"
28 #include "block/aio.h"
29 
30 /* This function make a bucket leak
31  *
32  * @bkt:   the bucket to make leak
33  * @delta_ns: the time delta
34  */
35 void throttle_leak_bucket(LeakyBucket *bkt, int64_t delta_ns)
36 {
37     double leak;
38 
39     /* compute how much to leak */
40     leak = (bkt->avg * (double) delta_ns) / NANOSECONDS_PER_SECOND;
41 
42     /* make the bucket leak */
43     bkt->level = MAX(bkt->level - leak, 0);
44 
45     /* if we allow bursts for more than one second we also need to
46      * keep track of bkt->burst_level so the bkt->max goal per second
47      * is attained */
48     if (bkt->burst_length > 1) {
49         leak = (bkt->max * (double) delta_ns) / NANOSECONDS_PER_SECOND;
50         bkt->burst_level = MAX(bkt->burst_level - leak, 0);
51     }
52 }
53 
54 /* Calculate the time delta since last leak and make proportionals leaks
55  *
56  * @now:      the current timestamp in ns
57  */
58 static void throttle_do_leak(ThrottleState *ts, int64_t now)
59 {
60     /* compute the time elapsed since the last leak */
61     int64_t delta_ns = now - ts->previous_leak;
62     int i;
63 
64     ts->previous_leak = now;
65 
66     if (delta_ns <= 0) {
67         return;
68     }
69 
70     /* make each bucket leak */
71     for (i = 0; i < BUCKETS_COUNT; i++) {
72         throttle_leak_bucket(&ts->cfg.buckets[i], delta_ns);
73     }
74 }
75 
76 /* do the real job of computing the time to wait
77  *
78  * @limit: the throttling limit
79  * @extra: the number of operation to delay
80  * @ret:   the time to wait in ns
81  */
82 static int64_t throttle_do_compute_wait(double limit, double extra)
83 {
84     double wait = extra * NANOSECONDS_PER_SECOND;
85     wait /= limit;
86     return wait;
87 }
88 
89 /* This function compute the wait time in ns that a leaky bucket should trigger
90  *
91  * @bkt: the leaky bucket we operate on
92  * @ret: the resulting wait time in ns or 0 if the operation can go through
93  */
94 int64_t throttle_compute_wait(LeakyBucket *bkt)
95 {
96     double extra; /* the number of extra units blocking the io */
97 
98     if (!bkt->avg) {
99         return 0;
100     }
101 
102     /* If the bucket is full then we have to wait */
103     extra = bkt->level - bkt->max * bkt->burst_length;
104     if (extra > 0) {
105         return throttle_do_compute_wait(bkt->avg, extra);
106     }
107 
108     /* If the bucket is not full yet we have to make sure that we
109      * fulfill the goal of bkt->max units per second. */
110     if (bkt->burst_length > 1) {
111         /* We use 1/10 of the max value to smooth the throttling.
112          * See throttle_fix_bucket() for more details. */
113         extra = bkt->burst_level - bkt->max / 10;
114         if (extra > 0) {
115             return throttle_do_compute_wait(bkt->max, extra);
116         }
117     }
118 
119     return 0;
120 }
121 
122 /* This function compute the time that must be waited while this IO
123  *
124  * @is_write:   true if the current IO is a write, false if it's a read
125  * @ret:        time to wait
126  */
127 static int64_t throttle_compute_wait_for(ThrottleState *ts,
128                                          bool is_write)
129 {
130     BucketType to_check[2][4] = { {THROTTLE_BPS_TOTAL,
131                                    THROTTLE_OPS_TOTAL,
132                                    THROTTLE_BPS_READ,
133                                    THROTTLE_OPS_READ},
134                                   {THROTTLE_BPS_TOTAL,
135                                    THROTTLE_OPS_TOTAL,
136                                    THROTTLE_BPS_WRITE,
137                                    THROTTLE_OPS_WRITE}, };
138     int64_t wait, max_wait = 0;
139     int i;
140 
141     for (i = 0; i < 4; i++) {
142         BucketType index = to_check[is_write][i];
143         wait = throttle_compute_wait(&ts->cfg.buckets[index]);
144         if (wait > max_wait) {
145             max_wait = wait;
146         }
147     }
148 
149     return max_wait;
150 }
151 
152 /* compute the timer for this type of operation
153  *
154  * @is_write:   the type of operation
155  * @now:        the current clock timestamp
156  * @next_timestamp: the resulting timer
157  * @ret:        true if a timer must be set
158  */
159 static bool throttle_compute_timer(ThrottleState *ts,
160                                    bool is_write,
161                                    int64_t now,
162                                    int64_t *next_timestamp)
163 {
164     int64_t wait;
165 
166     /* leak proportionally to the time elapsed */
167     throttle_do_leak(ts, now);
168 
169     /* compute the wait time if any */
170     wait = throttle_compute_wait_for(ts, is_write);
171 
172     /* if the code must wait compute when the next timer should fire */
173     if (wait) {
174         *next_timestamp = now + wait;
175         return true;
176     }
177 
178     /* else no need to wait at all */
179     *next_timestamp = now;
180     return false;
181 }
182 
183 /* Add timers to event loop */
184 void throttle_timers_attach_aio_context(ThrottleTimers *tt,
185                                         AioContext *new_context)
186 {
187     tt->timers[0] = aio_timer_new(new_context, tt->clock_type, SCALE_NS,
188                                   tt->read_timer_cb, tt->timer_opaque);
189     tt->timers[1] = aio_timer_new(new_context, tt->clock_type, SCALE_NS,
190                                   tt->write_timer_cb, tt->timer_opaque);
191 }
192 
193 /*
194  * Initialize the ThrottleConfig structure to a valid state
195  * @cfg: the config to initialize
196  */
197 void throttle_config_init(ThrottleConfig *cfg)
198 {
199     unsigned i;
200     memset(cfg, 0, sizeof(*cfg));
201     for (i = 0; i < BUCKETS_COUNT; i++) {
202         cfg->buckets[i].burst_length = 1;
203     }
204 }
205 
206 /* To be called first on the ThrottleState */
207 void throttle_init(ThrottleState *ts)
208 {
209     memset(ts, 0, sizeof(ThrottleState));
210     throttle_config_init(&ts->cfg);
211 }
212 
213 /* To be called first on the ThrottleTimers */
214 void throttle_timers_init(ThrottleTimers *tt,
215                           AioContext *aio_context,
216                           QEMUClockType clock_type,
217                           QEMUTimerCB *read_timer_cb,
218                           QEMUTimerCB *write_timer_cb,
219                           void *timer_opaque)
220 {
221     memset(tt, 0, sizeof(ThrottleTimers));
222 
223     tt->clock_type = clock_type;
224     tt->read_timer_cb = read_timer_cb;
225     tt->write_timer_cb = write_timer_cb;
226     tt->timer_opaque = timer_opaque;
227     throttle_timers_attach_aio_context(tt, aio_context);
228 }
229 
230 /* destroy a timer */
231 static void throttle_timer_destroy(QEMUTimer **timer)
232 {
233     assert(*timer != NULL);
234 
235     timer_del(*timer);
236     timer_free(*timer);
237     *timer = NULL;
238 }
239 
240 /* Remove timers from event loop */
241 void throttle_timers_detach_aio_context(ThrottleTimers *tt)
242 {
243     int i;
244 
245     for (i = 0; i < 2; i++) {
246         throttle_timer_destroy(&tt->timers[i]);
247     }
248 }
249 
250 /* To be called last on the ThrottleTimers */
251 void throttle_timers_destroy(ThrottleTimers *tt)
252 {
253     throttle_timers_detach_aio_context(tt);
254 }
255 
256 /* is any throttling timer configured */
257 bool throttle_timers_are_initialized(ThrottleTimers *tt)
258 {
259     if (tt->timers[0]) {
260         return true;
261     }
262 
263     return false;
264 }
265 
266 /* Does any throttling must be done
267  *
268  * @cfg: the throttling configuration to inspect
269  * @ret: true if throttling must be done else false
270  */
271 bool throttle_enabled(ThrottleConfig *cfg)
272 {
273     int i;
274 
275     for (i = 0; i < BUCKETS_COUNT; i++) {
276         if (cfg->buckets[i].avg > 0) {
277             return true;
278         }
279     }
280 
281     return false;
282 }
283 
284 /* check if a throttling configuration is valid
285  * @cfg: the throttling configuration to inspect
286  * @ret: true if valid else false
287  * @errp: error object
288  */
289 bool throttle_is_valid(ThrottleConfig *cfg, Error **errp)
290 {
291     int i;
292     bool bps_flag, ops_flag;
293     bool bps_max_flag, ops_max_flag;
294 
295     bps_flag = cfg->buckets[THROTTLE_BPS_TOTAL].avg &&
296                (cfg->buckets[THROTTLE_BPS_READ].avg ||
297                 cfg->buckets[THROTTLE_BPS_WRITE].avg);
298 
299     ops_flag = cfg->buckets[THROTTLE_OPS_TOTAL].avg &&
300                (cfg->buckets[THROTTLE_OPS_READ].avg ||
301                 cfg->buckets[THROTTLE_OPS_WRITE].avg);
302 
303     bps_max_flag = cfg->buckets[THROTTLE_BPS_TOTAL].max &&
304                   (cfg->buckets[THROTTLE_BPS_READ].max  ||
305                    cfg->buckets[THROTTLE_BPS_WRITE].max);
306 
307     ops_max_flag = cfg->buckets[THROTTLE_OPS_TOTAL].max &&
308                    (cfg->buckets[THROTTLE_OPS_READ].max ||
309                    cfg->buckets[THROTTLE_OPS_WRITE].max);
310 
311     if (bps_flag || ops_flag || bps_max_flag || ops_max_flag) {
312         error_setg(errp, "bps/iops/max total values and read/write values"
313                    " cannot be used at the same time");
314         return false;
315     }
316 
317     for (i = 0; i < BUCKETS_COUNT; i++) {
318         if (cfg->buckets[i].avg < 0 ||
319             cfg->buckets[i].max < 0 ||
320             cfg->buckets[i].avg > THROTTLE_VALUE_MAX ||
321             cfg->buckets[i].max > THROTTLE_VALUE_MAX) {
322             error_setg(errp, "bps/iops/max values must be within [0, %lld]",
323                        THROTTLE_VALUE_MAX);
324             return false;
325         }
326 
327         if (!cfg->buckets[i].burst_length) {
328             error_setg(errp, "the burst length cannot be 0");
329             return false;
330         }
331 
332         if (cfg->buckets[i].burst_length > 1 && !cfg->buckets[i].max) {
333             error_setg(errp, "burst length set without burst rate");
334             return false;
335         }
336 
337         if (cfg->buckets[i].max && !cfg->buckets[i].avg) {
338             error_setg(errp, "bps_max/iops_max require corresponding"
339                        " bps/iops values");
340             return false;
341         }
342     }
343 
344     return true;
345 }
346 
347 /* fix bucket parameters */
348 static void throttle_fix_bucket(LeakyBucket *bkt)
349 {
350     double min;
351 
352     /* zero bucket level */
353     bkt->level = bkt->burst_level = 0;
354 
355     /* The following is done to cope with the Linux CFQ block scheduler
356      * which regroup reads and writes by block of 100ms in the guest.
357      * When they are two process one making reads and one making writes cfq
358      * make a pattern looking like the following:
359      * WWWWWWWWWWWRRRRRRRRRRRRRRWWWWWWWWWWWWWwRRRRRRRRRRRRRRRRR
360      * Having a max burst value of 100ms of the average will help smooth the
361      * throttling
362      */
363     min = bkt->avg / 10;
364     if (bkt->avg && !bkt->max) {
365         bkt->max = min;
366     }
367 }
368 
369 /* take care of canceling a timer */
370 static void throttle_cancel_timer(QEMUTimer *timer)
371 {
372     assert(timer != NULL);
373 
374     timer_del(timer);
375 }
376 
377 /* Used to configure the throttle
378  *
379  * @ts: the throttle state we are working on
380  * @tt: the throttle timers we use in this aio context
381  * @cfg: the config to set
382  */
383 void throttle_config(ThrottleState *ts,
384                      ThrottleTimers *tt,
385                      ThrottleConfig *cfg)
386 {
387     int i;
388 
389     ts->cfg = *cfg;
390 
391     for (i = 0; i < BUCKETS_COUNT; i++) {
392         throttle_fix_bucket(&ts->cfg.buckets[i]);
393     }
394 
395     ts->previous_leak = qemu_clock_get_ns(tt->clock_type);
396 
397     for (i = 0; i < 2; i++) {
398         throttle_cancel_timer(tt->timers[i]);
399     }
400 }
401 
402 /* used to get config
403  *
404  * @ts:  the throttle state we are working on
405  * @cfg: the config to write
406  */
407 void throttle_get_config(ThrottleState *ts, ThrottleConfig *cfg)
408 {
409     *cfg = ts->cfg;
410 }
411 
412 
413 /* Schedule the read or write timer if needed
414  *
415  * NOTE: this function is not unit tested due to it's usage of timer_mod
416  *
417  * @tt:       the timers structure
418  * @is_write: the type of operation (read/write)
419  * @ret:      true if the timer has been scheduled else false
420  */
421 bool throttle_schedule_timer(ThrottleState *ts,
422                              ThrottleTimers *tt,
423                              bool is_write)
424 {
425     int64_t now = qemu_clock_get_ns(tt->clock_type);
426     int64_t next_timestamp;
427     bool must_wait;
428 
429     must_wait = throttle_compute_timer(ts,
430                                        is_write,
431                                        now,
432                                        &next_timestamp);
433 
434     /* request not throttled */
435     if (!must_wait) {
436         return false;
437     }
438 
439     /* request throttled and timer pending -> do nothing */
440     if (timer_pending(tt->timers[is_write])) {
441         return true;
442     }
443 
444     /* request throttled and timer not pending -> arm timer */
445     timer_mod(tt->timers[is_write], next_timestamp);
446     return true;
447 }
448 
449 /* do the accounting for this operation
450  *
451  * @is_write: the type of operation (read/write)
452  * @size:     the size of the operation
453  */
454 void throttle_account(ThrottleState *ts, bool is_write, uint64_t size)
455 {
456     const BucketType bucket_types_size[2][2] = {
457         { THROTTLE_BPS_TOTAL, THROTTLE_BPS_READ },
458         { THROTTLE_BPS_TOTAL, THROTTLE_BPS_WRITE }
459     };
460     const BucketType bucket_types_units[2][2] = {
461         { THROTTLE_OPS_TOTAL, THROTTLE_OPS_READ },
462         { THROTTLE_OPS_TOTAL, THROTTLE_OPS_WRITE }
463     };
464     double units = 1.0;
465     unsigned i;
466 
467     /* if cfg.op_size is defined and smaller than size we compute unit count */
468     if (ts->cfg.op_size && size > ts->cfg.op_size) {
469         units = (double) size / ts->cfg.op_size;
470     }
471 
472     for (i = 0; i < 2; i++) {
473         LeakyBucket *bkt;
474 
475         bkt = &ts->cfg.buckets[bucket_types_size[is_write][i]];
476         bkt->level += size;
477         if (bkt->burst_length > 1) {
478             bkt->burst_level += size;
479         }
480 
481         bkt = &ts->cfg.buckets[bucket_types_units[is_write][i]];
482         bkt->level += units;
483         if (bkt->burst_length > 1) {
484             bkt->burst_level += units;
485         }
486     }
487 }
488 
489