2 * Ratelimiting calculations
4 * Copyright IBM, Corp. 2011
7 * Stefan Hajnoczi <stefanha@linux.vnet.ibm.com>
9 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10 * See the COPYING.LIB file in the top-level directory.
14 #ifndef QEMU_RATELIMIT_H
15 #define QEMU_RATELIMIT_H
17 #include "qemu/timer.h"
20 int64_t slice_start_time
;
21 int64_t slice_end_time
;
27 /** Calculate and return delay for next request in ns
29 * Record that we sent @n data units (where @n matches the scale chosen
30 * during ratelimit_set_speed). If we may send more data units
31 * in the current time slice, return 0 (i.e. no delay). Otherwise
32 * return the amount of time (in ns) until the start of the next time
33 * slice that will permit sending the next chunk of data.
35 * Recording sent data units even after exceeding the quota is
36 * permitted; the time slice will be extended accordingly.
38 static inline int64_t ratelimit_calculate_delay(RateLimit
*limit
, uint64_t n
)
40 int64_t now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
43 assert(limit
->slice_quota
&& limit
->slice_ns
);
45 if (limit
->slice_end_time
< now
) {
46 /* Previous, possibly extended, time slice finished; reset the
48 limit
->slice_start_time
= now
;
49 limit
->slice_end_time
= now
+ limit
->slice_ns
;
50 limit
->dispatched
= 0;
53 limit
->dispatched
+= n
;
54 if (limit
->dispatched
< limit
->slice_quota
) {
55 /* We may send further data within the current time slice, no
56 * need to delay the next request. */
60 /* Quota exceeded. Wait based on the excess amount and then start a new
62 delay_slices
= (double)limit
->dispatched
/ limit
->slice_quota
;
63 limit
->slice_end_time
= limit
->slice_start_time
+
64 (uint64_t)(delay_slices
* limit
->slice_ns
);
65 return limit
->slice_end_time
- now
;
68 static inline void ratelimit_set_speed(RateLimit
*limit
, uint64_t speed
,
71 limit
->slice_ns
= slice_ns
;
72 limit
->slice_quota
= MAX(((double)speed
* slice_ns
) / 1000000000ULL, 1);