blob: 5a1cb32aaf8eeed91723de5dedeed3fb3627ed9f [file] [log] [blame]
Willy Tarreau7f062c42009-03-05 18:43:00 +01001/*
Willy Tarreau2438f2b2014-06-16 20:24:22 +02002 * include/proto/freq_ctr.h
3 * This file contains macros and inline functions for frequency counters.
4 *
5 * Copyright (C) 2000-2014 Willy Tarreau - w@1wt.eu
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation, version 2.1
10 * exclusively.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
Willy Tarreau7f062c42009-03-05 18:43:00 +010021
22#ifndef _PROTO_FREQ_CTR_H
23#define _PROTO_FREQ_CTR_H
24
25#include <common/config.h>
Willy Tarreau78ff5d02009-10-01 11:05:26 +020026#include <common/time.h>
Christopher Faulet94b71232017-10-12 09:49:09 +020027#include <common/hathreads.h>
Willy Tarreau7f062c42009-03-05 18:43:00 +010028#include <types/freq_ctr.h>
29
Willy Tarreau7f062c42009-03-05 18:43:00 +010030
31/* Update a frequency counter by <inc> incremental units. It is automatically
32 * rotated if the period is over. It is important that it correctly initializes
33 * a null area.
34 */
Christopher Fauletde2075f2017-09-01 12:18:36 +020035static inline unsigned int update_freq_ctr(struct freq_ctr *ctr, unsigned int inc)
Willy Tarreau7f062c42009-03-05 18:43:00 +010036{
Emeric Brun6e012862017-10-30 18:04:28 +010037 int elapsed;
Christopher Faulet94b71232017-10-12 09:49:09 +020038 unsigned int curr_sec;
Willy Tarreau38deb512021-03-17 19:10:23 +010039 uint32_t now_tmp;
Christopher Faulet94b71232017-10-12 09:49:09 +020040
Willy Tarreau0d6c75d2019-05-25 19:54:40 +020041
42 /* we manipulate curr_ctr using atomic ops out of the lock, since
43 * it's the most frequent access. However if we detect that a change
44 * is needed, it's done under the date lock. We don't care whether
45 * the value we're adding is considered as part of the current or
46 * new period if another thread starts to rotate the period while
47 * we operate, since timing variations would have resulted in the
48 * same uncertainty as well.
49 */
50 curr_sec = ctr->curr_sec;
Christopher Faulet94b71232017-10-12 09:49:09 +020051 do {
Willy Tarreau38deb512021-03-17 19:10:23 +010052 now_tmp = global_now >> 32;
53 if (curr_sec == (now_tmp & 0x7fffffff))
54 return _HA_ATOMIC_ADD(&ctr->curr_ctr, inc);
55
Christopher Faulet94b71232017-10-12 09:49:09 +020056 /* remove the bit, used for the lock */
Willy Tarreau0d6c75d2019-05-25 19:54:40 +020057 curr_sec &= 0x7fffffff;
58 } while (!_HA_ATOMIC_CAS(&ctr->curr_sec, &curr_sec, curr_sec | 0x80000000));
Olivier Houchardd5f9b192019-03-08 18:47:59 +010059 __ha_barrier_atomic_store();
Willy Tarreau7f062c42009-03-05 18:43:00 +010060
Willy Tarreau38deb512021-03-17 19:10:23 +010061 elapsed = (now_tmp & 0x7fffffff) - curr_sec;
Emeric Brun6e012862017-10-30 18:04:28 +010062 if (unlikely(elapsed > 0)) {
Christopher Faulet94b71232017-10-12 09:49:09 +020063 ctr->prev_ctr = ctr->curr_ctr;
Willy Tarreau0d6c75d2019-05-25 19:54:40 +020064 _HA_ATOMIC_SUB(&ctr->curr_ctr, ctr->prev_ctr);
Christopher Faulet94b71232017-10-12 09:49:09 +020065 if (likely(elapsed != 1)) {
66 /* we missed more than one second */
67 ctr->prev_ctr = 0;
68 }
Willy Tarreau38deb512021-03-17 19:10:23 +010069 curr_sec = now_tmp;
Willy Tarreau2970b0b2010-06-20 07:15:43 +020070 }
Christopher Faulet94b71232017-10-12 09:49:09 +020071
Christopher Faulet94b71232017-10-12 09:49:09 +020072 /* release the lock and update the time in case of rotate. */
Olivier Houchardd5f9b192019-03-08 18:47:59 +010073 _HA_ATOMIC_STORE(&ctr->curr_sec, curr_sec & 0x7fffffff);
Willy Tarreau0d6c75d2019-05-25 19:54:40 +020074
75 return _HA_ATOMIC_ADD(&ctr->curr_ctr, inc);
Willy Tarreau2970b0b2010-06-20 07:15:43 +020076}
77
78/* Update a frequency counter by <inc> incremental units. It is automatically
79 * rotated if the period is over. It is important that it correctly initializes
80 * a null area. This one works on frequency counters which have a period
81 * different from one second.
82 */
Christopher Fauletde2075f2017-09-01 12:18:36 +020083static inline unsigned int update_freq_ctr_period(struct freq_ctr_period *ctr,
84 unsigned int period, unsigned int inc)
Willy Tarreau2970b0b2010-06-20 07:15:43 +020085{
Christopher Faulet94b71232017-10-12 09:49:09 +020086 unsigned int curr_tick;
Willy Tarreau38deb512021-03-17 19:10:23 +010087 uint32_t now_ms_tmp;
Christopher Faulet94b71232017-10-12 09:49:09 +020088
Willy Tarreau0d6c75d2019-05-25 19:54:40 +020089 curr_tick = ctr->curr_tick;
Christopher Faulet94b71232017-10-12 09:49:09 +020090 do {
Willy Tarreau38deb512021-03-17 19:10:23 +010091 now_ms_tmp = (uint32_t)global_now / 1000;
92 if (now_ms_tmp - curr_tick < period)
93 return _HA_ATOMIC_ADD(&ctr->curr_ctr, inc);
94
Christopher Faulet94b71232017-10-12 09:49:09 +020095 /* remove the bit, used for the lock */
Willy Tarreau0d6c75d2019-05-25 19:54:40 +020096 curr_tick &= ~1;
97 } while (!_HA_ATOMIC_CAS(&ctr->curr_tick, &curr_tick, curr_tick | 0x1));
Olivier Houchardd5f9b192019-03-08 18:47:59 +010098 __ha_barrier_atomic_store();
Christopher Faulet94b71232017-10-12 09:49:09 +020099
Willy Tarreau38deb512021-03-17 19:10:23 +0100100 if (now_ms_tmp - curr_tick >= period) {
Christopher Faulet94b71232017-10-12 09:49:09 +0200101 ctr->prev_ctr = ctr->curr_ctr;
Willy Tarreau0d6c75d2019-05-25 19:54:40 +0200102 _HA_ATOMIC_SUB(&ctr->curr_ctr, ctr->prev_ctr);
Christopher Faulet94b71232017-10-12 09:49:09 +0200103 curr_tick += period;
Willy Tarreau38deb512021-03-17 19:10:23 +0100104 if (likely(now_ms_tmp - curr_tick >= period)) {
Christopher Faulet94b71232017-10-12 09:49:09 +0200105 /* we missed at least two periods */
106 ctr->prev_ctr = 0;
Willy Tarreau38deb512021-03-17 19:10:23 +0100107 curr_tick = now_ms_tmp;
Christopher Faulet94b71232017-10-12 09:49:09 +0200108 }
Willy Tarreau0d6c75d2019-05-25 19:54:40 +0200109 curr_tick &= ~1;
Willy Tarreau2970b0b2010-06-20 07:15:43 +0200110 }
Christopher Faulet94b71232017-10-12 09:49:09 +0200111
Christopher Faulet94b71232017-10-12 09:49:09 +0200112 /* release the lock and update the time in case of rotate. */
Willy Tarreau0d6c75d2019-05-25 19:54:40 +0200113 _HA_ATOMIC_STORE(&ctr->curr_tick, curr_tick);
114
115 return _HA_ATOMIC_ADD(&ctr->curr_ctr, inc);
Willy Tarreau2970b0b2010-06-20 07:15:43 +0200116}
117
Willy Tarreau7f062c42009-03-05 18:43:00 +0100118/* Read a frequency counter taking history into account for missing time in
119 * current period.
120 */
121unsigned int read_freq_ctr(struct freq_ctr *ctr);
122
Willy Tarreau79584222009-03-06 09:18:27 +0100123/* returns the number of remaining events that can occur on this freq counter
124 * while respecting <freq> and taking into account that <pend> events are
125 * already known to be pending. Returns 0 if limit was reached.
126 */
127unsigned int freq_ctr_remain(struct freq_ctr *ctr, unsigned int freq, unsigned int pend);
128
129/* return the expected wait time in ms before the next event may occur,
130 * respecting frequency <freq>, and assuming there may already be some pending
131 * events. It returns zero if we can proceed immediately, otherwise the wait
132 * time, which will be rounded down 1ms for better accuracy, with a minimum
133 * of one ms.
134 */
135unsigned int next_event_delay(struct freq_ctr *ctr, unsigned int freq, unsigned int pend);
136
Willy Tarreau2970b0b2010-06-20 07:15:43 +0200137/* process freq counters over configurable periods */
138unsigned int read_freq_ctr_period(struct freq_ctr_period *ctr, unsigned int period);
139unsigned int freq_ctr_remain_period(struct freq_ctr_period *ctr, unsigned int period,
140 unsigned int freq, unsigned int pend);
141
Willy Tarreau2438f2b2014-06-16 20:24:22 +0200142/* While the functions above report average event counts per period, we are
143 * also interested in average values per event. For this we use a different
144 * method. The principle is to rely on a long tail which sums the new value
145 * with a fraction of the previous value, resulting in a sliding window of
146 * infinite length depending on the precision we're interested in.
147 *
148 * The idea is that we always keep (N-1)/N of the sum and add the new sampled
149 * value. The sum over N values can be computed with a simple program for a
150 * constant value 1 at each iteration :
151 *
152 * N
153 * ,---
154 * \ N - 1 e - 1
155 * > ( --------- )^x ~= N * -----
156 * / N e
157 * '---
158 * x = 1
159 *
160 * Note: I'm not sure how to demonstrate this but at least this is easily
161 * verified with a simple program, the sum equals N * 0.632120 for any N
162 * moderately large (tens to hundreds).
163 *
164 * Inserting a constant sample value V here simply results in :
165 *
166 * sum = V * N * (e - 1) / e
167 *
168 * But we don't want to integrate over a small period, but infinitely. Let's
169 * cut the infinity in P periods of N values. Each period M is exactly the same
170 * as period M-1 with a factor of ((N-1)/N)^N applied. A test shows that given a
171 * large N :
172 *
173 * N - 1 1
174 * ( ------- )^N ~= ---
175 * N e
176 *
177 * Our sum is now a sum of each factor times :
178 *
179 * N*P P
180 * ,--- ,---
181 * \ N - 1 e - 1 \ 1
182 * > v ( --------- )^x ~= VN * ----- * > ---
183 * / N e / e^x
184 * '--- '---
185 * x = 1 x = 0
186 *
187 * For P "large enough", in tests we get this :
188 *
189 * P
190 * ,---
191 * \ 1 e
192 * > --- ~= -----
193 * / e^x e - 1
194 * '---
195 * x = 0
196 *
197 * This simplifies the sum above :
198 *
199 * N*P
200 * ,---
201 * \ N - 1
202 * > v ( --------- )^x = VN
203 * / N
204 * '---
205 * x = 1
206 *
207 * So basically by summing values and applying the last result an (N-1)/N factor
208 * we just get N times the values over the long term, so we can recover the
Willy Tarreau37585812016-11-25 11:55:10 +0100209 * constant value V by dividing by N. In order to limit the impact of integer
210 * overflows, we'll use this equivalence which saves us one multiply :
211 *
212 * N - 1 1 x0
213 * x1 = x0 * ------- = x0 * ( 1 - --- ) = x0 - ----
214 * N N N
215 *
216 * And given that x0 is discrete here we'll have to saturate the values before
217 * performing the divide, so the value insertion will become :
218 *
219 * x0 + N - 1
220 * x1 = x0 - ------------
221 * N
Willy Tarreau2438f2b2014-06-16 20:24:22 +0200222 *
223 * A value added at the entry of the sliding window of N values will thus be
224 * reduced to 1/e or 36.7% after N terms have been added. After a second batch,
225 * it will only be 1/e^2, or 13.5%, and so on. So practically speaking, each
226 * old period of N values represents only a quickly fading ratio of the global
227 * sum :
228 *
229 * period ratio
230 * 1 36.7%
231 * 2 13.5%
232 * 3 4.98%
233 * 4 1.83%
234 * 5 0.67%
235 * 6 0.25%
236 * 7 0.09%
237 * 8 0.033%
238 * 9 0.012%
239 * 10 0.0045%
240 *
241 * So after 10N samples, the initial value has already faded out by a factor of
242 * 22026, which is quite fast. If the sliding window is 1024 samples wide, it
243 * means that a sample will only count for 1/22k of its initial value after 10k
244 * samples went after it, which results in half of the value it would represent
245 * using an arithmetic mean. The benefit of this method is that it's very cheap
246 * in terms of computations when N is a power of two. This is very well suited
247 * to record response times as large values will fade out faster than with an
248 * arithmetic mean and will depend on sample count and not time.
249 *
250 * Demonstrating all the above assumptions with maths instead of a program is
251 * left as an exercise for the reader.
252 */
253
254/* Adds sample value <v> to sliding window sum <sum> configured for <n> samples.
Christopher Fauletaacd2fa2019-11-08 14:40:18 +0100255 * The sample is returned. Better if <n> is a power of two. This function is
256 * thread-safe.
Willy Tarreau2438f2b2014-06-16 20:24:22 +0200257 */
258static inline unsigned int swrate_add(unsigned int *sum, unsigned int n, unsigned int v)
259{
Christopher Fauletaacd2fa2019-11-08 14:40:18 +0100260 unsigned int new_sum, old_sum;
261
262 old_sum = *sum;
263 do {
264 new_sum = old_sum - (old_sum + n - 1) / n + v;
265 } while (!_HA_ATOMIC_CAS(sum, &old_sum, new_sum));
266 return new_sum;
Willy Tarreau2438f2b2014-06-16 20:24:22 +0200267}
268
Willy Tarreau627505d2018-10-17 09:24:56 +0200269/* Adds sample value <v> spanning <s> samples to sliding window sum <sum>
270 * configured for <n> samples, where <n> is supposed to be "much larger" than
271 * <s>. The sample is returned. Better if <n> is a power of two. Note that this
272 * is only an approximate. Indeed, as can be seen with two samples only over a
273 * 8-sample window, the original function would return :
274 * sum1 = sum - (sum + 7) / 8 + v
275 * sum2 = sum1 - (sum1 + 7) / 8 + v
276 * = (sum - (sum + 7) / 8 + v) - (sum - (sum + 7) / 8 + v + 7) / 8 + v
277 * ~= 7sum/8 - 7/8 + v - sum/8 + sum/64 - 7/64 - v/8 - 7/8 + v
278 * ~= (3sum/4 + sum/64) - (7/4 + 7/64) + 15v/8
279 *
280 * while the function below would return :
281 * sum = sum + 2*v - (sum + 8) * 2 / 8
282 * = 3sum/4 + 2v - 2
283 *
284 * this presents an error of ~ (sum/64 + 9/64 + v/8) = (sum+n+1)/(n^s) + v/n
285 *
286 * Thus the simplified function effectively replaces a part of the history with
287 * a linear sum instead of applying the exponential one. But as long as s/n is
288 * "small enough", the error fades away and remains small for both small and
Christopher Fauletaacd2fa2019-11-08 14:40:18 +0100289 * large values of n and s (typically < 0.2% measured). This function is
290 * thread-safe.
Willy Tarreau627505d2018-10-17 09:24:56 +0200291 */
292static inline unsigned int swrate_add_scaled(unsigned int *sum, unsigned int n, unsigned int v, unsigned int s)
293{
Christopher Fauletaacd2fa2019-11-08 14:40:18 +0100294 unsigned int new_sum, old_sum;
295
296 old_sum = *sum;
297 do {
298 new_sum = old_sum + v * s - div64_32((unsigned long long)(old_sum + n) * s, n);
299 } while (!_HA_ATOMIC_CAS(sum, &old_sum, new_sum));
300 return new_sum;
Willy Tarreau627505d2018-10-17 09:24:56 +0200301}
302
Willy Tarreau2438f2b2014-06-16 20:24:22 +0200303/* Returns the average sample value for the sum <sum> over a sliding window of
304 * <n> samples. Better if <n> is a power of two. It must be the same <n> as the
305 * one used above in all additions.
306 */
307static inline unsigned int swrate_avg(unsigned int sum, unsigned int n)
308{
309 return (sum + n - 1) / n;
310}
311
Willy Tarreau7f062c42009-03-05 18:43:00 +0100312#endif /* _PROTO_FREQ_CTR_H */
313
314/*
315 * Local variables:
316 * c-indent-level: 8
317 * c-basic-offset: 8
318 * End:
319 */