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