xref: /freebsd/sys/kern/subr_counter.c (revision 1cd5c35d136e2c8605b9ba23e6a5879539411947)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/kernel.h>
32 #include <sys/lock.h>
33 #include <sys/mutex.h>
34 #include <sys/proc.h>
35 #include <sys/sched.h>
36 #include <sys/smp.h>
37 #include <sys/sysctl.h>
38 #include <vm/uma.h>
39 
40 #define IN_SUBR_COUNTER_C
41 #include <sys/counter.h>
42 
43 static MALLOC_DEFINE(M_COUNTER_RATE, "counter_rate", "counter rate allocations");
44 
45 void
counter_u64_zero(counter_u64_t c)46 counter_u64_zero(counter_u64_t c)
47 {
48 
49 	counter_u64_zero_inline(c);
50 }
51 
52 uint64_t
counter_u64_fetch(counter_u64_t c)53 counter_u64_fetch(counter_u64_t c)
54 {
55 
56 	return (counter_u64_fetch_inline(c));
57 }
58 
59 counter_u64_t
counter_u64_alloc(int flags)60 counter_u64_alloc(int flags)
61 {
62 
63 	return (uma_zalloc_pcpu(pcpu_zone_8, flags | M_ZERO));
64 }
65 
66 void
counter_u64_free(counter_u64_t c)67 counter_u64_free(counter_u64_t c)
68 {
69 
70 	uma_zfree_pcpu(pcpu_zone_8, c);
71 }
72 
73 int
sysctl_handle_counter_u64(SYSCTL_HANDLER_ARGS)74 sysctl_handle_counter_u64(SYSCTL_HANDLER_ARGS)
75 {
76 	uint64_t out;
77 	int error;
78 
79 	out = counter_u64_fetch(*(counter_u64_t *)arg1);
80 
81 	error = SYSCTL_OUT(req, &out, sizeof(uint64_t));
82 
83 	if (error || !req->newptr)
84 		return (error);
85 
86 	/*
87 	 * Any write attempt to a counter zeroes it.
88 	 */
89 	counter_u64_zero(*(counter_u64_t *)arg1);
90 
91 	return (0);
92 }
93 
94 int
sysctl_handle_counter_u64_array(SYSCTL_HANDLER_ARGS)95 sysctl_handle_counter_u64_array(SYSCTL_HANDLER_ARGS)
96 {
97 	uint64_t *out;
98 	int error;
99 
100 	out = malloc(arg2 * sizeof(uint64_t), M_TEMP, M_WAITOK);
101 	for (int i = 0; i < arg2; i++)
102 		out[i] = counter_u64_fetch(((counter_u64_t *)arg1)[i]);
103 
104 	error = SYSCTL_OUT(req, out, arg2 * sizeof(uint64_t));
105 	free(out, M_TEMP);
106 
107 	if (error || !req->newptr)
108 		return (error);
109 
110 	/*
111 	 * Any write attempt to a counter zeroes it.
112 	 */
113 	for (int i = 0; i < arg2; i++)
114 		counter_u64_zero(((counter_u64_t *)arg1)[i]);
115 
116 	return (0);
117 }
118 
119 /*
120  * counter(9) based rate checking.
121  */
122 struct counter_rate {
123 	counter_u64_t	cr_rate;	/* Events since last second */
124 	volatile int	cr_lock;	/* Lock to clean the struct */
125 	int		cr_ticks;	/* Ticks on last clean */
126 	int		cr_over;	/* Over limit since cr_ticks? */
127 	int		cr_period;	/* Allow cr_rate per cr_period seconds. */
128 };
129 
130 struct counter_rate *
counter_rate_alloc(int flags,int period)131 counter_rate_alloc(int flags, int period)
132 {
133 	struct counter_rate *new;
134 
135 	new = malloc(sizeof(struct counter_rate), M_COUNTER_RATE,
136 	    flags | M_ZERO);
137 	if (new == NULL)
138 		return (NULL);
139 
140 	new->cr_rate = counter_u64_alloc(flags);
141 	if (new->cr_rate == NULL) {
142 		free(new, M_COUNTER_RATE);
143 		return (NULL);
144 	}
145 	new->cr_ticks = ticks;
146 	new->cr_period = period;
147 
148 	return (new);
149 }
150 
151 void
counter_rate_free(struct counter_rate * rate)152 counter_rate_free(struct counter_rate *rate)
153 {
154 	if (rate == NULL)
155 		return;
156 
157 	counter_u64_free(rate->cr_rate);
158 	free(rate, M_COUNTER_RATE);
159 }
160 
161 uint64_t
counter_rate_get(struct counter_rate * cr)162 counter_rate_get(struct counter_rate *cr)
163 {
164 	if (cr->cr_ticks < (tick - (hz * cr->cr_period)))
165 		return (0);
166 
167 	return (counter_u64_fetch(cr->cr_rate));
168 }
169 
170 /*
171  * MP-friendly version of ppsratecheck().
172  *
173  * Returns non-negative if we are in the rate, negative otherwise.
174  *  0 - rate limit not reached.
175  * -1 - rate limit reached.
176  * >0 - rate limit was reached before, and was just reset. The return value
177  *      is number of events since last reset.
178  */
179 int64_t
counter_ratecheck(struct counter_rate * cr,int64_t limit)180 counter_ratecheck(struct counter_rate *cr, int64_t limit)
181 {
182 	int64_t val;
183 	int now;
184 
185 	val = cr->cr_over;
186 	now = ticks;
187 
188 	if ((u_int)(now - cr->cr_ticks) >= (hz * cr->cr_period)) {
189 		/*
190 		 * Time to clear the structure, we are in the next second.
191 		 * First try unlocked read, and then proceed with atomic.
192 		 */
193 		if ((cr->cr_lock == 0) &&
194 		    atomic_cmpset_acq_int(&cr->cr_lock, 0, 1)) {
195 			/*
196 			 * Check if other thread has just went through the
197 			 * reset sequence before us.
198 			 */
199 			if ((u_int)(now - cr->cr_ticks) >= (hz * cr->cr_period)) {
200 				val = counter_u64_fetch(cr->cr_rate);
201 				counter_u64_zero(cr->cr_rate);
202 				cr->cr_over = 0;
203 				cr->cr_ticks = now;
204 				if (val <= limit)
205 					val = 0;
206 			}
207 			atomic_store_rel_int(&cr->cr_lock, 0);
208 		} else
209 			/*
210 			 * We failed to lock, in this case other thread may
211 			 * be running counter_u64_zero(), so it is not safe
212 			 * to do an update, we skip it.
213 			 */
214 			return (val);
215 	}
216 
217 	counter_u64_add(cr->cr_rate, 1);
218 	if (cr->cr_over != 0)
219 		return (-1);
220 	if (counter_u64_fetch(cr->cr_rate) > limit)
221 		val = cr->cr_over = -1;
222 
223 	return (val);
224 }
225 
226 void
counter_u64_sysinit(void * arg)227 counter_u64_sysinit(void *arg)
228 {
229 	counter_u64_t *cp;
230 
231 	cp = arg;
232 	*cp = counter_u64_alloc(M_WAITOK);
233 }
234 
235 void
counter_u64_sysuninit(void * arg)236 counter_u64_sysuninit(void *arg)
237 {
238 	counter_u64_t *cp;
239 
240 	cp = arg;
241 	counter_u64_free(*cp);
242 }
243