xref: /openbmc/qemu/util/throttle.c (revision 8ba02c24ea25a7a1fa4931e266af7916c115da2c)
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 "qapi/error.h"
27 #include "qemu/throttle.h"
28 #include "qemu/timer.h"
29 #include "block/aio.h"
30 
31 /* This function make a bucket leak
32  *
33  * @bkt:   the bucket to make leak
34  * @delta_ns: the time delta
35  */
36 void throttle_leak_bucket(LeakyBucket *bkt, int64_t delta_ns)
37 {
38     double leak;
39 
40     /* compute how much to leak */
41     leak = (bkt->avg * (double) delta_ns) / NANOSECONDS_PER_SECOND;
42 
43     /* make the bucket leak */
44     bkt->level = MAX(bkt->level - leak, 0);
45 
46     /* if we allow bursts for more than one second we also need to
47      * keep track of bkt->burst_level so the bkt->max goal per second
48      * is attained */
49     if (bkt->burst_length > 1) {
50         leak = (bkt->max * (double) delta_ns) / NANOSECONDS_PER_SECOND;
51         bkt->burst_level = MAX(bkt->burst_level - leak, 0);
52     }
53 }
54 
55 /* Calculate the time delta since last leak and make proportionals leaks
56  *
57  * @now:      the current timestamp in ns
58  */
59 static void throttle_do_leak(ThrottleState *ts, int64_t now)
60 {
61     /* compute the time elapsed since the last leak */
62     int64_t delta_ns = now - ts->previous_leak;
63     int i;
64 
65     ts->previous_leak = now;
66 
67     if (delta_ns <= 0) {
68         return;
69     }
70 
71     /* make each bucket leak */
72     for (i = 0; i < BUCKETS_COUNT; i++) {
73         throttle_leak_bucket(&ts->cfg.buckets[i], delta_ns);
74     }
75 }
76 
77 /* do the real job of computing the time to wait
78  *
79  * @limit: the throttling limit
80  * @extra: the number of operation to delay
81  * @ret:   the time to wait in ns
82  */
83 static int64_t throttle_do_compute_wait(double limit, double extra)
84 {
85     double wait = extra * NANOSECONDS_PER_SECOND;
86     wait /= limit;
87     return wait;
88 }
89 
90 /* This function compute the wait time in ns that a leaky bucket should trigger
91  *
92  * @bkt: the leaky bucket we operate on
93  * @ret: the resulting wait time in ns or 0 if the operation can go through
94  */
95 int64_t throttle_compute_wait(LeakyBucket *bkt)
96 {
97     double extra; /* the number of extra units blocking the io */
98     double bucket_size;   /* I/O before throttling to bkt->avg */
99     double burst_bucket_size; /* Before throttling to bkt->max */
100 
101     if (!bkt->avg) {
102         return 0;
103     }
104 
105     if (!bkt->max) {
106         /* If bkt->max is 0 we still want to allow short bursts of I/O
107          * from the guest, otherwise every other request will be throttled
108          * and performance will suffer considerably. */
109         bucket_size = (double) bkt->avg / 10;
110         burst_bucket_size = 0;
111     } else {
112         /* If we have a burst limit then we have to wait until all I/O
113          * at burst rate has finished before throttling to bkt->avg */
114         bucket_size = bkt->max * bkt->burst_length;
115         burst_bucket_size = (double) bkt->max / 10;
116     }
117 
118     /* If the main bucket is full then we have to wait */
119     extra = bkt->level - bucket_size;
120     if (extra > 0) {
121         return throttle_do_compute_wait(bkt->avg, extra);
122     }
123 
124     /* If the main bucket is not full yet we still have to check the
125      * burst bucket in order to enforce the burst limit */
126     if (bkt->burst_length > 1) {
127         assert(bkt->max > 0); /* see throttle_is_valid() */
128         extra = bkt->burst_level - burst_bucket_size;
129         if (extra > 0) {
130             return throttle_do_compute_wait(bkt->max, extra);
131         }
132     }
133 
134     return 0;
135 }
136 
137 /* This function compute the time that must be waited while this IO
138  *
139  * @is_write:   true if the current IO is a write, false if it's a read
140  * @ret:        time to wait
141  */
142 static int64_t throttle_compute_wait_for(ThrottleState *ts,
143                                          bool is_write)
144 {
145     BucketType to_check[2][4] = { {THROTTLE_BPS_TOTAL,
146                                    THROTTLE_OPS_TOTAL,
147                                    THROTTLE_BPS_READ,
148                                    THROTTLE_OPS_READ},
149                                   {THROTTLE_BPS_TOTAL,
150                                    THROTTLE_OPS_TOTAL,
151                                    THROTTLE_BPS_WRITE,
152                                    THROTTLE_OPS_WRITE}, };
153     int64_t wait, max_wait = 0;
154     int i;
155 
156     for (i = 0; i < 4; i++) {
157         BucketType index = to_check[is_write][i];
158         wait = throttle_compute_wait(&ts->cfg.buckets[index]);
159         if (wait > max_wait) {
160             max_wait = wait;
161         }
162     }
163 
164     return max_wait;
165 }
166 
167 /* compute the timer for this type of operation
168  *
169  * @is_write:   the type of operation
170  * @now:        the current clock timestamp
171  * @next_timestamp: the resulting timer
172  * @ret:        true if a timer must be set
173  */
174 static bool throttle_compute_timer(ThrottleState *ts,
175                                    bool is_write,
176                                    int64_t now,
177                                    int64_t *next_timestamp)
178 {
179     int64_t wait;
180 
181     /* leak proportionally to the time elapsed */
182     throttle_do_leak(ts, now);
183 
184     /* compute the wait time if any */
185     wait = throttle_compute_wait_for(ts, is_write);
186 
187     /* if the code must wait compute when the next timer should fire */
188     if (wait) {
189         *next_timestamp = now + wait;
190         return true;
191     }
192 
193     /* else no need to wait at all */
194     *next_timestamp = now;
195     return false;
196 }
197 
198 /* Add timers to event loop */
199 void throttle_timers_attach_aio_context(ThrottleTimers *tt,
200                                         AioContext *new_context)
201 {
202     tt->timers[THROTTLE_READ] =
203         aio_timer_new(new_context, tt->clock_type, SCALE_NS,
204                       tt->timer_cb[THROTTLE_READ], tt->timer_opaque);
205     tt->timers[THROTTLE_WRITE] =
206         aio_timer_new(new_context, tt->clock_type, SCALE_NS,
207                       tt->timer_cb[THROTTLE_WRITE], tt->timer_opaque);
208 }
209 
210 /*
211  * Initialize the ThrottleConfig structure to a valid state
212  * @cfg: the config to initialize
213  */
214 void throttle_config_init(ThrottleConfig *cfg)
215 {
216     unsigned i;
217     memset(cfg, 0, sizeof(*cfg));
218     for (i = 0; i < BUCKETS_COUNT; i++) {
219         cfg->buckets[i].burst_length = 1;
220     }
221 }
222 
223 /* To be called first on the ThrottleState */
224 void throttle_init(ThrottleState *ts)
225 {
226     memset(ts, 0, sizeof(ThrottleState));
227     throttle_config_init(&ts->cfg);
228 }
229 
230 /* To be called first on the ThrottleTimers */
231 void throttle_timers_init(ThrottleTimers *tt,
232                           AioContext *aio_context,
233                           QEMUClockType clock_type,
234                           QEMUTimerCB *read_timer_cb,
235                           QEMUTimerCB *write_timer_cb,
236                           void *timer_opaque)
237 {
238     memset(tt, 0, sizeof(ThrottleTimers));
239 
240     tt->clock_type = clock_type;
241     tt->timer_cb[THROTTLE_READ] = read_timer_cb;
242     tt->timer_cb[THROTTLE_WRITE] = write_timer_cb;
243     tt->timer_opaque = timer_opaque;
244     throttle_timers_attach_aio_context(tt, aio_context);
245 }
246 
247 /* destroy a timer */
248 static void throttle_timer_destroy(QEMUTimer **timer)
249 {
250     assert(*timer != NULL);
251 
252     timer_free(*timer);
253     *timer = NULL;
254 }
255 
256 /* Remove timers from event loop */
257 void throttle_timers_detach_aio_context(ThrottleTimers *tt)
258 {
259     int i;
260 
261     for (i = 0; i < THROTTLE_MAX; i++) {
262         throttle_timer_destroy(&tt->timers[i]);
263     }
264 }
265 
266 /* To be called last on the ThrottleTimers */
267 void throttle_timers_destroy(ThrottleTimers *tt)
268 {
269     throttle_timers_detach_aio_context(tt);
270 }
271 
272 /* is any throttling timer configured */
273 bool throttle_timers_are_initialized(ThrottleTimers *tt)
274 {
275     if (tt->timers[0]) {
276         return true;
277     }
278 
279     return false;
280 }
281 
282 /* Does any throttling must be done
283  *
284  * @cfg: the throttling configuration to inspect
285  * @ret: true if throttling must be done else false
286  */
287 bool throttle_enabled(ThrottleConfig *cfg)
288 {
289     int i;
290 
291     for (i = 0; i < BUCKETS_COUNT; i++) {
292         if (cfg->buckets[i].avg > 0) {
293             return true;
294         }
295     }
296 
297     return false;
298 }
299 
300 /* check if a throttling configuration is valid
301  * @cfg: the throttling configuration to inspect
302  * @ret: true if valid else false
303  * @errp: error object
304  */
305 bool throttle_is_valid(ThrottleConfig *cfg, Error **errp)
306 {
307     int i;
308     bool bps_flag, ops_flag;
309     bool bps_max_flag, ops_max_flag;
310 
311     bps_flag = cfg->buckets[THROTTLE_BPS_TOTAL].avg &&
312                (cfg->buckets[THROTTLE_BPS_READ].avg ||
313                 cfg->buckets[THROTTLE_BPS_WRITE].avg);
314 
315     ops_flag = cfg->buckets[THROTTLE_OPS_TOTAL].avg &&
316                (cfg->buckets[THROTTLE_OPS_READ].avg ||
317                 cfg->buckets[THROTTLE_OPS_WRITE].avg);
318 
319     bps_max_flag = cfg->buckets[THROTTLE_BPS_TOTAL].max &&
320                   (cfg->buckets[THROTTLE_BPS_READ].max  ||
321                    cfg->buckets[THROTTLE_BPS_WRITE].max);
322 
323     ops_max_flag = cfg->buckets[THROTTLE_OPS_TOTAL].max &&
324                    (cfg->buckets[THROTTLE_OPS_READ].max ||
325                    cfg->buckets[THROTTLE_OPS_WRITE].max);
326 
327     if (bps_flag || ops_flag || bps_max_flag || ops_max_flag) {
328         error_setg(errp, "bps/iops/max total values and read/write values"
329                    " cannot be used at the same time");
330         return false;
331     }
332 
333     if (cfg->op_size &&
334         !cfg->buckets[THROTTLE_OPS_TOTAL].avg &&
335         !cfg->buckets[THROTTLE_OPS_READ].avg &&
336         !cfg->buckets[THROTTLE_OPS_WRITE].avg) {
337         error_setg(errp, "iops size requires an iops value to be set");
338         return false;
339     }
340 
341     for (i = 0; i < BUCKETS_COUNT; i++) {
342         LeakyBucket *bkt = &cfg->buckets[i];
343         if (bkt->avg > THROTTLE_VALUE_MAX || bkt->max > THROTTLE_VALUE_MAX) {
344             error_setg(errp, "bps/iops/max values must be within [0, %lld]",
345                        THROTTLE_VALUE_MAX);
346             return false;
347         }
348 
349         if (!bkt->burst_length) {
350             error_setg(errp, "the burst length cannot be 0");
351             return false;
352         }
353 
354         if (bkt->burst_length > 1 && !bkt->max) {
355             error_setg(errp, "burst length set without burst rate");
356             return false;
357         }
358 
359         if (bkt->max && bkt->burst_length > THROTTLE_VALUE_MAX / bkt->max) {
360             error_setg(errp, "burst length too high for this burst rate");
361             return false;
362         }
363 
364         if (bkt->max && !bkt->avg) {
365             error_setg(errp, "bps_max/iops_max require corresponding"
366                        " bps/iops values");
367             return false;
368         }
369 
370         if (bkt->max && bkt->max < bkt->avg) {
371             error_setg(errp, "bps_max/iops_max cannot be lower than bps/iops");
372             return false;
373         }
374     }
375 
376     return true;
377 }
378 
379 /* Used to configure the throttle
380  *
381  * @ts: the throttle state we are working on
382  * @clock_type: the group's clock_type
383  * @cfg: the config to set
384  */
385 void throttle_config(ThrottleState *ts,
386                      QEMUClockType clock_type,
387                      ThrottleConfig *cfg)
388 {
389     int i;
390 
391     ts->cfg = *cfg;
392 
393     /* Zero bucket level */
394     for (i = 0; i < BUCKETS_COUNT; i++) {
395         ts->cfg.buckets[i].level = 0;
396         ts->cfg.buckets[i].burst_level = 0;
397     }
398 
399     ts->previous_leak = qemu_clock_get_ns(clock_type);
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 /* return a ThrottleConfig based on the options in a ThrottleLimits
490  *
491  * @arg:    the ThrottleLimits object to read from
492  * @cfg:    the ThrottleConfig to edit
493  * @errp:   error object
494  */
495 void throttle_limits_to_config(ThrottleLimits *arg, ThrottleConfig *cfg,
496                                Error **errp)
497 {
498     if (arg->has_bps_total) {
499         cfg->buckets[THROTTLE_BPS_TOTAL].avg = arg->bps_total;
500     }
501     if (arg->has_bps_read) {
502         cfg->buckets[THROTTLE_BPS_READ].avg  = arg->bps_read;
503     }
504     if (arg->has_bps_write) {
505         cfg->buckets[THROTTLE_BPS_WRITE].avg = arg->bps_write;
506     }
507 
508     if (arg->has_iops_total) {
509         cfg->buckets[THROTTLE_OPS_TOTAL].avg = arg->iops_total;
510     }
511     if (arg->has_iops_read) {
512         cfg->buckets[THROTTLE_OPS_READ].avg  = arg->iops_read;
513     }
514     if (arg->has_iops_write) {
515         cfg->buckets[THROTTLE_OPS_WRITE].avg = arg->iops_write;
516     }
517 
518     if (arg->has_bps_total_max) {
519         cfg->buckets[THROTTLE_BPS_TOTAL].max = arg->bps_total_max;
520     }
521     if (arg->has_bps_read_max) {
522         cfg->buckets[THROTTLE_BPS_READ].max = arg->bps_read_max;
523     }
524     if (arg->has_bps_write_max) {
525         cfg->buckets[THROTTLE_BPS_WRITE].max = arg->bps_write_max;
526     }
527     if (arg->has_iops_total_max) {
528         cfg->buckets[THROTTLE_OPS_TOTAL].max = arg->iops_total_max;
529     }
530     if (arg->has_iops_read_max) {
531         cfg->buckets[THROTTLE_OPS_READ].max = arg->iops_read_max;
532     }
533     if (arg->has_iops_write_max) {
534         cfg->buckets[THROTTLE_OPS_WRITE].max = arg->iops_write_max;
535     }
536 
537     if (arg->has_bps_total_max_length) {
538         if (arg->bps_total_max_length > UINT_MAX) {
539             error_setg(errp, "bps-total-max-length value must be in"
540                              " the range [0, %u]", UINT_MAX);
541             return;
542         }
543         cfg->buckets[THROTTLE_BPS_TOTAL].burst_length = arg->bps_total_max_length;
544     }
545     if (arg->has_bps_read_max_length) {
546         if (arg->bps_read_max_length > UINT_MAX) {
547             error_setg(errp, "bps-read-max-length value must be in"
548                              " the range [0, %u]", UINT_MAX);
549             return;
550         }
551         cfg->buckets[THROTTLE_BPS_READ].burst_length = arg->bps_read_max_length;
552     }
553     if (arg->has_bps_write_max_length) {
554         if (arg->bps_write_max_length > UINT_MAX) {
555             error_setg(errp, "bps-write-max-length value must be in"
556                              " the range [0, %u]", UINT_MAX);
557             return;
558         }
559         cfg->buckets[THROTTLE_BPS_WRITE].burst_length = arg->bps_write_max_length;
560     }
561     if (arg->has_iops_total_max_length) {
562         if (arg->iops_total_max_length > UINT_MAX) {
563             error_setg(errp, "iops-total-max-length value must be in"
564                              " the range [0, %u]", UINT_MAX);
565             return;
566         }
567         cfg->buckets[THROTTLE_OPS_TOTAL].burst_length = arg->iops_total_max_length;
568     }
569     if (arg->has_iops_read_max_length) {
570         if (arg->iops_read_max_length > UINT_MAX) {
571             error_setg(errp, "iops-read-max-length value must be in"
572                              " the range [0, %u]", UINT_MAX);
573             return;
574         }
575         cfg->buckets[THROTTLE_OPS_READ].burst_length = arg->iops_read_max_length;
576     }
577     if (arg->has_iops_write_max_length) {
578         if (arg->iops_write_max_length > UINT_MAX) {
579             error_setg(errp, "iops-write-max-length value must be in"
580                              " the range [0, %u]", UINT_MAX);
581             return;
582         }
583         cfg->buckets[THROTTLE_OPS_WRITE].burst_length = arg->iops_write_max_length;
584     }
585 
586     if (arg->has_iops_size) {
587         cfg->op_size = arg->iops_size;
588     }
589 
590     throttle_is_valid(cfg, errp);
591 }
592 
593 /* write the options of a ThrottleConfig to a ThrottleLimits
594  *
595  * @cfg:    the ThrottleConfig to read from
596  * @var:    the ThrottleLimits to write to
597  */
598 void throttle_config_to_limits(ThrottleConfig *cfg, ThrottleLimits *var)
599 {
600     var->bps_total               = cfg->buckets[THROTTLE_BPS_TOTAL].avg;
601     var->bps_read                = cfg->buckets[THROTTLE_BPS_READ].avg;
602     var->bps_write               = cfg->buckets[THROTTLE_BPS_WRITE].avg;
603     var->iops_total              = cfg->buckets[THROTTLE_OPS_TOTAL].avg;
604     var->iops_read               = cfg->buckets[THROTTLE_OPS_READ].avg;
605     var->iops_write              = cfg->buckets[THROTTLE_OPS_WRITE].avg;
606     var->bps_total_max           = cfg->buckets[THROTTLE_BPS_TOTAL].max;
607     var->bps_read_max            = cfg->buckets[THROTTLE_BPS_READ].max;
608     var->bps_write_max           = cfg->buckets[THROTTLE_BPS_WRITE].max;
609     var->iops_total_max          = cfg->buckets[THROTTLE_OPS_TOTAL].max;
610     var->iops_read_max           = cfg->buckets[THROTTLE_OPS_READ].max;
611     var->iops_write_max          = cfg->buckets[THROTTLE_OPS_WRITE].max;
612     var->bps_total_max_length    = cfg->buckets[THROTTLE_BPS_TOTAL].burst_length;
613     var->bps_read_max_length     = cfg->buckets[THROTTLE_BPS_READ].burst_length;
614     var->bps_write_max_length    = cfg->buckets[THROTTLE_BPS_WRITE].burst_length;
615     var->iops_total_max_length   = cfg->buckets[THROTTLE_OPS_TOTAL].burst_length;
616     var->iops_read_max_length    = cfg->buckets[THROTTLE_OPS_READ].burst_length;
617     var->iops_write_max_length   = cfg->buckets[THROTTLE_OPS_WRITE].burst_length;
618     var->iops_size               = cfg->op_size;
619 
620     var->has_bps_total = true;
621     var->has_bps_read = true;
622     var->has_bps_write = true;
623     var->has_iops_total = true;
624     var->has_iops_read = true;
625     var->has_iops_write = true;
626     var->has_bps_total_max = true;
627     var->has_bps_read_max = true;
628     var->has_bps_write_max = true;
629     var->has_iops_total_max = true;
630     var->has_iops_read_max = true;
631     var->has_iops_write_max = true;
632     var->has_bps_read_max_length = true;
633     var->has_bps_total_max_length = true;
634     var->has_bps_write_max_length = true;
635     var->has_iops_total_max_length = true;
636     var->has_iops_read_max_length = true;
637     var->has_iops_write_max_length = true;
638     var->has_iops_size = true;
639 }
640