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
18 int64_t slice_start_time
;
19 int64_t slice_end_time
;
25 /** Calculate and return delay for next request in ns
27 * Record that we sent @n data units (where @n matches the scale chosen
28 * during ratelimit_set_speed). If we may send more data units
29 * in the current time slice, return 0 (i.e. no delay). Otherwise
30 * return the amount of time (in ns) until the start of the next time
31 * slice that will permit sending the next chunk of data.
33 * Recording sent data units even after exceeding the quota is
34 * permitted; the time slice will be extended accordingly.
36 static inline int64_t ratelimit_calculate_delay(RateLimit
*limit
, uint64_t n
)
38 int64_t now
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
39 uint64_t delay_slices
;
41 assert(limit
->slice_quota
&& limit
->slice_ns
);
43 if (limit
->slice_end_time
< now
) {
44 /* Previous, possibly extended, time slice finished; reset the
46 limit
->slice_start_time
= now
;
47 limit
->slice_end_time
= now
+ limit
->slice_ns
;
48 limit
->dispatched
= 0;
51 limit
->dispatched
+= n
;
52 if (limit
->dispatched
< limit
->slice_quota
) {
53 /* We may send further data within the current time slice, no
54 * need to delay the next request. */
58 /* Quota exceeded. Calculate the next time slice we may start
59 * sending data again. */
60 delay_slices
= (limit
->dispatched
+ limit
->slice_quota
- 1) /
62 limit
->slice_end_time
= limit
->slice_start_time
+
63 delay_slices
* limit
->slice_ns
;
64 return limit
->slice_end_time
- now
;
67 static inline void ratelimit_set_speed(RateLimit
*limit
, uint64_t speed
,
70 limit
->slice_ns
= slice_ns
;
71 limit
->slice_quota
= MAX(((double)speed
* slice_ns
) / 1000000000ULL, 1);