1 /*
2 * Copyright © 2008-2011 Kristian Høgsberg
3 * Copyright © 2011 Intel Corporation
4 * Copyright © 2013-2015 Red Hat, Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23 * DEALINGS IN THE SOFTWARE.
24 */
25
26 #include "config.h"
27
28 #include <time.h>
29
30 #include "util-ratelimit.h"
31 #include "util-time.h"
32
33 void
ratelimit_init(struct ratelimit * r,uint64_t ival_us,unsigned int burst)34 ratelimit_init(struct ratelimit *r, uint64_t ival_us, unsigned int burst)
35 {
36 r->interval = ival_us;
37 r->begin = 0;
38 r->burst = burst;
39 r->num = 0;
40 }
41
42 /*
43 * Perform rate-limit test. Returns RATELIMIT_PASS if the rate-limited action
44 * is still allowed, RATELIMIT_THRESHOLD if the limit has been reached with
45 * this call, and RATELIMIT_EXCEEDED if you're beyond the threshold.
46 * It's safe to treat the return-value as boolean, if you're not interested in
47 * the exact state. It evaluates to "true" if the threshold hasn't been
48 * exceeded, yet.
49 *
50 * The ratelimit object must be initialized via ratelimit_init().
51 *
52 * Modelled after Linux' lib/ratelimit.c by Dave Young
53 * <hidave.darkstar@gmail.com>, which is licensed GPLv2.
54 */
55 enum ratelimit_state
ratelimit_test(struct ratelimit * r)56 ratelimit_test(struct ratelimit *r)
57 {
58 struct timespec ts;
59 uint64_t utime;
60
61 if (r->interval <= 0 || r->burst <= 0)
62 return RATELIMIT_PASS;
63
64 clock_gettime(CLOCK_MONOTONIC, &ts);
65 utime = s2us(ts.tv_sec) + ns2us(ts.tv_nsec);
66
67 if (r->begin <= 0 || r->begin + r->interval < utime) {
68 /* reset counter */
69 r->begin = utime;
70 r->num = 1;
71 return RATELIMIT_PASS;
72 } else if (r->num < r->burst) {
73 /* continue burst */
74 return (++r->num == r->burst) ? RATELIMIT_THRESHOLD
75 : RATELIMIT_PASS;
76 }
77
78 return RATELIMIT_EXCEEDED;
79 }
80