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