xref: /qemu/include/qemu/ratelimit.h (revision 603476c2)
1 /*
2  * Ratelimiting calculations
3  *
4  * Copyright IBM, Corp. 2011
5  *
6  * Authors:
7  *  Stefan Hajnoczi   <stefanha@linux.vnet.ibm.com>
8  *
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.
11  *
12  */
13 
14 #ifndef QEMU_RATELIMIT_H
15 #define QEMU_RATELIMIT_H
16 
17 typedef struct {
18     int64_t slice_start_time;
19     int64_t slice_end_time;
20     uint64_t slice_quota;
21     uint64_t slice_ns;
22     uint64_t dispatched;
23 } RateLimit;
24 
25 /** Calculate and return delay for next request in ns
26  *
27  * Record that we sent @p n data units. If we may send more data units
28  * in the current time slice, return 0 (i.e. no delay). Otherwise
29  * return the amount of time (in ns) until the start of the next time
30  * slice that will permit sending the next chunk of data.
31  *
32  * Recording sent data units even after exceeding the quota is
33  * permitted; the time slice will be extended accordingly.
34  */
35 static inline int64_t ratelimit_calculate_delay(RateLimit *limit, uint64_t n)
36 {
37     int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
38     uint64_t delay_slices;
39 
40     assert(limit->slice_quota && limit->slice_ns);
41 
42     if (limit->slice_end_time < now) {
43         /* Previous, possibly extended, time slice finished; reset the
44          * accounting. */
45         limit->slice_start_time = now;
46         limit->slice_end_time = now + limit->slice_ns;
47         limit->dispatched = 0;
48     }
49 
50     limit->dispatched += n;
51     if (limit->dispatched < limit->slice_quota) {
52         /* We may send further data within the current time slice, no
53          * need to delay the next request. */
54         return 0;
55     }
56 
57     /* Quota exceeded. Calculate the next time slice we may start
58      * sending data again. */
59     delay_slices = (limit->dispatched + limit->slice_quota - 1) /
60         limit->slice_quota;
61     limit->slice_end_time = limit->slice_start_time +
62         delay_slices * limit->slice_ns;
63     return limit->slice_end_time - now;
64 }
65 
66 static inline void ratelimit_set_speed(RateLimit *limit, uint64_t speed,
67                                        uint64_t slice_ns)
68 {
69     limit->slice_ns = slice_ns;
70     limit->slice_quota = MAX(((double)speed * slice_ns) / 1000000000ULL, 1);
71 }
72 
73 #endif
74