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