1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /* Copyright (C) 2013 Jozsef Kadlecsik <kadlec@netfilter.org> */
3 
4 #ifndef _IP_SET_HASH_GEN_H
5 #define _IP_SET_HASH_GEN_H
6 
7 #include <linux/rcupdate.h>
8 #include <linux/jhash.h>
9 #include <linux/types.h>
10 #include <linux/netfilter/nfnetlink.h>
11 #include <linux/netfilter/ipset/ip_set.h>
12 
13 #define __ipset_dereference(p)		\
14 	rcu_dereference_protected(p, 1)
15 #define ipset_dereference_nfnl(p)	\
16 	rcu_dereference_protected(p,	\
17 		lockdep_nfnl_is_held(NFNL_SUBSYS_IPSET))
18 #define ipset_dereference_set(p, set) 	\
19 	rcu_dereference_protected(p,	\
20 		lockdep_nfnl_is_held(NFNL_SUBSYS_IPSET) || \
21 		lockdep_is_held(&(set)->lock))
22 #define ipset_dereference_bh_nfnl(p)	\
23 	rcu_dereference_bh_check(p, 	\
24 		lockdep_nfnl_is_held(NFNL_SUBSYS_IPSET))
25 
26 /* Hashing which uses arrays to resolve clashing. The hash table is resized
27  * (doubled) when searching becomes too long.
28  * Internally jhash is used with the assumption that the size of the
29  * stored data is a multiple of sizeof(u32).
30  *
31  * Readers and resizing
32  *
33  * Resizing can be triggered by userspace command only, and those
34  * are serialized by the nfnl mutex. During resizing the set is
35  * read-locked, so the only possible concurrent operations are
36  * the kernel side readers. Those must be protected by proper RCU locking.
37  */
38 
39 /* Number of elements to store in an initial array block */
40 #define AHASH_INIT_SIZE			2
41 /* Max number of elements to store in an array block */
42 #define AHASH_MAX_SIZE			(6 * AHASH_INIT_SIZE)
43 /* Max muber of elements in the array block when tuned */
44 #define AHASH_MAX_TUNED			64
45 #define AHASH_MAX(h)			((h)->bucketsize)
46 
47 /* A hash bucket */
48 struct hbucket {
49 	struct rcu_head rcu;	/* for call_rcu */
50 	/* Which positions are used in the array */
51 	DECLARE_BITMAP(used, AHASH_MAX_TUNED);
52 	u8 size;		/* size of the array */
53 	u8 pos;			/* position of the first free entry */
54 	unsigned char value[]	/* the array of the values */
55 		__aligned(__alignof__(u64));
56 };
57 
58 /* Region size for locking == 2^HTABLE_REGION_BITS */
59 #define HTABLE_REGION_BITS	10
60 #define ahash_numof_locks(htable_bits)		\
61 	((htable_bits) < HTABLE_REGION_BITS ? 1	\
62 		: jhash_size((htable_bits) - HTABLE_REGION_BITS))
63 #define ahash_sizeof_regions(htable_bits)		\
64 	(ahash_numof_locks(htable_bits) * sizeof(struct ip_set_region))
65 #define ahash_region(n, htable_bits)		\
66 	((n) % ahash_numof_locks(htable_bits))
67 #define ahash_bucket_start(h,  htable_bits)	\
68 	((htable_bits) < HTABLE_REGION_BITS ? 0	\
69 		: (h) * jhash_size(HTABLE_REGION_BITS))
70 #define ahash_bucket_end(h,  htable_bits)	\
71 	((htable_bits) < HTABLE_REGION_BITS ? jhash_size(htable_bits)	\
72 		: ((h) + 1) * jhash_size(HTABLE_REGION_BITS))
73 
74 struct htable_gc {
75 	struct delayed_work dwork;
76 	struct ip_set *set;	/* Set the gc belongs to */
77 	u32 region;		/* Last gc run position */
78 };
79 
80 /* The hash table: the table size stored here in order to make resizing easy */
81 struct htable {
82 	atomic_t ref;		/* References for resizing */
83 	atomic_t uref;		/* References for dumping and gc */
84 	u8 htable_bits;		/* size of hash table == 2^htable_bits */
85 	u32 maxelem;		/* Maxelem per region */
86 	struct ip_set_region *hregion;	/* Region locks and ext sizes */
87 	struct hbucket __rcu *bucket[]; /* hashtable buckets */
88 };
89 
90 #define hbucket(h, i)		((h)->bucket[i])
91 #define ext_size(n, dsize)	\
92 	(sizeof(struct hbucket) + (n) * (dsize))
93 
94 #ifndef IPSET_NET_COUNT
95 #define IPSET_NET_COUNT		1
96 #endif
97 
98 /* Book-keeping of the prefixes added to the set */
99 struct net_prefixes {
100 	u32 nets[IPSET_NET_COUNT]; /* number of elements for this cidr */
101 	u8 cidr[IPSET_NET_COUNT];  /* the cidr value */
102 };
103 
104 /* Compute the hash table size */
105 static size_t
htable_size(u8 hbits)106 htable_size(u8 hbits)
107 {
108 	size_t hsize;
109 
110 	/* We must fit both into u32 in jhash and INT_MAX in kvmalloc_node() */
111 	if (hbits > 31)
112 		return 0;
113 	hsize = jhash_size(hbits);
114 	if ((INT_MAX - sizeof(struct htable)) / sizeof(struct hbucket *)
115 	    < hsize)
116 		return 0;
117 
118 	return hsize * sizeof(struct hbucket *) + sizeof(struct htable);
119 }
120 
121 #ifdef IP_SET_HASH_WITH_NETS
122 #if IPSET_NET_COUNT > 1
123 #define __CIDR(cidr, i)		(cidr[i])
124 #else
125 #define __CIDR(cidr, i)		(cidr)
126 #endif
127 
128 /* cidr + 1 is stored in net_prefixes to support /0 */
129 #define NCIDR_PUT(cidr)		((cidr) + 1)
130 #define NCIDR_GET(cidr)		((cidr) - 1)
131 
132 #ifdef IP_SET_HASH_WITH_NETS_PACKED
133 /* When cidr is packed with nomatch, cidr - 1 is stored in the data entry */
134 #define DCIDR_PUT(cidr)		((cidr) - 1)
135 #define DCIDR_GET(cidr, i)	(__CIDR(cidr, i) + 1)
136 #else
137 #define DCIDR_PUT(cidr)		(cidr)
138 #define DCIDR_GET(cidr, i)	__CIDR(cidr, i)
139 #endif
140 
141 #define INIT_CIDR(cidr, host_mask)	\
142 	DCIDR_PUT(((cidr) ? NCIDR_GET(cidr) : host_mask))
143 
144 #ifdef IP_SET_HASH_WITH_NET0
145 /* cidr from 0 to HOST_MASK value and c = cidr + 1 */
146 #define NLEN			(HOST_MASK + 1)
147 #define CIDR_POS(c)		((c) - 1)
148 #else
149 /* cidr from 1 to HOST_MASK value and c = cidr + 1 */
150 #define NLEN			HOST_MASK
151 #define CIDR_POS(c)		((c) - 2)
152 #endif
153 
154 #else
155 #define NLEN			0
156 #endif /* IP_SET_HASH_WITH_NETS */
157 
158 #define SET_ELEM_EXPIRED(set, d)	\
159 	(SET_WITH_TIMEOUT(set) &&	\
160 	 ip_set_timeout_expired(ext_timeout(d, set)))
161 
162 #if defined(IP_SET_HASH_WITH_NETMASK) || defined(IP_SET_HASH_WITH_BITMASK)
163 static const union nf_inet_addr onesmask = {
164 	.all[0] = 0xffffffff,
165 	.all[1] = 0xffffffff,
166 	.all[2] = 0xffffffff,
167 	.all[3] = 0xffffffff
168 };
169 
170 static const union nf_inet_addr zeromask = {};
171 #endif
172 
173 #endif /* _IP_SET_HASH_GEN_H */
174 
175 #ifndef MTYPE
176 #error "MTYPE is not defined!"
177 #endif
178 
179 #ifndef HTYPE
180 #error "HTYPE is not defined!"
181 #endif
182 
183 #ifndef HOST_MASK
184 #error "HOST_MASK is not defined!"
185 #endif
186 
187 /* Family dependent templates */
188 
189 #undef ahash_data
190 #undef mtype_data_equal
191 #undef mtype_do_data_match
192 #undef mtype_data_set_flags
193 #undef mtype_data_reset_elem
194 #undef mtype_data_reset_flags
195 #undef mtype_data_netmask
196 #undef mtype_data_list
197 #undef mtype_data_next
198 #undef mtype_elem
199 
200 #undef mtype_ahash_destroy
201 #undef mtype_ext_cleanup
202 #undef mtype_add_cidr
203 #undef mtype_del_cidr
204 #undef mtype_ahash_memsize
205 #undef mtype_flush
206 #undef mtype_destroy
207 #undef mtype_same_set
208 #undef mtype_kadt
209 #undef mtype_uadt
210 
211 #undef mtype_add
212 #undef mtype_del
213 #undef mtype_test_cidrs
214 #undef mtype_test
215 #undef mtype_uref
216 #undef mtype_resize
217 #undef mtype_ext_size
218 #undef mtype_resize_ad
219 #undef mtype_head
220 #undef mtype_list
221 #undef mtype_gc_do
222 #undef mtype_gc
223 #undef mtype_gc_init
224 #undef mtype_cancel_gc
225 #undef mtype_variant
226 #undef mtype_data_match
227 
228 #undef htype
229 #undef HKEY
230 
231 #define mtype_data_equal	IPSET_TOKEN(MTYPE, _data_equal)
232 #ifdef IP_SET_HASH_WITH_NETS
233 #define mtype_do_data_match	IPSET_TOKEN(MTYPE, _do_data_match)
234 #else
235 #define mtype_do_data_match(d)	1
236 #endif
237 #define mtype_data_set_flags	IPSET_TOKEN(MTYPE, _data_set_flags)
238 #define mtype_data_reset_elem	IPSET_TOKEN(MTYPE, _data_reset_elem)
239 #define mtype_data_reset_flags	IPSET_TOKEN(MTYPE, _data_reset_flags)
240 #define mtype_data_netmask	IPSET_TOKEN(MTYPE, _data_netmask)
241 #define mtype_data_list		IPSET_TOKEN(MTYPE, _data_list)
242 #define mtype_data_next		IPSET_TOKEN(MTYPE, _data_next)
243 #define mtype_elem		IPSET_TOKEN(MTYPE, _elem)
244 
245 #define mtype_ahash_destroy	IPSET_TOKEN(MTYPE, _ahash_destroy)
246 #define mtype_ext_cleanup	IPSET_TOKEN(MTYPE, _ext_cleanup)
247 #define mtype_add_cidr		IPSET_TOKEN(MTYPE, _add_cidr)
248 #define mtype_del_cidr		IPSET_TOKEN(MTYPE, _del_cidr)
249 #define mtype_ahash_memsize	IPSET_TOKEN(MTYPE, _ahash_memsize)
250 #define mtype_flush		IPSET_TOKEN(MTYPE, _flush)
251 #define mtype_destroy		IPSET_TOKEN(MTYPE, _destroy)
252 #define mtype_same_set		IPSET_TOKEN(MTYPE, _same_set)
253 #define mtype_kadt		IPSET_TOKEN(MTYPE, _kadt)
254 #define mtype_uadt		IPSET_TOKEN(MTYPE, _uadt)
255 
256 #define mtype_add		IPSET_TOKEN(MTYPE, _add)
257 #define mtype_del		IPSET_TOKEN(MTYPE, _del)
258 #define mtype_test_cidrs	IPSET_TOKEN(MTYPE, _test_cidrs)
259 #define mtype_test		IPSET_TOKEN(MTYPE, _test)
260 #define mtype_uref		IPSET_TOKEN(MTYPE, _uref)
261 #define mtype_resize		IPSET_TOKEN(MTYPE, _resize)
262 #define mtype_ext_size		IPSET_TOKEN(MTYPE, _ext_size)
263 #define mtype_resize_ad		IPSET_TOKEN(MTYPE, _resize_ad)
264 #define mtype_head		IPSET_TOKEN(MTYPE, _head)
265 #define mtype_list		IPSET_TOKEN(MTYPE, _list)
266 #define mtype_gc_do		IPSET_TOKEN(MTYPE, _gc_do)
267 #define mtype_gc		IPSET_TOKEN(MTYPE, _gc)
268 #define mtype_gc_init		IPSET_TOKEN(MTYPE, _gc_init)
269 #define mtype_cancel_gc		IPSET_TOKEN(MTYPE, _cancel_gc)
270 #define mtype_variant		IPSET_TOKEN(MTYPE, _variant)
271 #define mtype_data_match	IPSET_TOKEN(MTYPE, _data_match)
272 
273 #ifndef HKEY_DATALEN
274 #define HKEY_DATALEN		sizeof(struct mtype_elem)
275 #endif
276 
277 #define htype			MTYPE
278 
279 #define HKEY(data, initval, htable_bits)			\
280 ({								\
281 	const u32 *__k = (const u32 *)data;			\
282 	u32 __l = HKEY_DATALEN / sizeof(u32);			\
283 								\
284 	BUILD_BUG_ON(HKEY_DATALEN % sizeof(u32) != 0);		\
285 								\
286 	jhash2(__k, __l, initval) & jhash_mask(htable_bits);	\
287 })
288 
289 /* The generic hash structure */
290 struct htype {
291 	struct htable __rcu *table; /* the hash table */
292 	struct htable_gc gc;	/* gc workqueue */
293 	u32 maxelem;		/* max elements in the hash */
294 	u32 initval;		/* random jhash init value */
295 #ifdef IP_SET_HASH_WITH_MARKMASK
296 	u32 markmask;		/* markmask value for mark mask to store */
297 #endif
298 	u8 bucketsize;		/* max elements in an array block */
299 #if defined(IP_SET_HASH_WITH_NETMASK) || defined(IP_SET_HASH_WITH_BITMASK)
300 	u8 netmask;		/* netmask value for subnets to store */
301 	union nf_inet_addr bitmask;	/* stores bitmask */
302 #endif
303 	struct list_head ad;	/* Resize add|del backlist */
304 	struct mtype_elem next; /* temporary storage for uadd */
305 #ifdef IP_SET_HASH_WITH_NETS
306 	struct net_prefixes nets[NLEN]; /* book-keeping of prefixes */
307 #endif
308 };
309 
310 /* ADD|DEL entries saved during resize */
311 struct mtype_resize_ad {
312 	struct list_head list;
313 	enum ipset_adt ad;	/* ADD|DEL element */
314 	struct mtype_elem d;	/* Element value */
315 	struct ip_set_ext ext;	/* Extensions for ADD */
316 	struct ip_set_ext mext;	/* Target extensions for ADD */
317 	u32 flags;		/* Flags for ADD */
318 };
319 
320 #ifdef IP_SET_HASH_WITH_NETS
321 /* Network cidr size book keeping when the hash stores different
322  * sized networks. cidr == real cidr + 1 to support /0.
323  */
324 static void
mtype_add_cidr(struct ip_set * set,struct htype * h,u8 cidr,u8 n)325 mtype_add_cidr(struct ip_set *set, struct htype *h, u8 cidr, u8 n)
326 {
327 	int i, j;
328 
329 	spin_lock_bh(&set->lock);
330 	/* Add in increasing prefix order, so larger cidr first */
331 	for (i = 0, j = -1; i < NLEN && h->nets[i].cidr[n]; i++) {
332 		if (j != -1) {
333 			continue;
334 		} else if (h->nets[i].cidr[n] < cidr) {
335 			j = i;
336 		} else if (h->nets[i].cidr[n] == cidr) {
337 			h->nets[CIDR_POS(cidr)].nets[n]++;
338 			goto unlock;
339 		}
340 	}
341 	if (j != -1) {
342 		for (; i > j; i--)
343 			h->nets[i].cidr[n] = h->nets[i - 1].cidr[n];
344 	}
345 	h->nets[i].cidr[n] = cidr;
346 	h->nets[CIDR_POS(cidr)].nets[n] = 1;
347 unlock:
348 	spin_unlock_bh(&set->lock);
349 }
350 
351 static void
mtype_del_cidr(struct ip_set * set,struct htype * h,u8 cidr,u8 n)352 mtype_del_cidr(struct ip_set *set, struct htype *h, u8 cidr, u8 n)
353 {
354 	u8 i, j, net_end = NLEN - 1;
355 
356 	spin_lock_bh(&set->lock);
357 	for (i = 0; i < NLEN; i++) {
358 		if (h->nets[i].cidr[n] != cidr)
359 			continue;
360 		h->nets[CIDR_POS(cidr)].nets[n]--;
361 		if (h->nets[CIDR_POS(cidr)].nets[n] > 0)
362 			goto unlock;
363 		for (j = i; j < net_end && h->nets[j].cidr[n]; j++)
364 			h->nets[j].cidr[n] = h->nets[j + 1].cidr[n];
365 		h->nets[j].cidr[n] = 0;
366 		goto unlock;
367 	}
368 unlock:
369 	spin_unlock_bh(&set->lock);
370 }
371 #endif
372 
373 /* Calculate the actual memory size of the set data */
374 static size_t
mtype_ahash_memsize(const struct htype * h,const struct htable * t)375 mtype_ahash_memsize(const struct htype *h, const struct htable *t)
376 {
377 	return sizeof(*h) + sizeof(*t) + ahash_sizeof_regions(t->htable_bits);
378 }
379 
380 /* Get the ith element from the array block n */
381 #define ahash_data(n, i, dsize)	\
382 	((struct mtype_elem *)((n)->value + ((i) * (dsize))))
383 
384 static void
mtype_ext_cleanup(struct ip_set * set,struct hbucket * n)385 mtype_ext_cleanup(struct ip_set *set, struct hbucket *n)
386 {
387 	int i;
388 
389 	for (i = 0; i < n->pos; i++)
390 		if (test_bit(i, n->used))
391 			ip_set_ext_destroy(set, ahash_data(n, i, set->dsize));
392 }
393 
394 /* Flush a hash type of set: destroy all elements */
395 static void
mtype_flush(struct ip_set * set)396 mtype_flush(struct ip_set *set)
397 {
398 	struct htype *h = set->data;
399 	struct htable *t;
400 	struct hbucket *n;
401 	u32 r, i;
402 
403 	t = ipset_dereference_nfnl(h->table);
404 	for (r = 0; r < ahash_numof_locks(t->htable_bits); r++) {
405 		spin_lock_bh(&t->hregion[r].lock);
406 		for (i = ahash_bucket_start(r, t->htable_bits);
407 		     i < ahash_bucket_end(r, t->htable_bits); i++) {
408 			n = __ipset_dereference(hbucket(t, i));
409 			if (!n)
410 				continue;
411 			if (set->extensions & IPSET_EXT_DESTROY)
412 				mtype_ext_cleanup(set, n);
413 			/* FIXME: use slab cache */
414 			rcu_assign_pointer(hbucket(t, i), NULL);
415 			kfree_rcu(n, rcu);
416 		}
417 		t->hregion[r].ext_size = 0;
418 		t->hregion[r].elements = 0;
419 		spin_unlock_bh(&t->hregion[r].lock);
420 	}
421 #ifdef IP_SET_HASH_WITH_NETS
422 	memset(h->nets, 0, sizeof(h->nets));
423 #endif
424 }
425 
426 /* Destroy the hashtable part of the set */
427 static void
mtype_ahash_destroy(struct ip_set * set,struct htable * t,bool ext_destroy)428 mtype_ahash_destroy(struct ip_set *set, struct htable *t, bool ext_destroy)
429 {
430 	struct hbucket *n;
431 	u32 i;
432 
433 	for (i = 0; i < jhash_size(t->htable_bits); i++) {
434 		n = (__force struct hbucket *)hbucket(t, i);
435 		if (!n)
436 			continue;
437 		if (set->extensions & IPSET_EXT_DESTROY && ext_destroy)
438 			mtype_ext_cleanup(set, n);
439 		/* FIXME: use slab cache */
440 		kfree(n);
441 	}
442 
443 	ip_set_free(t->hregion);
444 	ip_set_free(t);
445 }
446 
447 /* Destroy a hash type of set */
448 static void
mtype_destroy(struct ip_set * set)449 mtype_destroy(struct ip_set *set)
450 {
451 	struct htype *h = set->data;
452 	struct list_head *l, *lt;
453 
454 	mtype_ahash_destroy(set, (__force struct htable *)h->table, true);
455 	list_for_each_safe(l, lt, &h->ad) {
456 		list_del(l);
457 		kfree(l);
458 	}
459 	kfree(h);
460 
461 	set->data = NULL;
462 }
463 
464 static bool
mtype_same_set(const struct ip_set * a,const struct ip_set * b)465 mtype_same_set(const struct ip_set *a, const struct ip_set *b)
466 {
467 	const struct htype *x = a->data;
468 	const struct htype *y = b->data;
469 
470 	/* Resizing changes htable_bits, so we ignore it */
471 	return x->maxelem == y->maxelem &&
472 	       a->timeout == b->timeout &&
473 #if defined(IP_SET_HASH_WITH_NETMASK) || defined(IP_SET_HASH_WITH_BITMASK)
474 	       nf_inet_addr_cmp(&x->bitmask, &y->bitmask) &&
475 #endif
476 #ifdef IP_SET_HASH_WITH_MARKMASK
477 	       x->markmask == y->markmask &&
478 #endif
479 	       a->extensions == b->extensions;
480 }
481 
482 static void
mtype_gc_do(struct ip_set * set,struct htype * h,struct htable * t,u32 r)483 mtype_gc_do(struct ip_set *set, struct htype *h, struct htable *t, u32 r)
484 {
485 	struct hbucket *n, *tmp;
486 	struct mtype_elem *data;
487 	u32 i, j, d;
488 	size_t dsize = set->dsize;
489 #ifdef IP_SET_HASH_WITH_NETS
490 	u8 k;
491 #endif
492 	u8 htable_bits = t->htable_bits;
493 
494 	spin_lock_bh(&t->hregion[r].lock);
495 	for (i = ahash_bucket_start(r, htable_bits);
496 	     i < ahash_bucket_end(r, htable_bits); i++) {
497 		n = __ipset_dereference(hbucket(t, i));
498 		if (!n)
499 			continue;
500 		for (j = 0, d = 0; j < n->pos; j++) {
501 			if (!test_bit(j, n->used)) {
502 				d++;
503 				continue;
504 			}
505 			data = ahash_data(n, j, dsize);
506 			if (!ip_set_timeout_expired(ext_timeout(data, set)))
507 				continue;
508 			pr_debug("expired %u/%u\n", i, j);
509 			clear_bit(j, n->used);
510 			smp_mb__after_atomic();
511 #ifdef IP_SET_HASH_WITH_NETS
512 			for (k = 0; k < IPSET_NET_COUNT; k++)
513 				mtype_del_cidr(set, h,
514 					NCIDR_PUT(DCIDR_GET(data->cidr, k)),
515 					k);
516 #endif
517 			t->hregion[r].elements--;
518 			ip_set_ext_destroy(set, data);
519 			d++;
520 		}
521 		if (d >= AHASH_INIT_SIZE) {
522 			if (d >= n->size) {
523 				t->hregion[r].ext_size -=
524 					ext_size(n->size, dsize);
525 				rcu_assign_pointer(hbucket(t, i), NULL);
526 				kfree_rcu(n, rcu);
527 				continue;
528 			}
529 			tmp = kzalloc(sizeof(*tmp) +
530 				(n->size - AHASH_INIT_SIZE) * dsize,
531 				GFP_ATOMIC);
532 			if (!tmp)
533 				/* Still try to delete expired elements. */
534 				continue;
535 			tmp->size = n->size - AHASH_INIT_SIZE;
536 			for (j = 0, d = 0; j < n->pos; j++) {
537 				if (!test_bit(j, n->used))
538 					continue;
539 				data = ahash_data(n, j, dsize);
540 				memcpy(tmp->value + d * dsize,
541 				       data, dsize);
542 				set_bit(d, tmp->used);
543 				d++;
544 			}
545 			tmp->pos = d;
546 			t->hregion[r].ext_size -=
547 				ext_size(AHASH_INIT_SIZE, dsize);
548 			rcu_assign_pointer(hbucket(t, i), tmp);
549 			kfree_rcu(n, rcu);
550 		}
551 	}
552 	spin_unlock_bh(&t->hregion[r].lock);
553 }
554 
555 static void
mtype_gc(struct work_struct * work)556 mtype_gc(struct work_struct *work)
557 {
558 	struct htable_gc *gc;
559 	struct ip_set *set;
560 	struct htype *h;
561 	struct htable *t;
562 	u32 r, numof_locks;
563 	unsigned int next_run;
564 
565 	gc = container_of(work, struct htable_gc, dwork.work);
566 	set = gc->set;
567 	h = set->data;
568 
569 	spin_lock_bh(&set->lock);
570 	t = ipset_dereference_set(h->table, set);
571 	atomic_inc(&t->uref);
572 	numof_locks = ahash_numof_locks(t->htable_bits);
573 	r = gc->region++;
574 	if (r >= numof_locks) {
575 		r = gc->region = 0;
576 	}
577 	next_run = (IPSET_GC_PERIOD(set->timeout) * HZ) / numof_locks;
578 	if (next_run < HZ/10)
579 		next_run = HZ/10;
580 	spin_unlock_bh(&set->lock);
581 
582 	mtype_gc_do(set, h, t, r);
583 
584 	if (atomic_dec_and_test(&t->uref) && atomic_read(&t->ref)) {
585 		pr_debug("Table destroy after resize by expire: %p\n", t);
586 		mtype_ahash_destroy(set, t, false);
587 	}
588 
589 	queue_delayed_work(system_power_efficient_wq, &gc->dwork, next_run);
590 
591 }
592 
593 static void
mtype_gc_init(struct htable_gc * gc)594 mtype_gc_init(struct htable_gc *gc)
595 {
596 	INIT_DEFERRABLE_WORK(&gc->dwork, mtype_gc);
597 	queue_delayed_work(system_power_efficient_wq, &gc->dwork, HZ);
598 }
599 
600 static void
mtype_cancel_gc(struct ip_set * set)601 mtype_cancel_gc(struct ip_set *set)
602 {
603 	struct htype *h = set->data;
604 
605 	if (SET_WITH_TIMEOUT(set))
606 		cancel_delayed_work_sync(&h->gc.dwork);
607 }
608 
609 static int
610 mtype_add(struct ip_set *set, void *value, const struct ip_set_ext *ext,
611 	  struct ip_set_ext *mext, u32 flags);
612 static int
613 mtype_del(struct ip_set *set, void *value, const struct ip_set_ext *ext,
614 	  struct ip_set_ext *mext, u32 flags);
615 
616 /* Resize a hash: create a new hash table with doubling the hashsize
617  * and inserting the elements to it. Repeat until we succeed or
618  * fail due to memory pressures.
619  */
620 static int
mtype_resize(struct ip_set * set,bool retried)621 mtype_resize(struct ip_set *set, bool retried)
622 {
623 	struct htype *h = set->data;
624 	struct htable *t, *orig;
625 	u8 htable_bits;
626 	size_t hsize, dsize = set->dsize;
627 #ifdef IP_SET_HASH_WITH_NETS
628 	u8 flags;
629 	struct mtype_elem *tmp;
630 #endif
631 	struct mtype_elem *data;
632 	struct mtype_elem *d;
633 	struct hbucket *n, *m;
634 	struct list_head *l, *lt;
635 	struct mtype_resize_ad *x;
636 	u32 i, j, r, nr, key;
637 	int ret;
638 
639 #ifdef IP_SET_HASH_WITH_NETS
640 	tmp = kmalloc(dsize, GFP_KERNEL);
641 	if (!tmp)
642 		return -ENOMEM;
643 #endif
644 	orig = ipset_dereference_bh_nfnl(h->table);
645 	htable_bits = orig->htable_bits;
646 
647 retry:
648 	ret = 0;
649 	htable_bits++;
650 	if (!htable_bits)
651 		goto hbwarn;
652 	hsize = htable_size(htable_bits);
653 	if (!hsize)
654 		goto hbwarn;
655 	t = ip_set_alloc(hsize);
656 	if (!t) {
657 		ret = -ENOMEM;
658 		goto out;
659 	}
660 	t->hregion = ip_set_alloc(ahash_sizeof_regions(htable_bits));
661 	if (!t->hregion) {
662 		ip_set_free(t);
663 		ret = -ENOMEM;
664 		goto out;
665 	}
666 	t->htable_bits = htable_bits;
667 	t->maxelem = h->maxelem / ahash_numof_locks(htable_bits);
668 	for (i = 0; i < ahash_numof_locks(htable_bits); i++)
669 		spin_lock_init(&t->hregion[i].lock);
670 
671 	/* There can't be another parallel resizing,
672 	 * but dumping, gc, kernel side add/del are possible
673 	 */
674 	orig = ipset_dereference_bh_nfnl(h->table);
675 	atomic_set(&orig->ref, 1);
676 	atomic_inc(&orig->uref);
677 	pr_debug("attempt to resize set %s from %u to %u, t %p\n",
678 		 set->name, orig->htable_bits, htable_bits, orig);
679 	for (r = 0; r < ahash_numof_locks(orig->htable_bits); r++) {
680 		/* Expire may replace a hbucket with another one */
681 		rcu_read_lock_bh();
682 		for (i = ahash_bucket_start(r, orig->htable_bits);
683 		     i < ahash_bucket_end(r, orig->htable_bits); i++) {
684 			n = __ipset_dereference(hbucket(orig, i));
685 			if (!n)
686 				continue;
687 			for (j = 0; j < n->pos; j++) {
688 				if (!test_bit(j, n->used))
689 					continue;
690 				data = ahash_data(n, j, dsize);
691 				if (SET_ELEM_EXPIRED(set, data))
692 					continue;
693 #ifdef IP_SET_HASH_WITH_NETS
694 				/* We have readers running parallel with us,
695 				 * so the live data cannot be modified.
696 				 */
697 				flags = 0;
698 				memcpy(tmp, data, dsize);
699 				data = tmp;
700 				mtype_data_reset_flags(data, &flags);
701 #endif
702 				key = HKEY(data, h->initval, htable_bits);
703 				m = __ipset_dereference(hbucket(t, key));
704 				nr = ahash_region(key, htable_bits);
705 				if (!m) {
706 					m = kzalloc(sizeof(*m) +
707 					    AHASH_INIT_SIZE * dsize,
708 					    GFP_ATOMIC);
709 					if (!m) {
710 						ret = -ENOMEM;
711 						goto cleanup;
712 					}
713 					m->size = AHASH_INIT_SIZE;
714 					t->hregion[nr].ext_size +=
715 						ext_size(AHASH_INIT_SIZE,
716 							 dsize);
717 					RCU_INIT_POINTER(hbucket(t, key), m);
718 				} else if (m->pos >= m->size) {
719 					struct hbucket *ht;
720 
721 					if (m->size >= AHASH_MAX(h)) {
722 						ret = -EAGAIN;
723 					} else {
724 						ht = kzalloc(sizeof(*ht) +
725 						(m->size + AHASH_INIT_SIZE)
726 						* dsize,
727 						GFP_ATOMIC);
728 						if (!ht)
729 							ret = -ENOMEM;
730 					}
731 					if (ret < 0)
732 						goto cleanup;
733 					memcpy(ht, m, sizeof(struct hbucket) +
734 					       m->size * dsize);
735 					ht->size = m->size + AHASH_INIT_SIZE;
736 					t->hregion[nr].ext_size +=
737 						ext_size(AHASH_INIT_SIZE,
738 							 dsize);
739 					kfree(m);
740 					m = ht;
741 					RCU_INIT_POINTER(hbucket(t, key), ht);
742 				}
743 				d = ahash_data(m, m->pos, dsize);
744 				memcpy(d, data, dsize);
745 				set_bit(m->pos++, m->used);
746 				t->hregion[nr].elements++;
747 #ifdef IP_SET_HASH_WITH_NETS
748 				mtype_data_reset_flags(d, &flags);
749 #endif
750 			}
751 		}
752 		rcu_read_unlock_bh();
753 	}
754 
755 	/* There can't be any other writer. */
756 	rcu_assign_pointer(h->table, t);
757 
758 	/* Give time to other readers of the set */
759 	synchronize_rcu();
760 
761 	pr_debug("set %s resized from %u (%p) to %u (%p)\n", set->name,
762 		 orig->htable_bits, orig, t->htable_bits, t);
763 	/* Add/delete elements processed by the SET target during resize.
764 	 * Kernel-side add cannot trigger a resize and userspace actions
765 	 * are serialized by the mutex.
766 	 */
767 	list_for_each_safe(l, lt, &h->ad) {
768 		x = list_entry(l, struct mtype_resize_ad, list);
769 		if (x->ad == IPSET_ADD) {
770 			mtype_add(set, &x->d, &x->ext, &x->mext, x->flags);
771 		} else {
772 			mtype_del(set, &x->d, NULL, NULL, 0);
773 		}
774 		list_del(l);
775 		kfree(l);
776 	}
777 	/* If there's nobody else using the table, destroy it */
778 	if (atomic_dec_and_test(&orig->uref)) {
779 		pr_debug("Table destroy by resize %p\n", orig);
780 		mtype_ahash_destroy(set, orig, false);
781 	}
782 
783 out:
784 #ifdef IP_SET_HASH_WITH_NETS
785 	kfree(tmp);
786 #endif
787 	return ret;
788 
789 cleanup:
790 	rcu_read_unlock_bh();
791 	atomic_set(&orig->ref, 0);
792 	atomic_dec(&orig->uref);
793 	mtype_ahash_destroy(set, t, false);
794 	if (ret == -EAGAIN)
795 		goto retry;
796 	goto out;
797 
798 hbwarn:
799 	/* In case we have plenty of memory :-) */
800 	pr_warn("Cannot increase the hashsize of set %s further\n", set->name);
801 	ret = -IPSET_ERR_HASH_FULL;
802 	goto out;
803 }
804 
805 /* Get the current number of elements and ext_size in the set  */
806 static void
mtype_ext_size(struct ip_set * set,u32 * elements,size_t * ext_size)807 mtype_ext_size(struct ip_set *set, u32 *elements, size_t *ext_size)
808 {
809 	struct htype *h = set->data;
810 	const struct htable *t;
811 	u32 i, j, r;
812 	struct hbucket *n;
813 	struct mtype_elem *data;
814 
815 	t = rcu_dereference_bh(h->table);
816 	for (r = 0; r < ahash_numof_locks(t->htable_bits); r++) {
817 		for (i = ahash_bucket_start(r, t->htable_bits);
818 		     i < ahash_bucket_end(r, t->htable_bits); i++) {
819 			n = rcu_dereference_bh(hbucket(t, i));
820 			if (!n)
821 				continue;
822 			for (j = 0; j < n->pos; j++) {
823 				if (!test_bit(j, n->used))
824 					continue;
825 				data = ahash_data(n, j, set->dsize);
826 				if (!SET_ELEM_EXPIRED(set, data))
827 					(*elements)++;
828 			}
829 		}
830 		*ext_size += t->hregion[r].ext_size;
831 	}
832 }
833 
834 /* Add an element to a hash and update the internal counters when succeeded,
835  * otherwise report the proper error code.
836  */
837 static int
mtype_add(struct ip_set * set,void * value,const struct ip_set_ext * ext,struct ip_set_ext * mext,u32 flags)838 mtype_add(struct ip_set *set, void *value, const struct ip_set_ext *ext,
839 	  struct ip_set_ext *mext, u32 flags)
840 {
841 	struct htype *h = set->data;
842 	struct htable *t;
843 	const struct mtype_elem *d = value;
844 	struct mtype_elem *data;
845 	struct hbucket *n, *old = ERR_PTR(-ENOENT);
846 	int i, j = -1, ret;
847 	bool flag_exist = flags & IPSET_FLAG_EXIST;
848 	bool deleted = false, forceadd = false, reuse = false;
849 	u32 r, key, multi = 0, elements, maxelem;
850 
851 	rcu_read_lock_bh();
852 	t = rcu_dereference_bh(h->table);
853 	key = HKEY(value, h->initval, t->htable_bits);
854 	r = ahash_region(key, t->htable_bits);
855 	atomic_inc(&t->uref);
856 	elements = t->hregion[r].elements;
857 	maxelem = t->maxelem;
858 	if (elements >= maxelem) {
859 		u32 e;
860 		if (SET_WITH_TIMEOUT(set)) {
861 			rcu_read_unlock_bh();
862 			mtype_gc_do(set, h, t, r);
863 			rcu_read_lock_bh();
864 		}
865 		maxelem = h->maxelem;
866 		elements = 0;
867 		for (e = 0; e < ahash_numof_locks(t->htable_bits); e++)
868 			elements += t->hregion[e].elements;
869 		if (elements >= maxelem && SET_WITH_FORCEADD(set))
870 			forceadd = true;
871 	}
872 	rcu_read_unlock_bh();
873 
874 	spin_lock_bh(&t->hregion[r].lock);
875 	n = rcu_dereference_bh(hbucket(t, key));
876 	if (!n) {
877 		if (forceadd || elements >= maxelem)
878 			goto set_full;
879 		old = NULL;
880 		n = kzalloc(sizeof(*n) + AHASH_INIT_SIZE * set->dsize,
881 			    GFP_ATOMIC);
882 		if (!n) {
883 			ret = -ENOMEM;
884 			goto unlock;
885 		}
886 		n->size = AHASH_INIT_SIZE;
887 		t->hregion[r].ext_size +=
888 			ext_size(AHASH_INIT_SIZE, set->dsize);
889 		goto copy_elem;
890 	}
891 	for (i = 0; i < n->pos; i++) {
892 		if (!test_bit(i, n->used)) {
893 			/* Reuse first deleted entry */
894 			if (j == -1) {
895 				deleted = reuse = true;
896 				j = i;
897 			}
898 			continue;
899 		}
900 		data = ahash_data(n, i, set->dsize);
901 		if (mtype_data_equal(data, d, &multi)) {
902 			if (flag_exist || SET_ELEM_EXPIRED(set, data)) {
903 				/* Just the extensions could be overwritten */
904 				j = i;
905 				goto overwrite_extensions;
906 			}
907 			ret = -IPSET_ERR_EXIST;
908 			goto unlock;
909 		}
910 		/* Reuse first timed out entry */
911 		if (SET_ELEM_EXPIRED(set, data) && j == -1) {
912 			j = i;
913 			reuse = true;
914 		}
915 	}
916 	if (reuse || forceadd) {
917 		if (j == -1)
918 			j = 0;
919 		data = ahash_data(n, j, set->dsize);
920 		if (!deleted) {
921 #ifdef IP_SET_HASH_WITH_NETS
922 			for (i = 0; i < IPSET_NET_COUNT; i++)
923 				mtype_del_cidr(set, h,
924 					NCIDR_PUT(DCIDR_GET(data->cidr, i)),
925 					i);
926 #endif
927 			ip_set_ext_destroy(set, data);
928 			t->hregion[r].elements--;
929 		}
930 		goto copy_data;
931 	}
932 	if (elements >= maxelem)
933 		goto set_full;
934 	/* Create a new slot */
935 	if (n->pos >= n->size) {
936 #ifdef IP_SET_HASH_WITH_MULTI
937 		if (h->bucketsize >= AHASH_MAX_TUNED)
938 			goto set_full;
939 		else if (h->bucketsize <= multi)
940 			h->bucketsize += AHASH_INIT_SIZE;
941 #endif
942 		if (n->size >= AHASH_MAX(h)) {
943 			/* Trigger rehashing */
944 			mtype_data_next(&h->next, d);
945 			ret = -EAGAIN;
946 			goto resize;
947 		}
948 		old = n;
949 		n = kzalloc(sizeof(*n) +
950 			    (old->size + AHASH_INIT_SIZE) * set->dsize,
951 			    GFP_ATOMIC);
952 		if (!n) {
953 			ret = -ENOMEM;
954 			goto unlock;
955 		}
956 		memcpy(n, old, sizeof(struct hbucket) +
957 		       old->size * set->dsize);
958 		n->size = old->size + AHASH_INIT_SIZE;
959 		t->hregion[r].ext_size +=
960 			ext_size(AHASH_INIT_SIZE, set->dsize);
961 	}
962 
963 copy_elem:
964 	j = n->pos++;
965 	data = ahash_data(n, j, set->dsize);
966 copy_data:
967 	t->hregion[r].elements++;
968 #ifdef IP_SET_HASH_WITH_NETS
969 	for (i = 0; i < IPSET_NET_COUNT; i++)
970 		mtype_add_cidr(set, h, NCIDR_PUT(DCIDR_GET(d->cidr, i)), i);
971 #endif
972 	memcpy(data, d, sizeof(struct mtype_elem));
973 overwrite_extensions:
974 #ifdef IP_SET_HASH_WITH_NETS
975 	mtype_data_set_flags(data, flags);
976 #endif
977 	if (SET_WITH_COUNTER(set))
978 		ip_set_init_counter(ext_counter(data, set), ext);
979 	if (SET_WITH_COMMENT(set))
980 		ip_set_init_comment(set, ext_comment(data, set), ext);
981 	if (SET_WITH_SKBINFO(set))
982 		ip_set_init_skbinfo(ext_skbinfo(data, set), ext);
983 	/* Must come last for the case when timed out entry is reused */
984 	if (SET_WITH_TIMEOUT(set))
985 		ip_set_timeout_set(ext_timeout(data, set), ext->timeout);
986 	smp_mb__before_atomic();
987 	set_bit(j, n->used);
988 	if (old != ERR_PTR(-ENOENT)) {
989 		rcu_assign_pointer(hbucket(t, key), n);
990 		if (old)
991 			kfree_rcu(old, rcu);
992 	}
993 	ret = 0;
994 resize:
995 	spin_unlock_bh(&t->hregion[r].lock);
996 	if (atomic_read(&t->ref) && ext->target) {
997 		/* Resize is in process and kernel side add, save values */
998 		struct mtype_resize_ad *x;
999 
1000 		x = kzalloc(sizeof(struct mtype_resize_ad), GFP_ATOMIC);
1001 		if (!x)
1002 			/* Don't bother */
1003 			goto out;
1004 		x->ad = IPSET_ADD;
1005 		memcpy(&x->d, value, sizeof(struct mtype_elem));
1006 		memcpy(&x->ext, ext, sizeof(struct ip_set_ext));
1007 		memcpy(&x->mext, mext, sizeof(struct ip_set_ext));
1008 		x->flags = flags;
1009 		spin_lock_bh(&set->lock);
1010 		list_add_tail(&x->list, &h->ad);
1011 		spin_unlock_bh(&set->lock);
1012 	}
1013 	goto out;
1014 
1015 set_full:
1016 	if (net_ratelimit())
1017 		pr_warn("Set %s is full, maxelem %u reached\n",
1018 			set->name, maxelem);
1019 	ret = -IPSET_ERR_HASH_FULL;
1020 unlock:
1021 	spin_unlock_bh(&t->hregion[r].lock);
1022 out:
1023 	if (atomic_dec_and_test(&t->uref) && atomic_read(&t->ref)) {
1024 		pr_debug("Table destroy after resize by add: %p\n", t);
1025 		mtype_ahash_destroy(set, t, false);
1026 	}
1027 	return ret;
1028 }
1029 
1030 /* Delete an element from the hash and free up space if possible.
1031  */
1032 static int
mtype_del(struct ip_set * set,void * value,const struct ip_set_ext * ext,struct ip_set_ext * mext,u32 flags)1033 mtype_del(struct ip_set *set, void *value, const struct ip_set_ext *ext,
1034 	  struct ip_set_ext *mext, u32 flags)
1035 {
1036 	struct htype *h = set->data;
1037 	struct htable *t;
1038 	const struct mtype_elem *d = value;
1039 	struct mtype_elem *data;
1040 	struct hbucket *n;
1041 	struct mtype_resize_ad *x = NULL;
1042 	int i, j, k, r, ret = -IPSET_ERR_EXIST;
1043 	u32 key, multi = 0;
1044 	size_t dsize = set->dsize;
1045 
1046 	/* Userspace add and resize is excluded by the mutex.
1047 	 * Kernespace add does not trigger resize.
1048 	 */
1049 	rcu_read_lock_bh();
1050 	t = rcu_dereference_bh(h->table);
1051 	key = HKEY(value, h->initval, t->htable_bits);
1052 	r = ahash_region(key, t->htable_bits);
1053 	atomic_inc(&t->uref);
1054 	rcu_read_unlock_bh();
1055 
1056 	spin_lock_bh(&t->hregion[r].lock);
1057 	n = rcu_dereference_bh(hbucket(t, key));
1058 	if (!n)
1059 		goto out;
1060 	for (i = 0, k = 0; i < n->pos; i++) {
1061 		if (!test_bit(i, n->used)) {
1062 			k++;
1063 			continue;
1064 		}
1065 		data = ahash_data(n, i, dsize);
1066 		if (!mtype_data_equal(data, d, &multi))
1067 			continue;
1068 		if (SET_ELEM_EXPIRED(set, data))
1069 			goto out;
1070 
1071 		ret = 0;
1072 		clear_bit(i, n->used);
1073 		smp_mb__after_atomic();
1074 		if (i + 1 == n->pos)
1075 			n->pos--;
1076 		t->hregion[r].elements--;
1077 #ifdef IP_SET_HASH_WITH_NETS
1078 		for (j = 0; j < IPSET_NET_COUNT; j++)
1079 			mtype_del_cidr(set, h,
1080 				       NCIDR_PUT(DCIDR_GET(d->cidr, j)), j);
1081 #endif
1082 		ip_set_ext_destroy(set, data);
1083 
1084 		if (atomic_read(&t->ref) && ext->target) {
1085 			/* Resize is in process and kernel side del,
1086 			 * save values
1087 			 */
1088 			x = kzalloc(sizeof(struct mtype_resize_ad),
1089 				    GFP_ATOMIC);
1090 			if (x) {
1091 				x->ad = IPSET_DEL;
1092 				memcpy(&x->d, value,
1093 				       sizeof(struct mtype_elem));
1094 				x->flags = flags;
1095 			}
1096 		}
1097 		for (; i < n->pos; i++) {
1098 			if (!test_bit(i, n->used))
1099 				k++;
1100 		}
1101 		if (n->pos == 0 && k == 0) {
1102 			t->hregion[r].ext_size -= ext_size(n->size, dsize);
1103 			rcu_assign_pointer(hbucket(t, key), NULL);
1104 			kfree_rcu(n, rcu);
1105 		} else if (k >= AHASH_INIT_SIZE) {
1106 			struct hbucket *tmp = kzalloc(sizeof(*tmp) +
1107 					(n->size - AHASH_INIT_SIZE) * dsize,
1108 					GFP_ATOMIC);
1109 			if (!tmp)
1110 				goto out;
1111 			tmp->size = n->size - AHASH_INIT_SIZE;
1112 			for (j = 0, k = 0; j < n->pos; j++) {
1113 				if (!test_bit(j, n->used))
1114 					continue;
1115 				data = ahash_data(n, j, dsize);
1116 				memcpy(tmp->value + k * dsize, data, dsize);
1117 				set_bit(k, tmp->used);
1118 				k++;
1119 			}
1120 			tmp->pos = k;
1121 			t->hregion[r].ext_size -=
1122 				ext_size(AHASH_INIT_SIZE, dsize);
1123 			rcu_assign_pointer(hbucket(t, key), tmp);
1124 			kfree_rcu(n, rcu);
1125 		}
1126 		goto out;
1127 	}
1128 
1129 out:
1130 	spin_unlock_bh(&t->hregion[r].lock);
1131 	if (x) {
1132 		spin_lock_bh(&set->lock);
1133 		list_add(&x->list, &h->ad);
1134 		spin_unlock_bh(&set->lock);
1135 	}
1136 	if (atomic_dec_and_test(&t->uref) && atomic_read(&t->ref)) {
1137 		pr_debug("Table destroy after resize by del: %p\n", t);
1138 		mtype_ahash_destroy(set, t, false);
1139 	}
1140 	return ret;
1141 }
1142 
1143 static int
mtype_data_match(struct mtype_elem * data,const struct ip_set_ext * ext,struct ip_set_ext * mext,struct ip_set * set,u32 flags)1144 mtype_data_match(struct mtype_elem *data, const struct ip_set_ext *ext,
1145 		 struct ip_set_ext *mext, struct ip_set *set, u32 flags)
1146 {
1147 	if (!ip_set_match_extensions(set, ext, mext, flags, data))
1148 		return 0;
1149 	/* nomatch entries return -ENOTEMPTY */
1150 	return mtype_do_data_match(data);
1151 }
1152 
1153 #ifdef IP_SET_HASH_WITH_NETS
1154 /* Special test function which takes into account the different network
1155  * sizes added to the set
1156  */
1157 static int
mtype_test_cidrs(struct ip_set * set,struct mtype_elem * d,const struct ip_set_ext * ext,struct ip_set_ext * mext,u32 flags)1158 mtype_test_cidrs(struct ip_set *set, struct mtype_elem *d,
1159 		 const struct ip_set_ext *ext,
1160 		 struct ip_set_ext *mext, u32 flags)
1161 {
1162 	struct htype *h = set->data;
1163 	struct htable *t = rcu_dereference_bh(h->table);
1164 	struct hbucket *n;
1165 	struct mtype_elem *data;
1166 #if IPSET_NET_COUNT == 2
1167 	struct mtype_elem orig = *d;
1168 	int ret, i, j = 0, k;
1169 #else
1170 	int ret, i, j = 0;
1171 #endif
1172 	u32 key, multi = 0;
1173 
1174 	pr_debug("test by nets\n");
1175 	for (; j < NLEN && h->nets[j].cidr[0] && !multi; j++) {
1176 #if IPSET_NET_COUNT == 2
1177 		mtype_data_reset_elem(d, &orig);
1178 		mtype_data_netmask(d, NCIDR_GET(h->nets[j].cidr[0]), false);
1179 		for (k = 0; k < NLEN && h->nets[k].cidr[1] && !multi;
1180 		     k++) {
1181 			mtype_data_netmask(d, NCIDR_GET(h->nets[k].cidr[1]),
1182 					   true);
1183 #else
1184 		mtype_data_netmask(d, NCIDR_GET(h->nets[j].cidr[0]));
1185 #endif
1186 		key = HKEY(d, h->initval, t->htable_bits);
1187 		n = rcu_dereference_bh(hbucket(t, key));
1188 		if (!n)
1189 			continue;
1190 		for (i = 0; i < n->pos; i++) {
1191 			if (!test_bit(i, n->used))
1192 				continue;
1193 			data = ahash_data(n, i, set->dsize);
1194 			if (!mtype_data_equal(data, d, &multi))
1195 				continue;
1196 			ret = mtype_data_match(data, ext, mext, set, flags);
1197 			if (ret != 0)
1198 				return ret;
1199 #ifdef IP_SET_HASH_WITH_MULTI
1200 			/* No match, reset multiple match flag */
1201 			multi = 0;
1202 #endif
1203 		}
1204 #if IPSET_NET_COUNT == 2
1205 		}
1206 #endif
1207 	}
1208 	return 0;
1209 }
1210 #endif
1211 
1212 /* Test whether the element is added to the set */
1213 static int
mtype_test(struct ip_set * set,void * value,const struct ip_set_ext * ext,struct ip_set_ext * mext,u32 flags)1214 mtype_test(struct ip_set *set, void *value, const struct ip_set_ext *ext,
1215 	   struct ip_set_ext *mext, u32 flags)
1216 {
1217 	struct htype *h = set->data;
1218 	struct htable *t;
1219 	struct mtype_elem *d = value;
1220 	struct hbucket *n;
1221 	struct mtype_elem *data;
1222 	int i, ret = 0;
1223 	u32 key, multi = 0;
1224 
1225 	rcu_read_lock_bh();
1226 	t = rcu_dereference_bh(h->table);
1227 #ifdef IP_SET_HASH_WITH_NETS
1228 	/* If we test an IP address and not a network address,
1229 	 * try all possible network sizes
1230 	 */
1231 	for (i = 0; i < IPSET_NET_COUNT; i++)
1232 		if (DCIDR_GET(d->cidr, i) != HOST_MASK)
1233 			break;
1234 	if (i == IPSET_NET_COUNT) {
1235 		ret = mtype_test_cidrs(set, d, ext, mext, flags);
1236 		goto out;
1237 	}
1238 #endif
1239 
1240 	key = HKEY(d, h->initval, t->htable_bits);
1241 	n = rcu_dereference_bh(hbucket(t, key));
1242 	if (!n) {
1243 		ret = 0;
1244 		goto out;
1245 	}
1246 	for (i = 0; i < n->pos; i++) {
1247 		if (!test_bit(i, n->used))
1248 			continue;
1249 		data = ahash_data(n, i, set->dsize);
1250 		if (!mtype_data_equal(data, d, &multi))
1251 			continue;
1252 		ret = mtype_data_match(data, ext, mext, set, flags);
1253 		if (ret != 0)
1254 			goto out;
1255 	}
1256 out:
1257 	rcu_read_unlock_bh();
1258 	return ret;
1259 }
1260 
1261 /* Reply a HEADER request: fill out the header part of the set */
1262 static int
mtype_head(struct ip_set * set,struct sk_buff * skb)1263 mtype_head(struct ip_set *set, struct sk_buff *skb)
1264 {
1265 	struct htype *h = set->data;
1266 	const struct htable *t;
1267 	struct nlattr *nested;
1268 	size_t memsize;
1269 	u32 elements = 0;
1270 	size_t ext_size = 0;
1271 	u8 htable_bits;
1272 
1273 	rcu_read_lock_bh();
1274 	t = rcu_dereference_bh(h->table);
1275 	mtype_ext_size(set, &elements, &ext_size);
1276 	memsize = mtype_ahash_memsize(h, t) + ext_size + set->ext_size;
1277 	htable_bits = t->htable_bits;
1278 	rcu_read_unlock_bh();
1279 
1280 	nested = nla_nest_start(skb, IPSET_ATTR_DATA);
1281 	if (!nested)
1282 		goto nla_put_failure;
1283 	if (nla_put_net32(skb, IPSET_ATTR_HASHSIZE,
1284 			  htonl(jhash_size(htable_bits))) ||
1285 	    nla_put_net32(skb, IPSET_ATTR_MAXELEM, htonl(h->maxelem)))
1286 		goto nla_put_failure;
1287 #ifdef IP_SET_HASH_WITH_BITMASK
1288 	/* if netmask is set to anything other than HOST_MASK we know that the user supplied netmask
1289 	 * and not bitmask. These two are mutually exclusive. */
1290 	if (h->netmask == HOST_MASK && !nf_inet_addr_cmp(&onesmask, &h->bitmask)) {
1291 		if (set->family == NFPROTO_IPV4) {
1292 			if (nla_put_ipaddr4(skb, IPSET_ATTR_BITMASK, h->bitmask.ip))
1293 				goto nla_put_failure;
1294 		} else if (set->family == NFPROTO_IPV6) {
1295 			if (nla_put_ipaddr6(skb, IPSET_ATTR_BITMASK, &h->bitmask.in6))
1296 				goto nla_put_failure;
1297 		}
1298 	}
1299 #endif
1300 #ifdef IP_SET_HASH_WITH_NETMASK
1301 	if (h->netmask != HOST_MASK && nla_put_u8(skb, IPSET_ATTR_NETMASK, h->netmask))
1302 		goto nla_put_failure;
1303 #endif
1304 #ifdef IP_SET_HASH_WITH_MARKMASK
1305 	if (nla_put_u32(skb, IPSET_ATTR_MARKMASK, h->markmask))
1306 		goto nla_put_failure;
1307 #endif
1308 	if (set->flags & IPSET_CREATE_FLAG_BUCKETSIZE) {
1309 		if (nla_put_u8(skb, IPSET_ATTR_BUCKETSIZE, h->bucketsize) ||
1310 		    nla_put_net32(skb, IPSET_ATTR_INITVAL, htonl(h->initval)))
1311 			goto nla_put_failure;
1312 	}
1313 	if (nla_put_net32(skb, IPSET_ATTR_REFERENCES, htonl(set->ref)) ||
1314 	    nla_put_net32(skb, IPSET_ATTR_MEMSIZE, htonl(memsize)) ||
1315 	    nla_put_net32(skb, IPSET_ATTR_ELEMENTS, htonl(elements)))
1316 		goto nla_put_failure;
1317 	if (unlikely(ip_set_put_flags(skb, set)))
1318 		goto nla_put_failure;
1319 	nla_nest_end(skb, nested);
1320 
1321 	return 0;
1322 nla_put_failure:
1323 	return -EMSGSIZE;
1324 }
1325 
1326 /* Make possible to run dumping parallel with resizing */
1327 static void
mtype_uref(struct ip_set * set,struct netlink_callback * cb,bool start)1328 mtype_uref(struct ip_set *set, struct netlink_callback *cb, bool start)
1329 {
1330 	struct htype *h = set->data;
1331 	struct htable *t;
1332 
1333 	if (start) {
1334 		rcu_read_lock_bh();
1335 		t = ipset_dereference_bh_nfnl(h->table);
1336 		atomic_inc(&t->uref);
1337 		cb->args[IPSET_CB_PRIVATE] = (unsigned long)t;
1338 		rcu_read_unlock_bh();
1339 	} else if (cb->args[IPSET_CB_PRIVATE]) {
1340 		t = (struct htable *)cb->args[IPSET_CB_PRIVATE];
1341 		if (atomic_dec_and_test(&t->uref) && atomic_read(&t->ref)) {
1342 			pr_debug("Table destroy after resize "
1343 				 " by dump: %p\n", t);
1344 			mtype_ahash_destroy(set, t, false);
1345 		}
1346 		cb->args[IPSET_CB_PRIVATE] = 0;
1347 	}
1348 }
1349 
1350 /* Reply a LIST/SAVE request: dump the elements of the specified set */
1351 static int
mtype_list(const struct ip_set * set,struct sk_buff * skb,struct netlink_callback * cb)1352 mtype_list(const struct ip_set *set,
1353 	   struct sk_buff *skb, struct netlink_callback *cb)
1354 {
1355 	const struct htable *t;
1356 	struct nlattr *atd, *nested;
1357 	const struct hbucket *n;
1358 	const struct mtype_elem *e;
1359 	u32 first = cb->args[IPSET_CB_ARG0];
1360 	/* We assume that one hash bucket fills into one page */
1361 	void *incomplete;
1362 	int i, ret = 0;
1363 
1364 	atd = nla_nest_start(skb, IPSET_ATTR_ADT);
1365 	if (!atd)
1366 		return -EMSGSIZE;
1367 
1368 	pr_debug("list hash set %s\n", set->name);
1369 	t = (const struct htable *)cb->args[IPSET_CB_PRIVATE];
1370 	/* Expire may replace a hbucket with another one */
1371 	rcu_read_lock();
1372 	for (; cb->args[IPSET_CB_ARG0] < jhash_size(t->htable_bits);
1373 	     cb->args[IPSET_CB_ARG0]++) {
1374 		cond_resched_rcu();
1375 		incomplete = skb_tail_pointer(skb);
1376 		n = rcu_dereference(hbucket(t, cb->args[IPSET_CB_ARG0]));
1377 		pr_debug("cb->arg bucket: %lu, t %p n %p\n",
1378 			 cb->args[IPSET_CB_ARG0], t, n);
1379 		if (!n)
1380 			continue;
1381 		for (i = 0; i < n->pos; i++) {
1382 			if (!test_bit(i, n->used))
1383 				continue;
1384 			e = ahash_data(n, i, set->dsize);
1385 			if (SET_ELEM_EXPIRED(set, e))
1386 				continue;
1387 			pr_debug("list hash %lu hbucket %p i %u, data %p\n",
1388 				 cb->args[IPSET_CB_ARG0], n, i, e);
1389 			nested = nla_nest_start(skb, IPSET_ATTR_DATA);
1390 			if (!nested) {
1391 				if (cb->args[IPSET_CB_ARG0] == first) {
1392 					nla_nest_cancel(skb, atd);
1393 					ret = -EMSGSIZE;
1394 					goto out;
1395 				}
1396 				goto nla_put_failure;
1397 			}
1398 			if (mtype_data_list(skb, e))
1399 				goto nla_put_failure;
1400 			if (ip_set_put_extensions(skb, set, e, true))
1401 				goto nla_put_failure;
1402 			nla_nest_end(skb, nested);
1403 		}
1404 	}
1405 	nla_nest_end(skb, atd);
1406 	/* Set listing finished */
1407 	cb->args[IPSET_CB_ARG0] = 0;
1408 
1409 	goto out;
1410 
1411 nla_put_failure:
1412 	nlmsg_trim(skb, incomplete);
1413 	if (unlikely(first == cb->args[IPSET_CB_ARG0])) {
1414 		pr_warn("Can't list set %s: one bucket does not fit into a message. Please report it!\n",
1415 			set->name);
1416 		cb->args[IPSET_CB_ARG0] = 0;
1417 		ret = -EMSGSIZE;
1418 	} else {
1419 		nla_nest_end(skb, atd);
1420 	}
1421 out:
1422 	rcu_read_unlock();
1423 	return ret;
1424 }
1425 
1426 static int
1427 IPSET_TOKEN(MTYPE, _kadt)(struct ip_set *set, const struct sk_buff *skb,
1428 			  const struct xt_action_param *par,
1429 			  enum ipset_adt adt, struct ip_set_adt_opt *opt);
1430 
1431 static int
1432 IPSET_TOKEN(MTYPE, _uadt)(struct ip_set *set, struct nlattr *tb[],
1433 			  enum ipset_adt adt, u32 *lineno, u32 flags,
1434 			  bool retried);
1435 
1436 static const struct ip_set_type_variant mtype_variant = {
1437 	.kadt	= mtype_kadt,
1438 	.uadt	= mtype_uadt,
1439 	.adt	= {
1440 		[IPSET_ADD] = mtype_add,
1441 		[IPSET_DEL] = mtype_del,
1442 		[IPSET_TEST] = mtype_test,
1443 	},
1444 	.destroy = mtype_destroy,
1445 	.flush	= mtype_flush,
1446 	.head	= mtype_head,
1447 	.list	= mtype_list,
1448 	.uref	= mtype_uref,
1449 	.resize	= mtype_resize,
1450 	.same_set = mtype_same_set,
1451 	.cancel_gc = mtype_cancel_gc,
1452 	.region_lock = true,
1453 };
1454 
1455 #ifdef IP_SET_EMIT_CREATE
1456 static int
IPSET_TOKEN(HTYPE,_create)1457 IPSET_TOKEN(HTYPE, _create)(struct net *net, struct ip_set *set,
1458 			    struct nlattr *tb[], u32 flags)
1459 {
1460 	u32 hashsize = IPSET_DEFAULT_HASHSIZE, maxelem = IPSET_DEFAULT_MAXELEM;
1461 #ifdef IP_SET_HASH_WITH_MARKMASK
1462 	u32 markmask;
1463 #endif
1464 	u8 hbits;
1465 #if defined(IP_SET_HASH_WITH_NETMASK) || defined(IP_SET_HASH_WITH_BITMASK)
1466 	int ret __attribute__((unused)) = 0;
1467 	u8 netmask = set->family == NFPROTO_IPV4 ? 32 : 128;
1468 	union nf_inet_addr bitmask = onesmask;
1469 #endif
1470 	size_t hsize;
1471 	struct htype *h;
1472 	struct htable *t;
1473 	u32 i;
1474 
1475 	pr_debug("Create set %s with family %s\n",
1476 		 set->name, set->family == NFPROTO_IPV4 ? "inet" : "inet6");
1477 
1478 #ifdef IP_SET_PROTO_UNDEF
1479 	if (set->family != NFPROTO_UNSPEC)
1480 		return -IPSET_ERR_INVALID_FAMILY;
1481 #else
1482 	if (!(set->family == NFPROTO_IPV4 || set->family == NFPROTO_IPV6))
1483 		return -IPSET_ERR_INVALID_FAMILY;
1484 #endif
1485 
1486 	if (unlikely(!ip_set_optattr_netorder(tb, IPSET_ATTR_HASHSIZE) ||
1487 		     !ip_set_optattr_netorder(tb, IPSET_ATTR_MAXELEM) ||
1488 		     !ip_set_optattr_netorder(tb, IPSET_ATTR_TIMEOUT) ||
1489 		     !ip_set_optattr_netorder(tb, IPSET_ATTR_CADT_FLAGS)))
1490 		return -IPSET_ERR_PROTOCOL;
1491 
1492 #ifdef IP_SET_HASH_WITH_MARKMASK
1493 	/* Separated condition in order to avoid directive in argument list */
1494 	if (unlikely(!ip_set_optattr_netorder(tb, IPSET_ATTR_MARKMASK)))
1495 		return -IPSET_ERR_PROTOCOL;
1496 
1497 	markmask = 0xffffffff;
1498 	if (tb[IPSET_ATTR_MARKMASK]) {
1499 		markmask = ntohl(nla_get_be32(tb[IPSET_ATTR_MARKMASK]));
1500 		if (markmask == 0)
1501 			return -IPSET_ERR_INVALID_MARKMASK;
1502 	}
1503 #endif
1504 
1505 #ifdef IP_SET_HASH_WITH_NETMASK
1506 	if (tb[IPSET_ATTR_NETMASK]) {
1507 		netmask = nla_get_u8(tb[IPSET_ATTR_NETMASK]);
1508 
1509 		if ((set->family == NFPROTO_IPV4 && netmask > 32) ||
1510 		    (set->family == NFPROTO_IPV6 && netmask > 128) ||
1511 		    netmask == 0)
1512 			return -IPSET_ERR_INVALID_NETMASK;
1513 
1514 		/* we convert netmask to bitmask and store it */
1515 		if (set->family == NFPROTO_IPV4)
1516 			bitmask.ip = ip_set_netmask(netmask);
1517 		else
1518 			ip6_netmask(&bitmask, netmask);
1519 	}
1520 #endif
1521 
1522 #ifdef IP_SET_HASH_WITH_BITMASK
1523 	if (tb[IPSET_ATTR_BITMASK]) {
1524 		/* bitmask and netmask do the same thing, allow only one of these options */
1525 		if (tb[IPSET_ATTR_NETMASK])
1526 			return -IPSET_ERR_BITMASK_NETMASK_EXCL;
1527 
1528 		if (set->family == NFPROTO_IPV4) {
1529 			ret = ip_set_get_ipaddr4(tb[IPSET_ATTR_BITMASK], &bitmask.ip);
1530 			if (ret || !bitmask.ip)
1531 				return -IPSET_ERR_INVALID_NETMASK;
1532 		} else if (set->family == NFPROTO_IPV6) {
1533 			ret = ip_set_get_ipaddr6(tb[IPSET_ATTR_BITMASK], &bitmask);
1534 			if (ret || ipv6_addr_any(&bitmask.in6))
1535 				return -IPSET_ERR_INVALID_NETMASK;
1536 		}
1537 
1538 		if (nf_inet_addr_cmp(&bitmask, &zeromask))
1539 			return -IPSET_ERR_INVALID_NETMASK;
1540 	}
1541 #endif
1542 
1543 	if (tb[IPSET_ATTR_HASHSIZE]) {
1544 		hashsize = ip_set_get_h32(tb[IPSET_ATTR_HASHSIZE]);
1545 		if (hashsize < IPSET_MIMINAL_HASHSIZE)
1546 			hashsize = IPSET_MIMINAL_HASHSIZE;
1547 	}
1548 
1549 	if (tb[IPSET_ATTR_MAXELEM])
1550 		maxelem = ip_set_get_h32(tb[IPSET_ATTR_MAXELEM]);
1551 
1552 	hsize = sizeof(*h);
1553 	h = kzalloc(hsize, GFP_KERNEL);
1554 	if (!h)
1555 		return -ENOMEM;
1556 
1557 	/* Compute htable_bits from the user input parameter hashsize.
1558 	 * Assume that hashsize == 2^htable_bits,
1559 	 * otherwise round up to the first 2^n value.
1560 	 */
1561 	hbits = fls(hashsize - 1);
1562 	hsize = htable_size(hbits);
1563 	if (hsize == 0) {
1564 		kfree(h);
1565 		return -ENOMEM;
1566 	}
1567 	t = ip_set_alloc(hsize);
1568 	if (!t) {
1569 		kfree(h);
1570 		return -ENOMEM;
1571 	}
1572 	t->hregion = ip_set_alloc(ahash_sizeof_regions(hbits));
1573 	if (!t->hregion) {
1574 		ip_set_free(t);
1575 		kfree(h);
1576 		return -ENOMEM;
1577 	}
1578 	h->gc.set = set;
1579 	for (i = 0; i < ahash_numof_locks(hbits); i++)
1580 		spin_lock_init(&t->hregion[i].lock);
1581 	h->maxelem = maxelem;
1582 #if defined(IP_SET_HASH_WITH_NETMASK) || defined(IP_SET_HASH_WITH_BITMASK)
1583 	h->bitmask = bitmask;
1584 	h->netmask = netmask;
1585 #endif
1586 #ifdef IP_SET_HASH_WITH_MARKMASK
1587 	h->markmask = markmask;
1588 #endif
1589 	if (tb[IPSET_ATTR_INITVAL])
1590 		h->initval = ntohl(nla_get_be32(tb[IPSET_ATTR_INITVAL]));
1591 	else
1592 		get_random_bytes(&h->initval, sizeof(h->initval));
1593 	h->bucketsize = AHASH_MAX_SIZE;
1594 	if (tb[IPSET_ATTR_BUCKETSIZE]) {
1595 		h->bucketsize = nla_get_u8(tb[IPSET_ATTR_BUCKETSIZE]);
1596 		if (h->bucketsize < AHASH_INIT_SIZE)
1597 			h->bucketsize = AHASH_INIT_SIZE;
1598 		else if (h->bucketsize > AHASH_MAX_SIZE)
1599 			h->bucketsize = AHASH_MAX_SIZE;
1600 		else if (h->bucketsize % 2)
1601 			h->bucketsize += 1;
1602 	}
1603 	t->htable_bits = hbits;
1604 	t->maxelem = h->maxelem / ahash_numof_locks(hbits);
1605 	RCU_INIT_POINTER(h->table, t);
1606 
1607 	INIT_LIST_HEAD(&h->ad);
1608 	set->data = h;
1609 #ifndef IP_SET_PROTO_UNDEF
1610 	if (set->family == NFPROTO_IPV4) {
1611 #endif
1612 		set->variant = &IPSET_TOKEN(HTYPE, 4_variant);
1613 		set->dsize = ip_set_elem_len(set, tb,
1614 			sizeof(struct IPSET_TOKEN(HTYPE, 4_elem)),
1615 			__alignof__(struct IPSET_TOKEN(HTYPE, 4_elem)));
1616 #ifndef IP_SET_PROTO_UNDEF
1617 	} else {
1618 		set->variant = &IPSET_TOKEN(HTYPE, 6_variant);
1619 		set->dsize = ip_set_elem_len(set, tb,
1620 			sizeof(struct IPSET_TOKEN(HTYPE, 6_elem)),
1621 			__alignof__(struct IPSET_TOKEN(HTYPE, 6_elem)));
1622 	}
1623 #endif
1624 	set->timeout = IPSET_NO_TIMEOUT;
1625 	if (tb[IPSET_ATTR_TIMEOUT]) {
1626 		set->timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
1627 #ifndef IP_SET_PROTO_UNDEF
1628 		if (set->family == NFPROTO_IPV4)
1629 #endif
1630 			IPSET_TOKEN(HTYPE, 4_gc_init)(&h->gc);
1631 #ifndef IP_SET_PROTO_UNDEF
1632 		else
1633 			IPSET_TOKEN(HTYPE, 6_gc_init)(&h->gc);
1634 #endif
1635 	}
1636 	pr_debug("create %s hashsize %u (%u) maxelem %u: %p(%p)\n",
1637 		 set->name, jhash_size(t->htable_bits),
1638 		 t->htable_bits, h->maxelem, set->data, t);
1639 
1640 	return 0;
1641 }
1642 #endif /* IP_SET_EMIT_CREATE */
1643 
1644 #undef HKEY_DATALEN
1645