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 1 16 17typedef struct { 18 int64_t next_slice_time; 19 uint64_t slice_quota; 20 uint64_t slice_ns; 21 uint64_t dispatched; 22} RateLimit; 23 24static inline int64_t ratelimit_calculate_delay(RateLimit *limit, uint64_t n) 25{ 26 int64_t now = qemu_clock_get_ns(QEMU_CLOCK_REALTIME); 27 28 if (limit->next_slice_time < now) { 29 limit->next_slice_time = now + limit->slice_ns; 30 limit->dispatched = 0; 31 } 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; 38 } 39} 40 41static inline void ratelimit_set_speed(RateLimit *limit, uint64_t speed, 42 uint64_t slice_ns) 43{ 44 limit->slice_ns = slice_ns; 45 limit->slice_quota = ((double)speed * slice_ns)/1000000000ULL; 46} 47 48#endif 49