blob: 38ace2801316b2d66ef30ad381e0d3cdff7a1d6e [file] [log] [blame]
Neale Rannsc8352bc2018-08-29 10:23:58 -07001/*
2 * Copyright (c) 2018 Cisco and/or its affiliates.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at:
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#ifndef __THROTTLE_H__
17#define __THROTTLE_H__
18
19#include <vlib/vlib.h>
Neale Rannscd35e532018-08-31 02:51:45 -070020#include <vppinfra/xxhash.h>
Neale Rannsc8352bc2018-08-29 10:23:58 -070021
22/**
23 * @brief A throttle
24 * Used in the data plane to decide if a given hash should be throttled,
Paul Vinciguerrabdc0e6b2018-09-22 05:32:50 -070025 * i.e. that the hash has been seen already 'recently'. Recent is the time
Neale Rannsc8352bc2018-08-29 10:23:58 -070026 * given in the throttle's initialisation.
27 */
28typedef struct throttle_t_
29{
30 f64 time;
31 uword **bitmaps;
Neale Rannscd35e532018-08-31 02:51:45 -070032 u64 *seeds;
Neale Rannsc8352bc2018-08-29 10:23:58 -070033 f64 *last_seed_change_time;
34} throttle_t;
35
36#define THROTTLE_BITS (512)
37
38extern void throttle_init (throttle_t * t, u32 n_threads, f64 time);
39
Neale Rannscd35e532018-08-31 02:51:45 -070040always_inline u64
Neale Rannsc8352bc2018-08-29 10:23:58 -070041throttle_seed (throttle_t * t, u32 thread_index, f64 time_now)
42{
43 if (time_now - t->last_seed_change_time[thread_index] > t->time)
44 {
Neale Rannscd35e532018-08-31 02:51:45 -070045 (void) random_u64 (&t->seeds[thread_index]);
Dave Barachb7b92992018-10-17 10:38:51 -040046 clib_memset (t->bitmaps[thread_index], 0, THROTTLE_BITS / BITS (u8));
Neale Rannsc8352bc2018-08-29 10:23:58 -070047
48 t->last_seed_change_time[thread_index] = time_now;
49 }
50 return t->seeds[thread_index];
51}
52
53always_inline int
Neale Rannscd35e532018-08-31 02:51:45 -070054throttle_check (throttle_t * t, u32 thread_index, u64 hash, u64 seed)
Neale Rannsc8352bc2018-08-29 10:23:58 -070055{
56 int drop;
57 uword m;
58 u32 w;
59
Neale Rannscd35e532018-08-31 02:51:45 -070060 hash = clib_xxhash (hash ^ seed);
61
Neale Rannsc8352bc2018-08-29 10:23:58 -070062 /* Select bit number */
63 hash &= THROTTLE_BITS - 1;
64 w = hash / BITS (uword);
65 m = (uword) 1 << (hash % BITS (uword));
66
67 drop = (t->bitmaps[thread_index][w] & m) != 0;
68 t->bitmaps[thread_index][w] |= m;
69
70 return (drop);
71}
72
73#endif
74
75/*
76 * fd.io coding-style-patch-verification: ON
77 *
78 * Local Variables:
79 * eval: (c-set-style "gnu")
80 * End:
81 */