Merge remote-tracking branch 'remotes/mdroth/tags/qga-pull-2016-03-21-tag' into staging
[qemu.git] / include / qemu / ratelimit.h
blobd413a4a696b78f79628e459395bb87dd35d681c1
1 /*
2 * Ratelimiting calculations
4 * Copyright IBM, Corp. 2011
6 * Authors:
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 1
17 typedef struct {
18 int64_t next_slice_time;
19 uint64_t slice_quota;
20 uint64_t slice_ns;
21 uint64_t dispatched;
22 } RateLimit;
24 static inline int64_t ratelimit_calculate_delay(RateLimit *limit, uint64_t n)
26 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);
28 if (limit->next_slice_time < now) {
29 limit->next_slice_time = now + limit->slice_ns;
30 limit->dispatched = 0;
32 if (limit->dispatched == 0 || limit->dispatched + n <= limit->slice_quota) {
33 limit->dispatched += n;
34 return 0;
35 } else {
36 limit->dispatched = n;
37 return limit->next_slice_time - now;
41 static inline void ratelimit_set_speed(RateLimit *limit, uint64_t speed,
42 uint64_t slice_ns)
44 limit->slice_ns = slice_ns;
45 limit->slice_quota = ((double)speed * slice_ns)/1000000000ULL;
48 #endif