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