]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - net/netfilter/ipset/ip_set_hash_gen.h
Merge remote-tracking branch 'driver-core/driver-core-next'
[karo-tx-linux.git] / net / netfilter / ipset / ip_set_hash_gen.h
1 /* Copyright (C) 2013 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
2  *
3  * This program is free software; you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License version 2 as
5  * published by the Free Software Foundation.
6  */
7
8 #ifndef _IP_SET_HASH_GEN_H
9 #define _IP_SET_HASH_GEN_H
10
11 #include <linux/rcupdate.h>
12 #include <linux/jhash.h>
13 #include <linux/netfilter/ipset/ip_set_timeout.h>
14 #ifndef rcu_dereference_bh
15 #define rcu_dereference_bh(p)   rcu_dereference(p)
16 #endif
17
18 #define rcu_dereference_bh_nfnl(p)      rcu_dereference_bh_check(p, 1)
19
20 /* Hashing which uses arrays to resolve clashing. The hash table is resized
21  * (doubled) when searching becomes too long.
22  * Internally jhash is used with the assumption that the size of the
23  * stored data is a multiple of sizeof(u32). If storage supports timeout,
24  * the timeout field must be the last one in the data structure - that field
25  * is ignored when computing the hash key.
26  *
27  * Readers and resizing
28  *
29  * Resizing can be triggered by userspace command only, and those
30  * are serialized by the nfnl mutex. During resizing the set is
31  * read-locked, so the only possible concurrent operations are
32  * the kernel side readers. Those must be protected by proper RCU locking.
33  */
34
35 /* Number of elements to store in an initial array block */
36 #define AHASH_INIT_SIZE                 4
37 /* Max number of elements to store in an array block */
38 #define AHASH_MAX_SIZE                  (3*AHASH_INIT_SIZE)
39
40 /* Max number of elements can be tuned */
41 #ifdef IP_SET_HASH_WITH_MULTI
42 #define AHASH_MAX(h)                    ((h)->ahash_max)
43
44 static inline u8
45 tune_ahash_max(u8 curr, u32 multi)
46 {
47         u32 n;
48
49         if (multi < curr)
50                 return curr;
51
52         n = curr + AHASH_INIT_SIZE;
53         /* Currently, at listing one hash bucket must fit into a message.
54          * Therefore we have a hard limit here.
55          */
56         return n > curr && n <= 64 ? n : curr;
57 }
58 #define TUNE_AHASH_MAX(h, multi)        \
59         ((h)->ahash_max = tune_ahash_max((h)->ahash_max, multi))
60 #else
61 #define AHASH_MAX(h)                    AHASH_MAX_SIZE
62 #define TUNE_AHASH_MAX(h, multi)
63 #endif
64
65 /* A hash bucket */
66 struct hbucket {
67         void *value;            /* the array of the values */
68         u8 size;                /* size of the array */
69         u8 pos;                 /* position of the first free entry */
70 };
71
72 /* The hash table: the table size stored here in order to make resizing easy */
73 struct htable {
74         u8 htable_bits;         /* size of hash table == 2^htable_bits */
75         struct hbucket bucket[0]; /* hashtable buckets */
76 };
77
78 #define hbucket(h, i)           (&((h)->bucket[i]))
79
80 #ifndef IPSET_NET_COUNT
81 #define IPSET_NET_COUNT         1
82 #endif
83
84 /* Book-keeping of the prefixes added to the set */
85 struct net_prefixes {
86         u32 nets[IPSET_NET_COUNT]; /* number of elements per cidr */
87         u8 cidr[IPSET_NET_COUNT];  /* the different cidr values in the set */
88 };
89
90 /* Compute the hash table size */
91 static size_t
92 htable_size(u8 hbits)
93 {
94         size_t hsize;
95
96         /* We must fit both into u32 in jhash and size_t */
97         if (hbits > 31)
98                 return 0;
99         hsize = jhash_size(hbits);
100         if ((((size_t)-1) - sizeof(struct htable))/sizeof(struct hbucket)
101             < hsize)
102                 return 0;
103
104         return hsize * sizeof(struct hbucket) + sizeof(struct htable);
105 }
106
107 /* Compute htable_bits from the user input parameter hashsize */
108 static u8
109 htable_bits(u32 hashsize)
110 {
111         /* Assume that hashsize == 2^htable_bits */
112         u8 bits = fls(hashsize - 1);
113         if (jhash_size(bits) != hashsize)
114                 /* Round up to the first 2^n value */
115                 bits = fls(hashsize);
116
117         return bits;
118 }
119
120 static int
121 hbucket_elem_add(struct hbucket *n, u8 ahash_max, size_t dsize)
122 {
123         if (n->pos >= n->size) {
124                 void *tmp;
125
126                 if (n->size >= ahash_max)
127                         /* Trigger rehashing */
128                         return -EAGAIN;
129
130                 tmp = kzalloc((n->size + AHASH_INIT_SIZE) * dsize,
131                               GFP_ATOMIC);
132                 if (!tmp)
133                         return -ENOMEM;
134                 if (n->size) {
135                         memcpy(tmp, n->value, n->size * dsize);
136                         kfree(n->value);
137                 }
138                 n->value = tmp;
139                 n->size += AHASH_INIT_SIZE;
140         }
141         return 0;
142 }
143
144 #ifdef IP_SET_HASH_WITH_NETS
145 #if IPSET_NET_COUNT > 1
146 #define __CIDR(cidr, i)         (cidr[i])
147 #else
148 #define __CIDR(cidr, i)         (cidr)
149 #endif
150 #ifdef IP_SET_HASH_WITH_NETS_PACKED
151 /* When cidr is packed with nomatch, cidr - 1 is stored in the entry */
152 #define CIDR(cidr, i)           (__CIDR(cidr, i) + 1)
153 #else
154 #define CIDR(cidr, i)           (__CIDR(cidr, i))
155 #endif
156
157 #define SET_HOST_MASK(family)   (family == AF_INET ? 32 : 128)
158
159 #ifdef IP_SET_HASH_WITH_MULTI
160 #define NLEN(family)            (SET_HOST_MASK(family) + 1)
161 #else
162 #define NLEN(family)            SET_HOST_MASK(family)
163 #endif
164
165 #else
166 #define NLEN(family)            0
167 #endif /* IP_SET_HASH_WITH_NETS */
168
169 #endif /* _IP_SET_HASH_GEN_H */
170
171 /* Family dependent templates */
172
173 #undef ahash_data
174 #undef mtype_data_equal
175 #undef mtype_do_data_match
176 #undef mtype_data_set_flags
177 #undef mtype_data_reset_flags
178 #undef mtype_data_netmask
179 #undef mtype_data_list
180 #undef mtype_data_next
181 #undef mtype_elem
182
183 #undef mtype_ahash_destroy
184 #undef mtype_ext_cleanup
185 #undef mtype_add_cidr
186 #undef mtype_del_cidr
187 #undef mtype_ahash_memsize
188 #undef mtype_flush
189 #undef mtype_destroy
190 #undef mtype_gc_init
191 #undef mtype_same_set
192 #undef mtype_kadt
193 #undef mtype_uadt
194 #undef mtype
195
196 #undef mtype_add
197 #undef mtype_del
198 #undef mtype_test_cidrs
199 #undef mtype_test
200 #undef mtype_expire
201 #undef mtype_resize
202 #undef mtype_head
203 #undef mtype_list
204 #undef mtype_gc
205 #undef mtype_gc_init
206 #undef mtype_variant
207 #undef mtype_data_match
208
209 #undef HKEY
210
211 #define mtype_data_equal        IPSET_TOKEN(MTYPE, _data_equal)
212 #ifdef IP_SET_HASH_WITH_NETS
213 #define mtype_do_data_match     IPSET_TOKEN(MTYPE, _do_data_match)
214 #else
215 #define mtype_do_data_match(d)  1
216 #endif
217 #define mtype_data_set_flags    IPSET_TOKEN(MTYPE, _data_set_flags)
218 #define mtype_data_reset_elem   IPSET_TOKEN(MTYPE, _data_reset_elem)
219 #define mtype_data_reset_flags  IPSET_TOKEN(MTYPE, _data_reset_flags)
220 #define mtype_data_netmask      IPSET_TOKEN(MTYPE, _data_netmask)
221 #define mtype_data_list         IPSET_TOKEN(MTYPE, _data_list)
222 #define mtype_data_next         IPSET_TOKEN(MTYPE, _data_next)
223 #define mtype_elem              IPSET_TOKEN(MTYPE, _elem)
224 #define mtype_ahash_destroy     IPSET_TOKEN(MTYPE, _ahash_destroy)
225 #define mtype_ext_cleanup       IPSET_TOKEN(MTYPE, _ext_cleanup)
226 #define mtype_add_cidr          IPSET_TOKEN(MTYPE, _add_cidr)
227 #define mtype_del_cidr          IPSET_TOKEN(MTYPE, _del_cidr)
228 #define mtype_ahash_memsize     IPSET_TOKEN(MTYPE, _ahash_memsize)
229 #define mtype_flush             IPSET_TOKEN(MTYPE, _flush)
230 #define mtype_destroy           IPSET_TOKEN(MTYPE, _destroy)
231 #define mtype_gc_init           IPSET_TOKEN(MTYPE, _gc_init)
232 #define mtype_same_set          IPSET_TOKEN(MTYPE, _same_set)
233 #define mtype_kadt              IPSET_TOKEN(MTYPE, _kadt)
234 #define mtype_uadt              IPSET_TOKEN(MTYPE, _uadt)
235 #define mtype                   MTYPE
236
237 #define mtype_elem              IPSET_TOKEN(MTYPE, _elem)
238 #define mtype_add               IPSET_TOKEN(MTYPE, _add)
239 #define mtype_del               IPSET_TOKEN(MTYPE, _del)
240 #define mtype_test_cidrs        IPSET_TOKEN(MTYPE, _test_cidrs)
241 #define mtype_test              IPSET_TOKEN(MTYPE, _test)
242 #define mtype_expire            IPSET_TOKEN(MTYPE, _expire)
243 #define mtype_resize            IPSET_TOKEN(MTYPE, _resize)
244 #define mtype_head              IPSET_TOKEN(MTYPE, _head)
245 #define mtype_list              IPSET_TOKEN(MTYPE, _list)
246 #define mtype_gc                IPSET_TOKEN(MTYPE, _gc)
247 #define mtype_variant           IPSET_TOKEN(MTYPE, _variant)
248 #define mtype_data_match        IPSET_TOKEN(MTYPE, _data_match)
249
250 #ifndef HKEY_DATALEN
251 #define HKEY_DATALEN            sizeof(struct mtype_elem)
252 #endif
253
254 #define HKEY(data, initval, htable_bits)                        \
255 (jhash2((u32 *)(data), HKEY_DATALEN/sizeof(u32), initval)       \
256         & jhash_mask(htable_bits))
257
258 #ifndef htype
259 #define htype                   HTYPE
260
261 /* The generic hash structure */
262 struct htype {
263         struct htable __rcu *table; /* the hash table */
264         u32 maxelem;            /* max elements in the hash */
265         u32 elements;           /* current element (vs timeout) */
266         u32 initval;            /* random jhash init value */
267         struct timer_list gc;   /* garbage collection when timeout enabled */
268         struct mtype_elem next; /* temporary storage for uadd */
269 #ifdef IP_SET_HASH_WITH_MULTI
270         u8 ahash_max;           /* max elements in an array block */
271 #endif
272 #ifdef IP_SET_HASH_WITH_NETMASK
273         u8 netmask;             /* netmask value for subnets to store */
274 #endif
275 #ifdef IP_SET_HASH_WITH_RBTREE
276         struct rb_root rbtree;
277 #endif
278 #ifdef IP_SET_HASH_WITH_NETS
279         struct net_prefixes nets[0]; /* book-keeping of prefixes */
280 #endif
281 };
282 #endif
283
284 #ifdef IP_SET_HASH_WITH_NETS
285 /* Network cidr size book keeping when the hash stores different
286  * sized networks */
287 static void
288 mtype_add_cidr(struct htype *h, u8 cidr, u8 nets_length, u8 n)
289 {
290         int i, j;
291
292         /* Add in increasing prefix order, so larger cidr first */
293         for (i = 0, j = -1; i < nets_length && h->nets[i].nets[n]; i++) {
294                 if (j != -1)
295                         continue;
296                 else if (h->nets[i].cidr[n] < cidr)
297                         j = i;
298                 else if (h->nets[i].cidr[n] == cidr) {
299                         h->nets[i].nets[n]++;
300                         return;
301                 }
302         }
303         if (j != -1) {
304                 for (; i > j; i--) {
305                         h->nets[i].cidr[n] = h->nets[i - 1].cidr[n];
306                         h->nets[i].nets[n] = h->nets[i - 1].nets[n];
307                 }
308         }
309         h->nets[i].cidr[n] = cidr;
310         h->nets[i].nets[n] = 1;
311 }
312
313 static void
314 mtype_del_cidr(struct htype *h, u8 cidr, u8 nets_length, u8 n)
315 {
316         u8 i, j, net_end = nets_length - 1;
317
318         for (i = 0; i < nets_length; i++) {
319                 if (h->nets[i].cidr[n] != cidr)
320                         continue;
321                 if (h->nets[i].nets[n] > 1 || i == net_end ||
322                     h->nets[i + 1].nets[n] == 0) {
323                         h->nets[i].nets[n]--;
324                         return;
325                 }
326                 for (j = i; j < net_end && h->nets[j].nets[n]; j++) {
327                         h->nets[j].cidr[n] = h->nets[j + 1].cidr[n];
328                         h->nets[j].nets[n] = h->nets[j + 1].nets[n];
329                 }
330                 h->nets[j].nets[n] = 0;
331                 return;
332         }
333 }
334 #endif
335
336 /* Calculate the actual memory size of the set data */
337 static size_t
338 mtype_ahash_memsize(const struct htype *h, const struct htable *t,
339                     u8 nets_length, size_t dsize)
340 {
341         u32 i;
342         size_t memsize = sizeof(*h)
343                          + sizeof(*t)
344 #ifdef IP_SET_HASH_WITH_NETS
345                          + sizeof(struct net_prefixes) * nets_length
346 #endif
347                          + jhash_size(t->htable_bits) * sizeof(struct hbucket);
348
349         for (i = 0; i < jhash_size(t->htable_bits); i++)
350                 memsize += t->bucket[i].size * dsize;
351
352         return memsize;
353 }
354
355 /* Get the ith element from the array block n */
356 #define ahash_data(n, i, dsize) \
357         ((struct mtype_elem *)((n)->value + ((i) * (dsize))))
358
359 static void
360 mtype_ext_cleanup(struct ip_set *set, struct hbucket *n)
361 {
362         int i;
363
364         for (i = 0; i < n->pos; i++)
365                 ip_set_ext_destroy(set, ahash_data(n, i, set->dsize));
366 }
367
368 /* Flush a hash type of set: destroy all elements */
369 static void
370 mtype_flush(struct ip_set *set)
371 {
372         struct htype *h = set->data;
373         struct htable *t;
374         struct hbucket *n;
375         u32 i;
376
377         t = rcu_dereference_bh_nfnl(h->table);
378         for (i = 0; i < jhash_size(t->htable_bits); i++) {
379                 n = hbucket(t, i);
380                 if (n->size) {
381                         if (set->extensions & IPSET_EXT_DESTROY)
382                                 mtype_ext_cleanup(set, n);
383                         n->size = n->pos = 0;
384                         /* FIXME: use slab cache */
385                         kfree(n->value);
386                 }
387         }
388 #ifdef IP_SET_HASH_WITH_NETS
389         memset(h->nets, 0, sizeof(struct net_prefixes) * NLEN(set->family));
390 #endif
391         h->elements = 0;
392 }
393
394 /* Destroy the hashtable part of the set */
395 static void
396 mtype_ahash_destroy(struct ip_set *set, struct htable *t, bool ext_destroy)
397 {
398         struct hbucket *n;
399         u32 i;
400
401         for (i = 0; i < jhash_size(t->htable_bits); i++) {
402                 n = hbucket(t, i);
403                 if (n->size) {
404                         if (set->extensions & IPSET_EXT_DESTROY && ext_destroy)
405                                 mtype_ext_cleanup(set, n);
406                         /* FIXME: use slab cache */
407                         kfree(n->value);
408                 }
409         }
410
411         ip_set_free(t);
412 }
413
414 /* Destroy a hash type of set */
415 static void
416 mtype_destroy(struct ip_set *set)
417 {
418         struct htype *h = set->data;
419
420         if (set->extensions & IPSET_EXT_TIMEOUT)
421                 del_timer_sync(&h->gc);
422
423         mtype_ahash_destroy(set, rcu_dereference_bh_nfnl(h->table), true);
424 #ifdef IP_SET_HASH_WITH_RBTREE
425         rbtree_destroy(&h->rbtree);
426 #endif
427         kfree(h);
428
429         set->data = NULL;
430 }
431
432 static void
433 mtype_gc_init(struct ip_set *set, void (*gc)(unsigned long ul_set))
434 {
435         struct htype *h = set->data;
436
437         init_timer(&h->gc);
438         h->gc.data = (unsigned long) set;
439         h->gc.function = gc;
440         h->gc.expires = jiffies + IPSET_GC_PERIOD(set->timeout) * HZ;
441         add_timer(&h->gc);
442         pr_debug("gc initialized, run in every %u\n",
443                  IPSET_GC_PERIOD(set->timeout));
444 }
445
446 static bool
447 mtype_same_set(const struct ip_set *a, const struct ip_set *b)
448 {
449         const struct htype *x = a->data;
450         const struct htype *y = b->data;
451
452         /* Resizing changes htable_bits, so we ignore it */
453         return x->maxelem == y->maxelem &&
454                a->timeout == b->timeout &&
455 #ifdef IP_SET_HASH_WITH_NETMASK
456                x->netmask == y->netmask &&
457 #endif
458                a->extensions == b->extensions;
459 }
460
461 /* Delete expired elements from the hashtable */
462 static void
463 mtype_expire(struct ip_set *set, struct htype *h, u8 nets_length, size_t dsize)
464 {
465         struct htable *t;
466         struct hbucket *n;
467         struct mtype_elem *data;
468         u32 i;
469         int j;
470 #ifdef IP_SET_HASH_WITH_NETS
471         u8 k;
472 #endif
473
474         rcu_read_lock_bh();
475         t = rcu_dereference_bh(h->table);
476         for (i = 0; i < jhash_size(t->htable_bits); i++) {
477                 n = hbucket(t, i);
478                 for (j = 0; j < n->pos; j++) {
479                         data = ahash_data(n, j, dsize);
480                         if (ip_set_timeout_expired(ext_timeout(data, set))) {
481                                 pr_debug("expired %u/%u\n", i, j);
482 #ifdef IP_SET_HASH_WITH_NETS
483                                 for (k = 0; k < IPSET_NET_COUNT; k++)
484                                         mtype_del_cidr(h, CIDR(data->cidr, k),
485                                                        nets_length, k);
486 #endif
487                                 ip_set_ext_destroy(set, data);
488                                 if (j != n->pos - 1)
489                                         /* Not last one */
490                                         memcpy(data,
491                                                ahash_data(n, n->pos - 1, dsize),
492                                                dsize);
493                                 n->pos--;
494                                 h->elements--;
495                         }
496                 }
497                 if (n->pos + AHASH_INIT_SIZE < n->size) {
498                         void *tmp = kzalloc((n->size - AHASH_INIT_SIZE)
499                                             * dsize,
500                                             GFP_ATOMIC);
501                         if (!tmp)
502                                 /* Still try to delete expired elements */
503                                 continue;
504                         n->size -= AHASH_INIT_SIZE;
505                         memcpy(tmp, n->value, n->size * dsize);
506                         kfree(n->value);
507                         n->value = tmp;
508                 }
509         }
510         rcu_read_unlock_bh();
511 }
512
513 static void
514 mtype_gc(unsigned long ul_set)
515 {
516         struct ip_set *set = (struct ip_set *) ul_set;
517         struct htype *h = set->data;
518
519         pr_debug("called\n");
520         write_lock_bh(&set->lock);
521         mtype_expire(set, h, NLEN(set->family), set->dsize);
522         write_unlock_bh(&set->lock);
523
524         h->gc.expires = jiffies + IPSET_GC_PERIOD(set->timeout) * HZ;
525         add_timer(&h->gc);
526 }
527
528 /* Resize a hash: create a new hash table with doubling the hashsize
529  * and inserting the elements to it. Repeat until we succeed or
530  * fail due to memory pressures. */
531 static int
532 mtype_resize(struct ip_set *set, bool retried)
533 {
534         struct htype *h = set->data;
535         struct htable *t, *orig = rcu_dereference_bh_nfnl(h->table);
536         u8 htable_bits = orig->htable_bits;
537 #ifdef IP_SET_HASH_WITH_NETS
538         u8 flags;
539 #endif
540         struct mtype_elem *data;
541         struct mtype_elem *d;
542         struct hbucket *n, *m;
543         u32 i, j;
544         int ret;
545
546         /* Try to cleanup once */
547         if (SET_WITH_TIMEOUT(set) && !retried) {
548                 i = h->elements;
549                 write_lock_bh(&set->lock);
550                 mtype_expire(set, set->data, NLEN(set->family), set->dsize);
551                 write_unlock_bh(&set->lock);
552                 if (h->elements < i)
553                         return 0;
554         }
555
556 retry:
557         ret = 0;
558         htable_bits++;
559         pr_debug("attempt to resize set %s from %u to %u, t %p\n",
560                  set->name, orig->htable_bits, htable_bits, orig);
561         if (!htable_bits) {
562                 /* In case we have plenty of memory :-) */
563                 pr_warning("Cannot increase the hashsize of set %s further\n",
564                            set->name);
565                 return -IPSET_ERR_HASH_FULL;
566         }
567         t = ip_set_alloc(sizeof(*t)
568                          + jhash_size(htable_bits) * sizeof(struct hbucket));
569         if (!t)
570                 return -ENOMEM;
571         t->htable_bits = htable_bits;
572
573         read_lock_bh(&set->lock);
574         for (i = 0; i < jhash_size(orig->htable_bits); i++) {
575                 n = hbucket(orig, i);
576                 for (j = 0; j < n->pos; j++) {
577                         data = ahash_data(n, j, set->dsize);
578 #ifdef IP_SET_HASH_WITH_NETS
579                         flags = 0;
580                         mtype_data_reset_flags(data, &flags);
581 #endif
582                         m = hbucket(t, HKEY(data, h->initval, htable_bits));
583                         ret = hbucket_elem_add(m, AHASH_MAX(h), set->dsize);
584                         if (ret < 0) {
585 #ifdef IP_SET_HASH_WITH_NETS
586                                 mtype_data_reset_flags(data, &flags);
587 #endif
588                                 read_unlock_bh(&set->lock);
589                                 mtype_ahash_destroy(set, t, false);
590                                 if (ret == -EAGAIN)
591                                         goto retry;
592                                 return ret;
593                         }
594                         d = ahash_data(m, m->pos++, set->dsize);
595                         memcpy(d, data, set->dsize);
596 #ifdef IP_SET_HASH_WITH_NETS
597                         mtype_data_reset_flags(d, &flags);
598 #endif
599                 }
600         }
601
602         rcu_assign_pointer(h->table, t);
603         read_unlock_bh(&set->lock);
604
605         /* Give time to other readers of the set */
606         synchronize_rcu_bh();
607
608         pr_debug("set %s resized from %u (%p) to %u (%p)\n", set->name,
609                  orig->htable_bits, orig, t->htable_bits, t);
610         mtype_ahash_destroy(set, orig, false);
611
612         return 0;
613 }
614
615 /* Add an element to a hash and update the internal counters when succeeded,
616  * otherwise report the proper error code. */
617 static int
618 mtype_add(struct ip_set *set, void *value, const struct ip_set_ext *ext,
619           struct ip_set_ext *mext, u32 flags)
620 {
621         struct htype *h = set->data;
622         struct htable *t;
623         const struct mtype_elem *d = value;
624         struct mtype_elem *data;
625         struct hbucket *n;
626         int i, ret = 0;
627         int j = AHASH_MAX(h) + 1;
628         bool flag_exist = flags & IPSET_FLAG_EXIST;
629         u32 key, multi = 0;
630
631         if (SET_WITH_TIMEOUT(set) && h->elements >= h->maxelem)
632                 /* FIXME: when set is full, we slow down here */
633                 mtype_expire(set, h, NLEN(set->family), set->dsize);
634
635         if (h->elements >= h->maxelem) {
636                 if (net_ratelimit())
637                         pr_warning("Set %s is full, maxelem %u reached\n",
638                                    set->name, h->maxelem);
639                 return -IPSET_ERR_HASH_FULL;
640         }
641
642         rcu_read_lock_bh();
643         t = rcu_dereference_bh(h->table);
644         key = HKEY(value, h->initval, t->htable_bits);
645         n = hbucket(t, key);
646         for (i = 0; i < n->pos; i++) {
647                 data = ahash_data(n, i, set->dsize);
648                 if (mtype_data_equal(data, d, &multi)) {
649                         if (flag_exist ||
650                             (SET_WITH_TIMEOUT(set) &&
651                              ip_set_timeout_expired(ext_timeout(data, set)))) {
652                                 /* Just the extensions could be overwritten */
653                                 j = i;
654                                 goto reuse_slot;
655                         } else {
656                                 ret = -IPSET_ERR_EXIST;
657                                 goto out;
658                         }
659                 }
660                 /* Reuse first timed out entry */
661                 if (SET_WITH_TIMEOUT(set) &&
662                     ip_set_timeout_expired(ext_timeout(data, set)) &&
663                     j != AHASH_MAX(h) + 1)
664                         j = i;
665         }
666 reuse_slot:
667         if (j != AHASH_MAX(h) + 1) {
668                 /* Fill out reused slot */
669                 data = ahash_data(n, j, set->dsize);
670 #ifdef IP_SET_HASH_WITH_NETS
671                 for (i = 0; i < IPSET_NET_COUNT; i++) {
672                         mtype_del_cidr(h, CIDR(data->cidr, i),
673                                        NLEN(set->family), i);
674                         mtype_add_cidr(h, CIDR(d->cidr, i),
675                                        NLEN(set->family), i);
676                 }
677 #endif
678                 ip_set_ext_destroy(set, data);
679         } else {
680                 /* Use/create a new slot */
681                 TUNE_AHASH_MAX(h, multi);
682                 ret = hbucket_elem_add(n, AHASH_MAX(h), set->dsize);
683                 if (ret != 0) {
684                         if (ret == -EAGAIN)
685                                 mtype_data_next(&h->next, d);
686                         goto out;
687                 }
688                 data = ahash_data(n, n->pos++, set->dsize);
689 #ifdef IP_SET_HASH_WITH_NETS
690                 for (i = 0; i < IPSET_NET_COUNT; i++)
691                         mtype_add_cidr(h, CIDR(d->cidr, i), NLEN(set->family),
692                                        i);
693 #endif
694                 h->elements++;
695         }
696         memcpy(data, d, sizeof(struct mtype_elem));
697 #ifdef IP_SET_HASH_WITH_NETS
698         mtype_data_set_flags(data, flags);
699 #endif
700         if (SET_WITH_TIMEOUT(set))
701                 ip_set_timeout_set(ext_timeout(data, set), ext->timeout);
702         if (SET_WITH_COUNTER(set))
703                 ip_set_init_counter(ext_counter(data, set), ext);
704         if (SET_WITH_COMMENT(set))
705                 ip_set_init_comment(ext_comment(data, set), ext);
706
707 out:
708         rcu_read_unlock_bh();
709         return ret;
710 }
711
712 /* Delete an element from the hash: swap it with the last element
713  * and free up space if possible.
714  */
715 static int
716 mtype_del(struct ip_set *set, void *value, const struct ip_set_ext *ext,
717           struct ip_set_ext *mext, u32 flags)
718 {
719         struct htype *h = set->data;
720         struct htable *t;
721         const struct mtype_elem *d = value;
722         struct mtype_elem *data;
723         struct hbucket *n;
724         int i, ret = -IPSET_ERR_EXIST;
725 #ifdef IP_SET_HASH_WITH_NETS
726         u8 j;
727 #endif
728         u32 key, multi = 0;
729
730         rcu_read_lock_bh();
731         t = rcu_dereference_bh(h->table);
732         key = HKEY(value, h->initval, t->htable_bits);
733         n = hbucket(t, key);
734         for (i = 0; i < n->pos; i++) {
735                 data = ahash_data(n, i, set->dsize);
736                 if (!mtype_data_equal(data, d, &multi))
737                         continue;
738                 if (SET_WITH_TIMEOUT(set) &&
739                     ip_set_timeout_expired(ext_timeout(data, set)))
740                         goto out;
741                 if (i != n->pos - 1)
742                         /* Not last one */
743                         memcpy(data, ahash_data(n, n->pos - 1, set->dsize),
744                                set->dsize);
745
746                 n->pos--;
747                 h->elements--;
748 #ifdef IP_SET_HASH_WITH_NETS
749                 for (j = 0; j < IPSET_NET_COUNT; j++)
750                         mtype_del_cidr(h, CIDR(d->cidr, j), NLEN(set->family),
751                                        j);
752 #endif
753                 ip_set_ext_destroy(set, data);
754                 if (n->pos + AHASH_INIT_SIZE < n->size) {
755                         void *tmp = kzalloc((n->size - AHASH_INIT_SIZE)
756                                             * set->dsize,
757                                             GFP_ATOMIC);
758                         if (!tmp) {
759                                 ret = 0;
760                                 goto out;
761                         }
762                         n->size -= AHASH_INIT_SIZE;
763                         memcpy(tmp, n->value, n->size * set->dsize);
764                         kfree(n->value);
765                         n->value = tmp;
766                 }
767                 ret = 0;
768                 goto out;
769         }
770
771 out:
772         rcu_read_unlock_bh();
773         return ret;
774 }
775
776 static inline int
777 mtype_data_match(struct mtype_elem *data, const struct ip_set_ext *ext,
778                  struct ip_set_ext *mext, struct ip_set *set, u32 flags)
779 {
780         if (SET_WITH_COUNTER(set))
781                 ip_set_update_counter(ext_counter(data, set),
782                                       ext, mext, flags);
783         return mtype_do_data_match(data);
784 }
785
786 #ifdef IP_SET_HASH_WITH_NETS
787 /* Special test function which takes into account the different network
788  * sizes added to the set */
789 static int
790 mtype_test_cidrs(struct ip_set *set, struct mtype_elem *d,
791                  const struct ip_set_ext *ext,
792                  struct ip_set_ext *mext, u32 flags)
793 {
794         struct htype *h = set->data;
795         struct htable *t = rcu_dereference_bh(h->table);
796         struct hbucket *n;
797         struct mtype_elem *data;
798 #if IPSET_NET_COUNT == 2
799         struct mtype_elem orig = *d;
800         int i, j = 0, k;
801 #else
802         int i, j = 0;
803 #endif
804         u32 key, multi = 0;
805         u8 nets_length = NLEN(set->family);
806
807         pr_debug("test by nets\n");
808         for (; j < nets_length && h->nets[j].nets[0] && !multi; j++) {
809 #if IPSET_NET_COUNT == 2
810                 mtype_data_reset_elem(d, &orig);
811                 mtype_data_netmask(d, h->nets[j].cidr[0], false);
812                 for (k = 0; k < nets_length && h->nets[k].nets[1] && !multi;
813                      k++) {
814                         mtype_data_netmask(d, h->nets[k].cidr[1], true);
815 #else
816                 mtype_data_netmask(d, h->nets[j].cidr[0]);
817 #endif
818                 key = HKEY(d, h->initval, t->htable_bits);
819                 n = hbucket(t, key);
820                 for (i = 0; i < n->pos; i++) {
821                         data = ahash_data(n, i, set->dsize);
822                         if (!mtype_data_equal(data, d, &multi))
823                                 continue;
824                         if (SET_WITH_TIMEOUT(set)) {
825                                 if (!ip_set_timeout_expired(
826                                                 ext_timeout(data, set)))
827                                         return mtype_data_match(data, ext,
828                                                                 mext, set,
829                                                                 flags);
830 #ifdef IP_SET_HASH_WITH_MULTI
831                                 multi = 0;
832 #endif
833                         } else
834                                 return mtype_data_match(data, ext,
835                                                         mext, set, flags);
836                 }
837 #if IPSET_NET_COUNT == 2
838                 }
839 #endif
840         }
841         return 0;
842 }
843 #endif
844
845 /* Test whether the element is added to the set */
846 static int
847 mtype_test(struct ip_set *set, void *value, const struct ip_set_ext *ext,
848            struct ip_set_ext *mext, u32 flags)
849 {
850         struct htype *h = set->data;
851         struct htable *t;
852         struct mtype_elem *d = value;
853         struct hbucket *n;
854         struct mtype_elem *data;
855         int i, ret = 0;
856         u32 key, multi = 0;
857
858         rcu_read_lock_bh();
859         t = rcu_dereference_bh(h->table);
860 #ifdef IP_SET_HASH_WITH_NETS
861         /* If we test an IP address and not a network address,
862          * try all possible network sizes */
863         for (i = 0; i < IPSET_NET_COUNT; i++)
864                 if (CIDR(d->cidr, i) != SET_HOST_MASK(set->family))
865                         break;
866         if (i == IPSET_NET_COUNT) {
867                 ret = mtype_test_cidrs(set, d, ext, mext, flags);
868                 goto out;
869         }
870 #endif
871
872         key = HKEY(d, h->initval, t->htable_bits);
873         n = hbucket(t, key);
874         for (i = 0; i < n->pos; i++) {
875                 data = ahash_data(n, i, set->dsize);
876                 if (mtype_data_equal(data, d, &multi) &&
877                     !(SET_WITH_TIMEOUT(set) &&
878                       ip_set_timeout_expired(ext_timeout(data, set)))) {
879                         ret = mtype_data_match(data, ext, mext, set, flags);
880                         goto out;
881                 }
882         }
883 out:
884         rcu_read_unlock_bh();
885         return ret;
886 }
887
888 /* Reply a HEADER request: fill out the header part of the set */
889 static int
890 mtype_head(struct ip_set *set, struct sk_buff *skb)
891 {
892         const struct htype *h = set->data;
893         const struct htable *t;
894         struct nlattr *nested;
895         size_t memsize;
896
897         t = rcu_dereference_bh_nfnl(h->table);
898         memsize = mtype_ahash_memsize(h, t, NLEN(set->family), set->dsize);
899
900         nested = ipset_nest_start(skb, IPSET_ATTR_DATA);
901         if (!nested)
902                 goto nla_put_failure;
903         if (nla_put_net32(skb, IPSET_ATTR_HASHSIZE,
904                           htonl(jhash_size(t->htable_bits))) ||
905             nla_put_net32(skb, IPSET_ATTR_MAXELEM, htonl(h->maxelem)))
906                 goto nla_put_failure;
907 #ifdef IP_SET_HASH_WITH_NETMASK
908         if (h->netmask != HOST_MASK &&
909             nla_put_u8(skb, IPSET_ATTR_NETMASK, h->netmask))
910                 goto nla_put_failure;
911 #endif
912         if (nla_put_net32(skb, IPSET_ATTR_REFERENCES, htonl(set->ref - 1)) ||
913             nla_put_net32(skb, IPSET_ATTR_MEMSIZE, htonl(memsize)))
914                 goto nla_put_failure;
915         if (unlikely(ip_set_put_flags(skb, set)))
916                 goto nla_put_failure;
917         ipset_nest_end(skb, nested);
918
919         return 0;
920 nla_put_failure:
921         return -EMSGSIZE;
922 }
923
924 /* Reply a LIST/SAVE request: dump the elements of the specified set */
925 static int
926 mtype_list(const struct ip_set *set,
927            struct sk_buff *skb, struct netlink_callback *cb)
928 {
929         const struct htype *h = set->data;
930         const struct htable *t = rcu_dereference_bh_nfnl(h->table);
931         struct nlattr *atd, *nested;
932         const struct hbucket *n;
933         const struct mtype_elem *e;
934         u32 first = cb->args[2];
935         /* We assume that one hash bucket fills into one page */
936         void *incomplete;
937         int i;
938
939         atd = ipset_nest_start(skb, IPSET_ATTR_ADT);
940         if (!atd)
941                 return -EMSGSIZE;
942         pr_debug("list hash set %s\n", set->name);
943         for (; cb->args[2] < jhash_size(t->htable_bits); cb->args[2]++) {
944                 incomplete = skb_tail_pointer(skb);
945                 n = hbucket(t, cb->args[2]);
946                 pr_debug("cb->args[2]: %lu, t %p n %p\n", cb->args[2], t, n);
947                 for (i = 0; i < n->pos; i++) {
948                         e = ahash_data(n, i, set->dsize);
949                         if (SET_WITH_TIMEOUT(set) &&
950                             ip_set_timeout_expired(ext_timeout(e, set)))
951                                 continue;
952                         pr_debug("list hash %lu hbucket %p i %u, data %p\n",
953                                  cb->args[2], n, i, e);
954                         nested = ipset_nest_start(skb, IPSET_ATTR_DATA);
955                         if (!nested) {
956                                 if (cb->args[2] == first) {
957                                         nla_nest_cancel(skb, atd);
958                                         return -EMSGSIZE;
959                                 } else
960                                         goto nla_put_failure;
961                         }
962                         if (mtype_data_list(skb, e))
963                                 goto nla_put_failure;
964                         if (ip_set_put_extensions(skb, set, e, true))
965                                 goto nla_put_failure;
966                         ipset_nest_end(skb, nested);
967                 }
968         }
969         ipset_nest_end(skb, atd);
970         /* Set listing finished */
971         cb->args[2] = 0;
972
973         return 0;
974
975 nla_put_failure:
976         nlmsg_trim(skb, incomplete);
977         if (unlikely(first == cb->args[2])) {
978                 pr_warning("Can't list set %s: one bucket does not fit into "
979                            "a message. Please report it!\n", set->name);
980                 cb->args[2] = 0;
981                 return -EMSGSIZE;
982         }
983         ipset_nest_end(skb, atd);
984         return 0;
985 }
986
987 static int
988 IPSET_TOKEN(MTYPE, _kadt)(struct ip_set *set, const struct sk_buff *skb,
989             const struct xt_action_param *par,
990             enum ipset_adt adt, struct ip_set_adt_opt *opt);
991
992 static int
993 IPSET_TOKEN(MTYPE, _uadt)(struct ip_set *set, struct nlattr *tb[],
994             enum ipset_adt adt, u32 *lineno, u32 flags, bool retried);
995
996 static const struct ip_set_type_variant mtype_variant = {
997         .kadt   = mtype_kadt,
998         .uadt   = mtype_uadt,
999         .adt    = {
1000                 [IPSET_ADD] = mtype_add,
1001                 [IPSET_DEL] = mtype_del,
1002                 [IPSET_TEST] = mtype_test,
1003         },
1004         .destroy = mtype_destroy,
1005         .flush  = mtype_flush,
1006         .head   = mtype_head,
1007         .list   = mtype_list,
1008         .resize = mtype_resize,
1009         .same_set = mtype_same_set,
1010 };
1011
1012 #ifdef IP_SET_EMIT_CREATE
1013 static int
1014 IPSET_TOKEN(HTYPE, _create)(struct net *net, struct ip_set *set,
1015                             struct nlattr *tb[], u32 flags)
1016 {
1017         u32 hashsize = IPSET_DEFAULT_HASHSIZE, maxelem = IPSET_DEFAULT_MAXELEM;
1018         u8 hbits;
1019 #ifdef IP_SET_HASH_WITH_NETMASK
1020         u8 netmask;
1021 #endif
1022         size_t hsize;
1023         struct HTYPE *h;
1024         struct htable *t;
1025
1026         if (!(set->family == NFPROTO_IPV4 || set->family == NFPROTO_IPV6))
1027                 return -IPSET_ERR_INVALID_FAMILY;
1028 #ifdef IP_SET_HASH_WITH_NETMASK
1029         netmask = set->family == NFPROTO_IPV4 ? 32 : 128;
1030         pr_debug("Create set %s with family %s\n",
1031                  set->name, set->family == NFPROTO_IPV4 ? "inet" : "inet6");
1032 #endif
1033
1034         if (unlikely(!ip_set_optattr_netorder(tb, IPSET_ATTR_HASHSIZE) ||
1035                      !ip_set_optattr_netorder(tb, IPSET_ATTR_MAXELEM) ||
1036                      !ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT) ||
1037                      !ip_set_optattr_netorder(tb, IPSET_ATTR_CADT_FLAGS)))
1038                 return -IPSET_ERR_PROTOCOL;
1039
1040         if (tb[IPSET_ATTR_HASHSIZE]) {
1041                 hashsize = ip_set_get_h32(tb[IPSET_ATTR_HASHSIZE]);
1042                 if (hashsize < IPSET_MIMINAL_HASHSIZE)
1043                         hashsize = IPSET_MIMINAL_HASHSIZE;
1044         }
1045
1046         if (tb[IPSET_ATTR_MAXELEM])
1047                 maxelem = ip_set_get_h32(tb[IPSET_ATTR_MAXELEM]);
1048
1049 #ifdef IP_SET_HASH_WITH_NETMASK
1050         if (tb[IPSET_ATTR_NETMASK]) {
1051                 netmask = nla_get_u8(tb[IPSET_ATTR_NETMASK]);
1052
1053                 if ((set->family == NFPROTO_IPV4 && netmask > 32) ||
1054                     (set->family == NFPROTO_IPV6 && netmask > 128) ||
1055                     netmask == 0)
1056                         return -IPSET_ERR_INVALID_NETMASK;
1057         }
1058 #endif
1059
1060         hsize = sizeof(*h);
1061 #ifdef IP_SET_HASH_WITH_NETS
1062         hsize += sizeof(struct net_prefixes) *
1063                 (set->family == NFPROTO_IPV4 ? 32 : 128);
1064 #endif
1065         h = kzalloc(hsize, GFP_KERNEL);
1066         if (!h)
1067                 return -ENOMEM;
1068
1069         h->maxelem = maxelem;
1070 #ifdef IP_SET_HASH_WITH_NETMASK
1071         h->netmask = netmask;
1072 #endif
1073         get_random_bytes(&h->initval, sizeof(h->initval));
1074         set->timeout = IPSET_NO_TIMEOUT;
1075
1076         hbits = htable_bits(hashsize);
1077         hsize = htable_size(hbits);
1078         if (hsize == 0) {
1079                 kfree(h);
1080                 return -ENOMEM;
1081         }
1082         t = ip_set_alloc(hsize);
1083         if (!t) {
1084                 kfree(h);
1085                 return -ENOMEM;
1086         }
1087         t->htable_bits = hbits;
1088         rcu_assign_pointer(h->table, t);
1089
1090         set->data = h;
1091         if (set->family == NFPROTO_IPV4) {
1092                 set->variant = &IPSET_TOKEN(HTYPE, 4_variant);
1093                 set->dsize = ip_set_elem_len(set, tb,
1094                                 sizeof(struct IPSET_TOKEN(HTYPE, 4_elem)));
1095         } else {
1096                 set->variant = &IPSET_TOKEN(HTYPE, 6_variant);
1097                 set->dsize = ip_set_elem_len(set, tb,
1098                                 sizeof(struct IPSET_TOKEN(HTYPE, 6_elem)));
1099         }
1100         if (tb[IPSET_ATTR_TIMEOUT]) {
1101                 set->timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
1102                 if (set->family == NFPROTO_IPV4)
1103                         IPSET_TOKEN(HTYPE, 4_gc_init)(set,
1104                                 IPSET_TOKEN(HTYPE, 4_gc));
1105                 else
1106                         IPSET_TOKEN(HTYPE, 6_gc_init)(set,
1107                                 IPSET_TOKEN(HTYPE, 6_gc));
1108         }
1109
1110         pr_debug("create %s hashsize %u (%u) maxelem %u: %p(%p)\n",
1111                  set->name, jhash_size(t->htable_bits),
1112                  t->htable_bits, h->maxelem, set->data, t);
1113
1114         return 0;
1115 }
1116 #endif /* IP_SET_EMIT_CREATE */