Debian Codegraph @

src/basic/ratelimit.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "ratelimit.h"
4 #include "time-util.h"
5
6 /* Modelled after Linux' lib/ratelimit.c by Dave Young
7 * <[email protected]>, which is licensed GPLv2. */
8
9 bool ratelimit_below(RateLimit *rl) {
10 usec_t ts;
11
12 assert(rl);
13
14 if (!ratelimit_configured(rl))
15 return true;
16
17 ts = now(CLOCK_MONOTONIC);
18
19 if (rl->begin <= 0 ||
20 usec_sub_unsigned(ts, rl->begin) > rl->interval) {
21 rl->begin = ts; /* Start a new time window */
22 rl->num = 1; /* Reset counter */
23 return true;
24 }
25
26 if (_unlikely_(rl->num == UINT_MAX))
27 return false;
28
29 rl->num++;
30 return rl->num <= rl->burst;
31 }
32
33 unsigned ratelimit_num_dropped(const RateLimit *rl) {
34 assert(rl);
35
36 if (rl->num == UINT_MAX) /* overflow, return as special case */
37 return UINT_MAX;
38
39 return LESS_BY(rl->num, rl->burst);
40 }
41
42 usec_t ratelimit_end(const RateLimit *rl) {
43 assert(rl);
44
45 if (rl->begin == 0)
46 return 0;
47
48 return usec_add(rl->begin, rl->interval);
49 }
50
51 usec_t ratelimit_left(const RateLimit *rl) {
52 assert(rl);
53
54 if (rl->begin == 0)
55 return 0;
56
57 return usec_sub_unsigned(ratelimit_end(rl), now(CLOCK_MONOTONIC));
58 }