xref: /freebsd/sys/netpfil/ipfw/ip_fw_dynamic.c (revision 22cf89c938886d14f5796fc49f9f020c23ea8eaf)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2017-2018 Yandex LLC
5  * Copyright (c) 2017-2018 Andrey V. Elsukov <ae@FreeBSD.org>
6  * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_ipfw.h"
34 #ifndef INET
35 #error IPFIREWALL requires INET.
36 #endif /* INET */
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/hash.h>
41 #include <sys/mbuf.h>
42 #include <sys/kernel.h>
43 #include <sys/lock.h>
44 #include <sys/pcpu.h>
45 #include <sys/queue.h>
46 #include <sys/rmlock.h>
47 #include <sys/smp.h>
48 #include <sys/socket.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <net/ethernet.h>
52 #include <net/if.h>
53 #include <net/if_var.h>
54 #include <net/vnet.h>
55 
56 #include <netinet/in.h>
57 #include <netinet/ip.h>
58 #include <netinet/ip_var.h>
59 #include <netinet/ip_fw.h>
60 #include <netinet/udp.h>
61 #include <netinet/tcp.h>
62 
63 #include <netinet/ip6.h>	/* IN6_ARE_ADDR_EQUAL */
64 #ifdef INET6
65 #include <netinet6/in6_var.h>
66 #include <netinet6/ip6_var.h>
67 #include <netinet6/scope6_var.h>
68 #endif
69 
70 #include <netpfil/ipfw/ip_fw_private.h>
71 
72 #include <machine/in_cksum.h>	/* XXX for in_cksum */
73 
74 #ifdef MAC
75 #include <security/mac/mac_framework.h>
76 #endif
77 
78 /*
79  * Description of dynamic states.
80  *
81  * Dynamic states are stored in lists accessed through a hash tables
82  * whose size is curr_dyn_buckets. This value can be modified through
83  * the sysctl variable dyn_buckets.
84  *
85  * Currently there are four tables: dyn_ipv4, dyn_ipv6, dyn_ipv4_parent,
86  * and dyn_ipv6_parent.
87  *
88  * When a packet is received, its address fields hashed, then matched
89  * against the entries in the corresponding list by addr_type.
90  * Dynamic states can be used for different purposes:
91  *  + stateful rules;
92  *  + enforcing limits on the number of sessions;
93  *  + in-kernel NAT (not implemented yet)
94  *
95  * The lifetime of dynamic states is regulated by dyn_*_lifetime,
96  * measured in seconds and depending on the flags.
97  *
98  * The total number of dynamic states is equal to UMA zone items count.
99  * The max number of dynamic states is dyn_max. When we reach
100  * the maximum number of rules we do not create anymore. This is
101  * done to avoid consuming too much memory, but also too much
102  * time when searching on each packet (ideally, we should try instead
103  * to put a limit on the length of the list on each bucket...).
104  *
105  * Each state holds a pointer to the parent ipfw rule so we know what
106  * action to perform. Dynamic rules are removed when the parent rule is
107  * deleted.
108  *
109  * There are some limitations with dynamic rules -- we do not
110  * obey the 'randomized match', and we do not do multiple
111  * passes through the firewall. XXX check the latter!!!
112  */
113 
114 /* By default use jenkins hash function */
115 #define	IPFIREWALL_JENKINSHASH
116 
117 #define	DYN_COUNTER_INC(d, dir, pktlen)	do {	\
118 	(d)->pcnt_ ## dir++;			\
119 	(d)->bcnt_ ## dir += pktlen;		\
120 	} while (0)
121 
122 #define	DYN_REFERENCED		0x01
123 /*
124  * DYN_REFERENCED flag is used to show that state keeps reference to named
125  * object, and this reference should be released when state becomes expired.
126  */
127 
128 struct dyn_data {
129 	void		*parent;	/* pointer to parent rule */
130 	uint32_t	chain_id;	/* cached ruleset id */
131 	uint32_t	f_pos;		/* cached rule index */
132 
133 	uint32_t	hashval;	/* hash value used for hash resize */
134 	uint16_t	fibnum;		/* fib used to send keepalives */
135 	uint8_t		_pad[3];
136 	uint8_t		flags;		/* internal flags */
137 	uint16_t	rulenum;	/* parent rule number */
138 	uint32_t	ruleid;		/* parent rule id */
139 
140 	uint32_t	state;		/* TCP session state and flags */
141 	uint32_t	ack_fwd;	/* most recent ACKs in forward */
142 	uint32_t	ack_rev;	/* and reverse direction (used */
143 					/* to generate keepalives) */
144 	uint32_t	sync;		/* synchronization time */
145 	uint32_t	expire;		/* expire time */
146 
147 	uint64_t	pcnt_fwd;	/* bytes counter in forward */
148 	uint64_t	bcnt_fwd;	/* packets counter in forward */
149 	uint64_t	pcnt_rev;	/* bytes counter in reverse */
150 	uint64_t	bcnt_rev;	/* packets counter in reverse */
151 };
152 
153 #define	DPARENT_COUNT_DEC(p)	do {			\
154 	MPASS(p->count > 0);				\
155 	ck_pr_dec_32(&(p)->count);			\
156 } while (0)
157 #define	DPARENT_COUNT_INC(p)	ck_pr_inc_32(&(p)->count)
158 #define	DPARENT_COUNT(p)	ck_pr_load_32(&(p)->count)
159 struct dyn_parent {
160 	void		*parent;	/* pointer to parent rule */
161 	uint32_t	count;		/* number of linked states */
162 	uint8_t		_pad[2];
163 	uint16_t	rulenum;	/* parent rule number */
164 	uint32_t	ruleid;		/* parent rule id */
165 	uint32_t	hashval;	/* hash value used for hash resize */
166 	uint32_t	expire;		/* expire time */
167 };
168 
169 struct dyn_ipv4_state {
170 	uint8_t		type;		/* State type */
171 	uint8_t		proto;		/* UL Protocol */
172 	uint16_t	kidx;		/* named object index */
173 	uint16_t	sport, dport;	/* ULP source and destination ports */
174 	in_addr_t	src, dst;	/* IPv4 source and destination */
175 
176 	union {
177 		struct dyn_data	*data;
178 		struct dyn_parent *limit;
179 	};
180 	CK_SLIST_ENTRY(dyn_ipv4_state)	entry;
181 	SLIST_ENTRY(dyn_ipv4_state)	expired;
182 };
183 CK_SLIST_HEAD(dyn_ipv4ck_slist, dyn_ipv4_state);
184 VNET_DEFINE_STATIC(struct dyn_ipv4ck_slist *, dyn_ipv4);
185 VNET_DEFINE_STATIC(struct dyn_ipv4ck_slist *, dyn_ipv4_parent);
186 
187 SLIST_HEAD(dyn_ipv4_slist, dyn_ipv4_state);
188 VNET_DEFINE_STATIC(struct dyn_ipv4_slist, dyn_expired_ipv4);
189 #define	V_dyn_ipv4			VNET(dyn_ipv4)
190 #define	V_dyn_ipv4_parent		VNET(dyn_ipv4_parent)
191 #define	V_dyn_expired_ipv4		VNET(dyn_expired_ipv4)
192 
193 #ifdef INET6
194 struct dyn_ipv6_state {
195 	uint8_t		type;		/* State type */
196 	uint8_t		proto;		/* UL Protocol */
197 	uint16_t	kidx;		/* named object index */
198 	uint16_t	sport, dport;	/* ULP source and destination ports */
199 	struct in6_addr	src, dst;	/* IPv6 source and destination */
200 	uint32_t	zoneid;		/* IPv6 scope zone id */
201 	union {
202 		struct dyn_data	*data;
203 		struct dyn_parent *limit;
204 	};
205 	CK_SLIST_ENTRY(dyn_ipv6_state)	entry;
206 	SLIST_ENTRY(dyn_ipv6_state)	expired;
207 };
208 CK_SLIST_HEAD(dyn_ipv6ck_slist, dyn_ipv6_state);
209 VNET_DEFINE_STATIC(struct dyn_ipv6ck_slist *, dyn_ipv6);
210 VNET_DEFINE_STATIC(struct dyn_ipv6ck_slist *, dyn_ipv6_parent);
211 
212 SLIST_HEAD(dyn_ipv6_slist, dyn_ipv6_state);
213 VNET_DEFINE_STATIC(struct dyn_ipv6_slist, dyn_expired_ipv6);
214 #define	V_dyn_ipv6			VNET(dyn_ipv6)
215 #define	V_dyn_ipv6_parent		VNET(dyn_ipv6_parent)
216 #define	V_dyn_expired_ipv6		VNET(dyn_expired_ipv6)
217 #endif /* INET6 */
218 
219 /*
220  * Per-CPU pointer indicates that specified state is currently in use
221  * and must not be reclaimed by expiration callout.
222  */
223 static void **dyn_hp_cache;
224 DPCPU_DEFINE_STATIC(void *, dyn_hp);
225 #define	DYNSTATE_GET(cpu)	ck_pr_load_ptr(DPCPU_ID_PTR((cpu), dyn_hp))
226 #define	DYNSTATE_PROTECT(v)	ck_pr_store_ptr(DPCPU_PTR(dyn_hp), (v))
227 #define	DYNSTATE_RELEASE()	DYNSTATE_PROTECT(NULL)
228 #define	DYNSTATE_CRITICAL_ENTER()	critical_enter()
229 #define	DYNSTATE_CRITICAL_EXIT()	do {	\
230 	DYNSTATE_RELEASE();			\
231 	critical_exit();			\
232 } while (0);
233 
234 /*
235  * We keep two version numbers, one is updated when new entry added to
236  * the list. Second is updated when an entry deleted from the list.
237  * Versions are updated under bucket lock.
238  *
239  * Bucket "add" version number is used to know, that in the time between
240  * state lookup (i.e. ipfw_dyn_lookup_state()) and the followed state
241  * creation (i.e. ipfw_dyn_install_state()) another concurrent thread did
242  * not install some state in this bucket. Using this info we can avoid
243  * additional state lookup, because we are sure that we will not install
244  * the state twice.
245  *
246  * Also doing the tracking of bucket "del" version during lookup we can
247  * be sure, that state entry was not unlinked and freed in time between
248  * we read the state pointer and protect it with hazard pointer.
249  *
250  * An entry unlinked from CK list keeps unchanged until it is freed.
251  * Unlinked entries are linked into expired lists using "expired" field.
252  */
253 
254 /*
255  * dyn_expire_lock is used to protect access to dyn_expired_xxx lists.
256  * dyn_bucket_lock is used to get write access to lists in specific bucket.
257  * Currently one dyn_bucket_lock is used for all ipv4, ipv4_parent, ipv6,
258  * and ipv6_parent lists.
259  */
260 VNET_DEFINE_STATIC(struct mtx, dyn_expire_lock);
261 VNET_DEFINE_STATIC(struct mtx *, dyn_bucket_lock);
262 #define	V_dyn_expire_lock		VNET(dyn_expire_lock)
263 #define	V_dyn_bucket_lock		VNET(dyn_bucket_lock)
264 
265 /*
266  * Bucket's add/delete generation versions.
267  */
268 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv4_add);
269 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv4_del);
270 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv4_parent_add);
271 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv4_parent_del);
272 #define	V_dyn_ipv4_add			VNET(dyn_ipv4_add)
273 #define	V_dyn_ipv4_del			VNET(dyn_ipv4_del)
274 #define	V_dyn_ipv4_parent_add		VNET(dyn_ipv4_parent_add)
275 #define	V_dyn_ipv4_parent_del		VNET(dyn_ipv4_parent_del)
276 
277 #ifdef INET6
278 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv6_add);
279 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv6_del);
280 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv6_parent_add);
281 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv6_parent_del);
282 #define	V_dyn_ipv6_add			VNET(dyn_ipv6_add)
283 #define	V_dyn_ipv6_del			VNET(dyn_ipv6_del)
284 #define	V_dyn_ipv6_parent_add		VNET(dyn_ipv6_parent_add)
285 #define	V_dyn_ipv6_parent_del		VNET(dyn_ipv6_parent_del)
286 #endif /* INET6 */
287 
288 #define	DYN_BUCKET(h, b)		((h) & (b - 1))
289 #define	DYN_BUCKET_VERSION(b, v)	ck_pr_load_32(&V_dyn_ ## v[(b)])
290 #define	DYN_BUCKET_VERSION_BUMP(b, v)	ck_pr_inc_32(&V_dyn_ ## v[(b)])
291 
292 #define	DYN_BUCKET_LOCK_INIT(lock, b)		\
293     mtx_init(&lock[(b)], "IPFW dynamic bucket", NULL, MTX_DEF)
294 #define	DYN_BUCKET_LOCK_DESTROY(lock, b)	mtx_destroy(&lock[(b)])
295 #define	DYN_BUCKET_LOCK(b)	mtx_lock(&V_dyn_bucket_lock[(b)])
296 #define	DYN_BUCKET_UNLOCK(b)	mtx_unlock(&V_dyn_bucket_lock[(b)])
297 #define	DYN_BUCKET_ASSERT(b)	mtx_assert(&V_dyn_bucket_lock[(b)], MA_OWNED)
298 
299 #define	DYN_EXPIRED_LOCK_INIT()		\
300     mtx_init(&V_dyn_expire_lock, "IPFW expired states list", NULL, MTX_DEF)
301 #define	DYN_EXPIRED_LOCK_DESTROY()	mtx_destroy(&V_dyn_expire_lock)
302 #define	DYN_EXPIRED_LOCK()		mtx_lock(&V_dyn_expire_lock)
303 #define	DYN_EXPIRED_UNLOCK()		mtx_unlock(&V_dyn_expire_lock)
304 
305 VNET_DEFINE_STATIC(uint32_t, dyn_buckets_max);
306 VNET_DEFINE_STATIC(uint32_t, curr_dyn_buckets);
307 VNET_DEFINE_STATIC(struct callout, dyn_timeout);
308 #define	V_dyn_buckets_max		VNET(dyn_buckets_max)
309 #define	V_curr_dyn_buckets		VNET(curr_dyn_buckets)
310 #define	V_dyn_timeout			VNET(dyn_timeout)
311 
312 /* Maximum length of states chain in a bucket */
313 VNET_DEFINE_STATIC(uint32_t, curr_max_length);
314 #define	V_curr_max_length		VNET(curr_max_length)
315 
316 VNET_DEFINE_STATIC(uint32_t, dyn_keep_states);
317 #define	V_dyn_keep_states		VNET(dyn_keep_states)
318 
319 VNET_DEFINE_STATIC(uma_zone_t, dyn_data_zone);
320 VNET_DEFINE_STATIC(uma_zone_t, dyn_parent_zone);
321 VNET_DEFINE_STATIC(uma_zone_t, dyn_ipv4_zone);
322 #ifdef INET6
323 VNET_DEFINE_STATIC(uma_zone_t, dyn_ipv6_zone);
324 #define	V_dyn_ipv6_zone			VNET(dyn_ipv6_zone)
325 #endif /* INET6 */
326 #define	V_dyn_data_zone			VNET(dyn_data_zone)
327 #define	V_dyn_parent_zone		VNET(dyn_parent_zone)
328 #define	V_dyn_ipv4_zone			VNET(dyn_ipv4_zone)
329 
330 /*
331  * Timeouts for various events in handing dynamic rules.
332  */
333 VNET_DEFINE_STATIC(uint32_t, dyn_ack_lifetime);
334 VNET_DEFINE_STATIC(uint32_t, dyn_syn_lifetime);
335 VNET_DEFINE_STATIC(uint32_t, dyn_fin_lifetime);
336 VNET_DEFINE_STATIC(uint32_t, dyn_rst_lifetime);
337 VNET_DEFINE_STATIC(uint32_t, dyn_udp_lifetime);
338 VNET_DEFINE_STATIC(uint32_t, dyn_short_lifetime);
339 
340 #define	V_dyn_ack_lifetime		VNET(dyn_ack_lifetime)
341 #define	V_dyn_syn_lifetime		VNET(dyn_syn_lifetime)
342 #define	V_dyn_fin_lifetime		VNET(dyn_fin_lifetime)
343 #define	V_dyn_rst_lifetime		VNET(dyn_rst_lifetime)
344 #define	V_dyn_udp_lifetime		VNET(dyn_udp_lifetime)
345 #define	V_dyn_short_lifetime		VNET(dyn_short_lifetime)
346 
347 /*
348  * Keepalives are sent if dyn_keepalive is set. They are sent every
349  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
350  * seconds of lifetime of a rule.
351  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
352  * than dyn_keepalive_period.
353  */
354 VNET_DEFINE_STATIC(uint32_t, dyn_keepalive_interval);
355 VNET_DEFINE_STATIC(uint32_t, dyn_keepalive_period);
356 VNET_DEFINE_STATIC(uint32_t, dyn_keepalive);
357 VNET_DEFINE_STATIC(time_t, dyn_keepalive_last);
358 
359 #define	V_dyn_keepalive_interval	VNET(dyn_keepalive_interval)
360 #define	V_dyn_keepalive_period		VNET(dyn_keepalive_period)
361 #define	V_dyn_keepalive			VNET(dyn_keepalive)
362 #define	V_dyn_keepalive_last		VNET(dyn_keepalive_last)
363 
364 VNET_DEFINE_STATIC(uint32_t, dyn_max);		/* max # of dynamic states */
365 VNET_DEFINE_STATIC(uint32_t, dyn_count);	/* number of states */
366 VNET_DEFINE_STATIC(uint32_t, dyn_parent_max);	/* max # of parent states */
367 VNET_DEFINE_STATIC(uint32_t, dyn_parent_count);	/* number of parent states */
368 
369 #define	V_dyn_max			VNET(dyn_max)
370 #define	V_dyn_count			VNET(dyn_count)
371 #define	V_dyn_parent_max		VNET(dyn_parent_max)
372 #define	V_dyn_parent_count		VNET(dyn_parent_count)
373 
374 #define	DYN_COUNT_DEC(name)	do {			\
375 	MPASS((V_ ## name) > 0);			\
376 	ck_pr_dec_32(&(V_ ## name));			\
377 } while (0)
378 #define	DYN_COUNT_INC(name)	ck_pr_inc_32(&(V_ ## name))
379 #define	DYN_COUNT(name)		ck_pr_load_32(&(V_ ## name))
380 
381 static time_t last_log;	/* Log ratelimiting */
382 
383 /*
384  * Get/set maximum number of dynamic states in given VNET instance.
385  */
386 static int
387 sysctl_dyn_max(SYSCTL_HANDLER_ARGS)
388 {
389 	uint32_t nstates;
390 	int error;
391 
392 	nstates = V_dyn_max;
393 	error = sysctl_handle_32(oidp, &nstates, 0, req);
394 	/* Read operation or some error */
395 	if ((error != 0) || (req->newptr == NULL))
396 		return (error);
397 
398 	V_dyn_max = nstates;
399 	uma_zone_set_max(V_dyn_data_zone, V_dyn_max);
400 	return (0);
401 }
402 
403 static int
404 sysctl_dyn_parent_max(SYSCTL_HANDLER_ARGS)
405 {
406 	uint32_t nstates;
407 	int error;
408 
409 	nstates = V_dyn_parent_max;
410 	error = sysctl_handle_32(oidp, &nstates, 0, req);
411 	/* Read operation or some error */
412 	if ((error != 0) || (req->newptr == NULL))
413 		return (error);
414 
415 	V_dyn_parent_max = nstates;
416 	uma_zone_set_max(V_dyn_parent_zone, V_dyn_parent_max);
417 	return (0);
418 }
419 
420 static int
421 sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
422 {
423 	uint32_t nbuckets;
424 	int error;
425 
426 	nbuckets = V_dyn_buckets_max;
427 	error = sysctl_handle_32(oidp, &nbuckets, 0, req);
428 	/* Read operation or some error */
429 	if ((error != 0) || (req->newptr == NULL))
430 		return (error);
431 
432 	if (nbuckets > 256)
433 		V_dyn_buckets_max = 1 << fls(nbuckets - 1);
434 	else
435 		return (EINVAL);
436 	return (0);
437 }
438 
439 SYSCTL_DECL(_net_inet_ip_fw);
440 
441 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_count,
442     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
443     "Current number of dynamic states.");
444 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_parent_count,
445     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(dyn_parent_count), 0,
446     "Current number of parent states. ");
447 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
448     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
449     "Current number of buckets for states hash table.");
450 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, curr_max_length,
451     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(curr_max_length), 0,
452     "Current maximum length of states chains in hash buckets.");
453 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
454     CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
455     0, 0, sysctl_dyn_buckets, "IU",
456     "Max number of buckets for dynamic states hash table.");
457 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_max,
458     CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
459     0, 0, sysctl_dyn_max, "IU",
460     "Max number of dynamic states.");
461 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_parent_max,
462     CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW | CTLFLAG_NEEDGIANT,
463     0, 0, sysctl_dyn_parent_max, "IU",
464     "Max number of parent dynamic states.");
465 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
466     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
467     "Lifetime of dynamic states for TCP ACK.");
468 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
469     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
470     "Lifetime of dynamic states for TCP SYN.");
471 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
472     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
473     "Lifetime of dynamic states for TCP FIN.");
474 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
475     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
476     "Lifetime of dynamic states for TCP RST.");
477 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
478     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
479     "Lifetime of dynamic states for UDP.");
480 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
481     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
482     "Lifetime of dynamic states for other situations.");
483 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
484     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
485     "Enable keepalives for dynamic states.");
486 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_keep_states,
487     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_keep_states), 0,
488     "Do not flush dynamic states on rule deletion");
489 
490 #ifdef IPFIREWALL_DYNDEBUG
491 #define	DYN_DEBUG(fmt, ...)	do {			\
492 	printf("%s: " fmt "\n", __func__, __VA_ARGS__);	\
493 } while (0)
494 #else
495 #define	DYN_DEBUG(fmt, ...)
496 #endif /* !IPFIREWALL_DYNDEBUG */
497 
498 #ifdef INET6
499 /* Functions to work with IPv6 states */
500 static struct dyn_ipv6_state *dyn_lookup_ipv6_state(
501     const struct ipfw_flow_id *, uint32_t, const void *,
502     struct ipfw_dyn_info *, int);
503 static int dyn_lookup_ipv6_state_locked(const struct ipfw_flow_id *,
504     uint32_t, const void *, int, uint32_t, uint16_t);
505 static struct dyn_ipv6_state *dyn_alloc_ipv6_state(
506     const struct ipfw_flow_id *, uint32_t, uint16_t, uint8_t);
507 static int dyn_add_ipv6_state(void *, uint32_t, uint16_t,
508     const struct ipfw_flow_id *, uint32_t, const void *, int, uint32_t,
509     struct ipfw_dyn_info *, uint16_t, uint16_t, uint8_t);
510 static void dyn_export_ipv6_state(const struct dyn_ipv6_state *,
511     ipfw_dyn_rule *);
512 
513 static uint32_t dyn_getscopeid(const struct ip_fw_args *);
514 static void dyn_make_keepalive_ipv6(struct mbuf *, const struct in6_addr *,
515     const struct in6_addr *, uint32_t, uint32_t, uint32_t, uint16_t,
516     uint16_t);
517 static void dyn_enqueue_keepalive_ipv6(struct mbufq *,
518     const struct dyn_ipv6_state *);
519 static void dyn_send_keepalive_ipv6(struct ip_fw_chain *);
520 
521 static struct dyn_ipv6_state *dyn_lookup_ipv6_parent(
522     const struct ipfw_flow_id *, uint32_t, const void *, uint32_t, uint16_t,
523     uint32_t);
524 static struct dyn_ipv6_state *dyn_lookup_ipv6_parent_locked(
525     const struct ipfw_flow_id *, uint32_t, const void *, uint32_t, uint16_t,
526     uint32_t);
527 static struct dyn_ipv6_state *dyn_add_ipv6_parent(void *, uint32_t, uint16_t,
528     const struct ipfw_flow_id *, uint32_t, uint32_t, uint32_t, uint16_t);
529 #endif /* INET6 */
530 
531 /* Functions to work with limit states */
532 static void *dyn_get_parent_state(const struct ipfw_flow_id *, uint32_t,
533     struct ip_fw *, uint32_t, uint32_t, uint16_t);
534 static struct dyn_ipv4_state *dyn_lookup_ipv4_parent(
535     const struct ipfw_flow_id *, const void *, uint32_t, uint16_t, uint32_t);
536 static struct dyn_ipv4_state *dyn_lookup_ipv4_parent_locked(
537     const struct ipfw_flow_id *, const void *, uint32_t, uint16_t, uint32_t);
538 static struct dyn_parent *dyn_alloc_parent(void *, uint32_t, uint16_t,
539     uint32_t);
540 static struct dyn_ipv4_state *dyn_add_ipv4_parent(void *, uint32_t, uint16_t,
541     const struct ipfw_flow_id *, uint32_t, uint32_t, uint16_t);
542 
543 static void dyn_tick(void *);
544 static void dyn_expire_states(struct ip_fw_chain *, ipfw_range_tlv *);
545 static void dyn_free_states(struct ip_fw_chain *);
546 static void dyn_export_parent(const struct dyn_parent *, uint16_t, uint8_t,
547     ipfw_dyn_rule *);
548 static void dyn_export_data(const struct dyn_data *, uint16_t, uint8_t,
549     uint8_t, ipfw_dyn_rule *);
550 static uint32_t dyn_update_tcp_state(struct dyn_data *,
551     const struct ipfw_flow_id *, const struct tcphdr *, int);
552 static void dyn_update_proto_state(struct dyn_data *,
553     const struct ipfw_flow_id *, const void *, int, int);
554 
555 /* Functions to work with IPv4 states */
556 struct dyn_ipv4_state *dyn_lookup_ipv4_state(const struct ipfw_flow_id *,
557     const void *, struct ipfw_dyn_info *, int);
558 static int dyn_lookup_ipv4_state_locked(const struct ipfw_flow_id *,
559     const void *, int, uint32_t, uint16_t);
560 static struct dyn_ipv4_state *dyn_alloc_ipv4_state(
561     const struct ipfw_flow_id *, uint16_t, uint8_t);
562 static int dyn_add_ipv4_state(void *, uint32_t, uint16_t,
563     const struct ipfw_flow_id *, const void *, int, uint32_t,
564     struct ipfw_dyn_info *, uint16_t, uint16_t, uint8_t);
565 static void dyn_export_ipv4_state(const struct dyn_ipv4_state *,
566     ipfw_dyn_rule *);
567 
568 /*
569  * Named states support.
570  */
571 static char *default_state_name = "default";
572 struct dyn_state_obj {
573 	struct named_object	no;
574 	char			name[64];
575 };
576 
577 #define	DYN_STATE_OBJ(ch, cmd)	\
578     ((struct dyn_state_obj *)SRV_OBJECT(ch, (cmd)->arg1))
579 /*
580  * Classifier callback.
581  * Return 0 if opcode contains object that should be referenced
582  * or rewritten.
583  */
584 static int
585 dyn_classify(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
586 {
587 
588 	DYN_DEBUG("opcode %d, arg1 %d", cmd->opcode, cmd->arg1);
589 	/* Don't rewrite "check-state any" */
590 	if (cmd->arg1 == 0 &&
591 	    cmd->opcode == O_CHECK_STATE)
592 		return (1);
593 
594 	*puidx = cmd->arg1;
595 	*ptype = 0;
596 	return (0);
597 }
598 
599 static void
600 dyn_update(ipfw_insn *cmd, uint16_t idx)
601 {
602 
603 	cmd->arg1 = idx;
604 	DYN_DEBUG("opcode %d, arg1 %d", cmd->opcode, cmd->arg1);
605 }
606 
607 static int
608 dyn_findbyname(struct ip_fw_chain *ch, struct tid_info *ti,
609     struct named_object **pno)
610 {
611 	ipfw_obj_ntlv *ntlv;
612 	const char *name;
613 
614 	DYN_DEBUG("uidx %d", ti->uidx);
615 	if (ti->uidx != 0) {
616 		if (ti->tlvs == NULL)
617 			return (EINVAL);
618 		/* Search ntlv in the buffer provided by user */
619 		ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx,
620 		    IPFW_TLV_STATE_NAME);
621 		if (ntlv == NULL)
622 			return (EINVAL);
623 		name = ntlv->name;
624 	} else
625 		name = default_state_name;
626 	/*
627 	 * Search named object with corresponding name.
628 	 * Since states objects are global - ignore the set value
629 	 * and use zero instead.
630 	 */
631 	*pno = ipfw_objhash_lookup_name_type(CHAIN_TO_SRV(ch), 0,
632 	    IPFW_TLV_STATE_NAME, name);
633 	/*
634 	 * We always return success here.
635 	 * The caller will check *pno and mark object as unresolved,
636 	 * then it will automatically create "default" object.
637 	 */
638 	return (0);
639 }
640 
641 static struct named_object *
642 dyn_findbykidx(struct ip_fw_chain *ch, uint16_t idx)
643 {
644 
645 	DYN_DEBUG("kidx %d", idx);
646 	return (ipfw_objhash_lookup_kidx(CHAIN_TO_SRV(ch), idx));
647 }
648 
649 static int
650 dyn_create(struct ip_fw_chain *ch, struct tid_info *ti,
651     uint16_t *pkidx)
652 {
653 	struct namedobj_instance *ni;
654 	struct dyn_state_obj *obj;
655 	struct named_object *no;
656 	ipfw_obj_ntlv *ntlv;
657 	char *name;
658 
659 	DYN_DEBUG("uidx %d", ti->uidx);
660 	if (ti->uidx != 0) {
661 		if (ti->tlvs == NULL)
662 			return (EINVAL);
663 		ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx,
664 		    IPFW_TLV_STATE_NAME);
665 		if (ntlv == NULL)
666 			return (EINVAL);
667 		name = ntlv->name;
668 	} else
669 		name = default_state_name;
670 
671 	ni = CHAIN_TO_SRV(ch);
672 	obj = malloc(sizeof(*obj), M_IPFW, M_WAITOK | M_ZERO);
673 	obj->no.name = obj->name;
674 	obj->no.etlv = IPFW_TLV_STATE_NAME;
675 	strlcpy(obj->name, name, sizeof(obj->name));
676 
677 	IPFW_UH_WLOCK(ch);
678 	no = ipfw_objhash_lookup_name_type(ni, 0,
679 	    IPFW_TLV_STATE_NAME, name);
680 	if (no != NULL) {
681 		/*
682 		 * Object is already created.
683 		 * Just return its kidx and bump refcount.
684 		 */
685 		*pkidx = no->kidx;
686 		no->refcnt++;
687 		IPFW_UH_WUNLOCK(ch);
688 		free(obj, M_IPFW);
689 		DYN_DEBUG("\tfound kidx %d", *pkidx);
690 		return (0);
691 	}
692 	if (ipfw_objhash_alloc_idx(ni, &obj->no.kidx) != 0) {
693 		DYN_DEBUG("\talloc_idx failed for %s", name);
694 		IPFW_UH_WUNLOCK(ch);
695 		free(obj, M_IPFW);
696 		return (ENOSPC);
697 	}
698 	ipfw_objhash_add(ni, &obj->no);
699 	SRV_OBJECT(ch, obj->no.kidx) = obj;
700 	obj->no.refcnt++;
701 	*pkidx = obj->no.kidx;
702 	IPFW_UH_WUNLOCK(ch);
703 	DYN_DEBUG("\tcreated kidx %d", *pkidx);
704 	return (0);
705 }
706 
707 static void
708 dyn_destroy(struct ip_fw_chain *ch, struct named_object *no)
709 {
710 	struct dyn_state_obj *obj;
711 
712 	IPFW_UH_WLOCK_ASSERT(ch);
713 
714 	KASSERT(no->etlv == IPFW_TLV_STATE_NAME,
715 	    ("%s: wrong object type %u", __func__, no->etlv));
716 	KASSERT(no->refcnt == 1,
717 	    ("Destroying object '%s' (type %u, idx %u) with refcnt %u",
718 	    no->name, no->etlv, no->kidx, no->refcnt));
719 	DYN_DEBUG("kidx %d", no->kidx);
720 	obj = SRV_OBJECT(ch, no->kidx);
721 	SRV_OBJECT(ch, no->kidx) = NULL;
722 	ipfw_objhash_del(CHAIN_TO_SRV(ch), no);
723 	ipfw_objhash_free_idx(CHAIN_TO_SRV(ch), no->kidx);
724 
725 	free(obj, M_IPFW);
726 }
727 
728 static struct opcode_obj_rewrite dyn_opcodes[] = {
729 	{
730 		O_KEEP_STATE, IPFW_TLV_STATE_NAME,
731 		dyn_classify, dyn_update,
732 		dyn_findbyname, dyn_findbykidx,
733 		dyn_create, dyn_destroy
734 	},
735 	{
736 		O_CHECK_STATE, IPFW_TLV_STATE_NAME,
737 		dyn_classify, dyn_update,
738 		dyn_findbyname, dyn_findbykidx,
739 		dyn_create, dyn_destroy
740 	},
741 	{
742 		O_PROBE_STATE, IPFW_TLV_STATE_NAME,
743 		dyn_classify, dyn_update,
744 		dyn_findbyname, dyn_findbykidx,
745 		dyn_create, dyn_destroy
746 	},
747 	{
748 		O_LIMIT, IPFW_TLV_STATE_NAME,
749 		dyn_classify, dyn_update,
750 		dyn_findbyname, dyn_findbykidx,
751 		dyn_create, dyn_destroy
752 	},
753 };
754 
755 /*
756  * IMPORTANT: the hash function for dynamic rules must be commutative
757  * in source and destination (ip,port), because rules are bidirectional
758  * and we want to find both in the same bucket.
759  */
760 #ifndef IPFIREWALL_JENKINSHASH
761 static __inline uint32_t
762 hash_packet(const struct ipfw_flow_id *id)
763 {
764 	uint32_t i;
765 
766 #ifdef INET6
767 	if (IS_IP6_FLOW_ID(id))
768 		i = ntohl((id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
769 		    (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
770 		    (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
771 		    (id->src_ip6.__u6_addr.__u6_addr32[3]));
772 	else
773 #endif /* INET6 */
774 	i = (id->dst_ip) ^ (id->src_ip);
775 	i ^= (id->dst_port) ^ (id->src_port);
776 	return (i);
777 }
778 
779 static __inline uint32_t
780 hash_parent(const struct ipfw_flow_id *id, const void *rule)
781 {
782 
783 	return (hash_packet(id) ^ ((uintptr_t)rule));
784 }
785 
786 #else /* IPFIREWALL_JENKINSHASH */
787 
788 VNET_DEFINE_STATIC(uint32_t, dyn_hashseed);
789 #define	V_dyn_hashseed		VNET(dyn_hashseed)
790 
791 static __inline int
792 addrcmp4(const struct ipfw_flow_id *id)
793 {
794 
795 	if (id->src_ip < id->dst_ip)
796 		return (0);
797 	if (id->src_ip > id->dst_ip)
798 		return (1);
799 	if (id->src_port <= id->dst_port)
800 		return (0);
801 	return (1);
802 }
803 
804 #ifdef INET6
805 static __inline int
806 addrcmp6(const struct ipfw_flow_id *id)
807 {
808 	int ret;
809 
810 	ret = memcmp(&id->src_ip6, &id->dst_ip6, sizeof(struct in6_addr));
811 	if (ret < 0)
812 		return (0);
813 	if (ret > 0)
814 		return (1);
815 	if (id->src_port <= id->dst_port)
816 		return (0);
817 	return (1);
818 }
819 
820 static __inline uint32_t
821 hash_packet6(const struct ipfw_flow_id *id)
822 {
823 	struct tuple6 {
824 		struct in6_addr	addr[2];
825 		uint16_t	port[2];
826 	} t6;
827 
828 	if (addrcmp6(id) == 0) {
829 		t6.addr[0] = id->src_ip6;
830 		t6.addr[1] = id->dst_ip6;
831 		t6.port[0] = id->src_port;
832 		t6.port[1] = id->dst_port;
833 	} else {
834 		t6.addr[0] = id->dst_ip6;
835 		t6.addr[1] = id->src_ip6;
836 		t6.port[0] = id->dst_port;
837 		t6.port[1] = id->src_port;
838 	}
839 	return (jenkins_hash32((const uint32_t *)&t6,
840 	    sizeof(t6) / sizeof(uint32_t), V_dyn_hashseed));
841 }
842 #endif
843 
844 static __inline uint32_t
845 hash_packet(const struct ipfw_flow_id *id)
846 {
847 	struct tuple4 {
848 		in_addr_t	addr[2];
849 		uint16_t	port[2];
850 	} t4;
851 
852 	if (IS_IP4_FLOW_ID(id)) {
853 		/* All fields are in host byte order */
854 		if (addrcmp4(id) == 0) {
855 			t4.addr[0] = id->src_ip;
856 			t4.addr[1] = id->dst_ip;
857 			t4.port[0] = id->src_port;
858 			t4.port[1] = id->dst_port;
859 		} else {
860 			t4.addr[0] = id->dst_ip;
861 			t4.addr[1] = id->src_ip;
862 			t4.port[0] = id->dst_port;
863 			t4.port[1] = id->src_port;
864 		}
865 		return (jenkins_hash32((const uint32_t *)&t4,
866 		    sizeof(t4) / sizeof(uint32_t), V_dyn_hashseed));
867 	} else
868 #ifdef INET6
869 	if (IS_IP6_FLOW_ID(id))
870 		return (hash_packet6(id));
871 #endif
872 	return (0);
873 }
874 
875 static __inline uint32_t
876 hash_parent(const struct ipfw_flow_id *id, const void *rule)
877 {
878 
879 	return (jenkins_hash32((const uint32_t *)&rule,
880 	    sizeof(rule) / sizeof(uint32_t), hash_packet(id)));
881 }
882 #endif /* IPFIREWALL_JENKINSHASH */
883 
884 /*
885  * Print customizable flow id description via log(9) facility.
886  */
887 static void
888 print_dyn_rule_flags(const struct ipfw_flow_id *id, int dyn_type,
889     int log_flags, char *prefix, char *postfix)
890 {
891 	struct in_addr da;
892 #ifdef INET6
893 	char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
894 #else
895 	char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
896 #endif
897 
898 #ifdef INET6
899 	if (IS_IP6_FLOW_ID(id)) {
900 		ip6_sprintf(src, &id->src_ip6);
901 		ip6_sprintf(dst, &id->dst_ip6);
902 	} else
903 #endif
904 	{
905 		da.s_addr = htonl(id->src_ip);
906 		inet_ntop(AF_INET, &da, src, sizeof(src));
907 		da.s_addr = htonl(id->dst_ip);
908 		inet_ntop(AF_INET, &da, dst, sizeof(dst));
909 	}
910 	log(log_flags, "ipfw: %s type %d %s %d -> %s %d, %d %s\n",
911 	    prefix, dyn_type, src, id->src_port, dst,
912 	    id->dst_port, V_dyn_count, postfix);
913 }
914 
915 #define	print_dyn_rule(id, dtype, prefix, postfix)	\
916 	print_dyn_rule_flags(id, dtype, LOG_DEBUG, prefix, postfix)
917 
918 #define	TIME_LEQ(a,b)	((int)((a)-(b)) <= 0)
919 #define	TIME_LE(a,b)	((int)((a)-(b)) < 0)
920 #define	_SEQ_GE(a,b)	((int)((a)-(b)) >= 0)
921 #define	BOTH_SYN	(TH_SYN | (TH_SYN << 8))
922 #define	BOTH_FIN	(TH_FIN | (TH_FIN << 8))
923 #define	TCP_FLAGS	(TH_FLAGS | (TH_FLAGS << 8))
924 #define	ACK_FWD		0x00010000	/* fwd ack seen */
925 #define	ACK_REV		0x00020000	/* rev ack seen */
926 #define	ACK_BOTH	(ACK_FWD | ACK_REV)
927 
928 static uint32_t
929 dyn_update_tcp_state(struct dyn_data *data, const struct ipfw_flow_id *pkt,
930     const struct tcphdr *tcp, int dir)
931 {
932 	uint32_t ack, expire;
933 	uint32_t state, old;
934 	uint8_t th_flags;
935 
936 	expire = data->expire;
937 	old = state = data->state;
938 	th_flags = pkt->_flags & (TH_FIN | TH_SYN | TH_RST);
939 	state |= (dir == MATCH_FORWARD) ? th_flags: (th_flags << 8);
940 	switch (state & TCP_FLAGS) {
941 	case TH_SYN:			/* opening */
942 		expire = time_uptime + V_dyn_syn_lifetime;
943 		break;
944 
945 	case BOTH_SYN:			/* move to established */
946 	case BOTH_SYN | TH_FIN:		/* one side tries to close */
947 	case BOTH_SYN | (TH_FIN << 8):
948 		if (tcp == NULL)
949 			break;
950 		ack = ntohl(tcp->th_ack);
951 		if (dir == MATCH_FORWARD) {
952 			if (data->ack_fwd == 0 ||
953 			    _SEQ_GE(ack, data->ack_fwd)) {
954 				state |= ACK_FWD;
955 				if (data->ack_fwd != ack)
956 					ck_pr_store_32(&data->ack_fwd, ack);
957 			}
958 		} else {
959 			if (data->ack_rev == 0 ||
960 			    _SEQ_GE(ack, data->ack_rev)) {
961 				state |= ACK_REV;
962 				if (data->ack_rev != ack)
963 					ck_pr_store_32(&data->ack_rev, ack);
964 			}
965 		}
966 		if ((state & ACK_BOTH) == ACK_BOTH) {
967 			/*
968 			 * Set expire time to V_dyn_ack_lifetime only if
969 			 * we got ACKs for both directions.
970 			 * We use XOR here to avoid possible state
971 			 * overwriting in concurrent thread.
972 			 */
973 			expire = time_uptime + V_dyn_ack_lifetime;
974 			ck_pr_xor_32(&data->state, ACK_BOTH);
975 		} else if ((data->state & ACK_BOTH) != (state & ACK_BOTH))
976 			ck_pr_or_32(&data->state, state & ACK_BOTH);
977 		break;
978 
979 	case BOTH_SYN | BOTH_FIN:	/* both sides closed */
980 		if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
981 			V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
982 		expire = time_uptime + V_dyn_fin_lifetime;
983 		break;
984 
985 	default:
986 		if (V_dyn_keepalive != 0 &&
987 		    V_dyn_rst_lifetime >= V_dyn_keepalive_period)
988 			V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
989 		expire = time_uptime + V_dyn_rst_lifetime;
990 	}
991 	/* Save TCP state if it was changed */
992 	if ((state & TCP_FLAGS) != (old & TCP_FLAGS))
993 		ck_pr_or_32(&data->state, state & TCP_FLAGS);
994 	return (expire);
995 }
996 
997 /*
998  * Update ULP specific state.
999  * For TCP we keep sequence numbers and flags. For other protocols
1000  * currently we update only expire time. Packets and bytes counters
1001  * are also updated here.
1002  */
1003 static void
1004 dyn_update_proto_state(struct dyn_data *data, const struct ipfw_flow_id *pkt,
1005     const void *ulp, int pktlen, int dir)
1006 {
1007 	uint32_t expire;
1008 
1009 	/* NOTE: we are in critical section here. */
1010 	switch (pkt->proto) {
1011 	case IPPROTO_UDP:
1012 	case IPPROTO_UDPLITE:
1013 		expire = time_uptime + V_dyn_udp_lifetime;
1014 		break;
1015 	case IPPROTO_TCP:
1016 		expire = dyn_update_tcp_state(data, pkt, ulp, dir);
1017 		break;
1018 	default:
1019 		expire = time_uptime + V_dyn_short_lifetime;
1020 	}
1021 	/*
1022 	 * Expiration timer has the per-second granularity, no need to update
1023 	 * it every time when state is matched.
1024 	 */
1025 	if (data->expire != expire)
1026 		ck_pr_store_32(&data->expire, expire);
1027 
1028 	if (dir == MATCH_FORWARD)
1029 		DYN_COUNTER_INC(data, fwd, pktlen);
1030 	else
1031 		DYN_COUNTER_INC(data, rev, pktlen);
1032 }
1033 
1034 /*
1035  * Lookup IPv4 state.
1036  * Must be called in critical section.
1037  */
1038 struct dyn_ipv4_state *
1039 dyn_lookup_ipv4_state(const struct ipfw_flow_id *pkt, const void *ulp,
1040     struct ipfw_dyn_info *info, int pktlen)
1041 {
1042 	struct dyn_ipv4_state *s;
1043 	uint32_t version, bucket;
1044 
1045 	bucket = DYN_BUCKET(info->hashval, V_curr_dyn_buckets);
1046 	info->version = DYN_BUCKET_VERSION(bucket, ipv4_add);
1047 restart:
1048 	version = DYN_BUCKET_VERSION(bucket, ipv4_del);
1049 	CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
1050 		DYNSTATE_PROTECT(s);
1051 		if (version != DYN_BUCKET_VERSION(bucket, ipv4_del))
1052 			goto restart;
1053 		if (s->proto != pkt->proto)
1054 			continue;
1055 		if (info->kidx != 0 && s->kidx != info->kidx)
1056 			continue;
1057 		if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1058 		    s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1059 			info->direction = MATCH_FORWARD;
1060 			break;
1061 		}
1062 		if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1063 		    s->src == pkt->dst_ip && s->dst == pkt->src_ip) {
1064 			info->direction = MATCH_REVERSE;
1065 			break;
1066 		}
1067 	}
1068 
1069 	if (s != NULL)
1070 		dyn_update_proto_state(s->data, pkt, ulp, pktlen,
1071 		    info->direction);
1072 	return (s);
1073 }
1074 
1075 /*
1076  * Lookup IPv4 state.
1077  * Simplifed version is used to check that matching state doesn't exist.
1078  */
1079 static int
1080 dyn_lookup_ipv4_state_locked(const struct ipfw_flow_id *pkt,
1081     const void *ulp, int pktlen, uint32_t bucket, uint16_t kidx)
1082 {
1083 	struct dyn_ipv4_state *s;
1084 	int dir;
1085 
1086 	dir = MATCH_NONE;
1087 	DYN_BUCKET_ASSERT(bucket);
1088 	CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
1089 		if (s->proto != pkt->proto ||
1090 		    s->kidx != kidx)
1091 			continue;
1092 		if (s->sport == pkt->src_port &&
1093 		    s->dport == pkt->dst_port &&
1094 		    s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1095 			dir = MATCH_FORWARD;
1096 			break;
1097 		}
1098 		if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1099 		    s->src == pkt->dst_ip && s->dst == pkt->src_ip) {
1100 			dir = MATCH_REVERSE;
1101 			break;
1102 		}
1103 	}
1104 	if (s != NULL)
1105 		dyn_update_proto_state(s->data, pkt, ulp, pktlen, dir);
1106 	return (s != NULL);
1107 }
1108 
1109 struct dyn_ipv4_state *
1110 dyn_lookup_ipv4_parent(const struct ipfw_flow_id *pkt, const void *rule,
1111     uint32_t ruleid, uint16_t rulenum, uint32_t hashval)
1112 {
1113 	struct dyn_ipv4_state *s;
1114 	uint32_t version, bucket;
1115 
1116 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1117 restart:
1118 	version = DYN_BUCKET_VERSION(bucket, ipv4_parent_del);
1119 	CK_SLIST_FOREACH(s, &V_dyn_ipv4_parent[bucket], entry) {
1120 		DYNSTATE_PROTECT(s);
1121 		if (version != DYN_BUCKET_VERSION(bucket, ipv4_parent_del))
1122 			goto restart;
1123 		/*
1124 		 * NOTE: we do not need to check kidx, because parent rule
1125 		 * can not create states with different kidx.
1126 		 * And parent rule always created for forward direction.
1127 		 */
1128 		if (s->limit->parent == rule &&
1129 		    s->limit->ruleid == ruleid &&
1130 		    s->limit->rulenum == rulenum &&
1131 		    s->proto == pkt->proto &&
1132 		    s->sport == pkt->src_port &&
1133 		    s->dport == pkt->dst_port &&
1134 		    s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1135 			if (s->limit->expire != time_uptime +
1136 			    V_dyn_short_lifetime)
1137 				ck_pr_store_32(&s->limit->expire,
1138 				    time_uptime + V_dyn_short_lifetime);
1139 			break;
1140 		}
1141 	}
1142 	return (s);
1143 }
1144 
1145 static struct dyn_ipv4_state *
1146 dyn_lookup_ipv4_parent_locked(const struct ipfw_flow_id *pkt,
1147     const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t bucket)
1148 {
1149 	struct dyn_ipv4_state *s;
1150 
1151 	DYN_BUCKET_ASSERT(bucket);
1152 	CK_SLIST_FOREACH(s, &V_dyn_ipv4_parent[bucket], entry) {
1153 		if (s->limit->parent == rule &&
1154 		    s->limit->ruleid == ruleid &&
1155 		    s->limit->rulenum == rulenum &&
1156 		    s->proto == pkt->proto &&
1157 		    s->sport == pkt->src_port &&
1158 		    s->dport == pkt->dst_port &&
1159 		    s->src == pkt->src_ip && s->dst == pkt->dst_ip)
1160 			break;
1161 	}
1162 	return (s);
1163 }
1164 
1165 #ifdef INET6
1166 static uint32_t
1167 dyn_getscopeid(const struct ip_fw_args *args)
1168 {
1169 
1170 	/*
1171 	 * If source or destination address is an scopeid address, we need
1172 	 * determine the scope zone id to resolve address scope ambiguity.
1173 	 */
1174 	if (IN6_IS_ADDR_LINKLOCAL(&args->f_id.src_ip6) ||
1175 	    IN6_IS_ADDR_LINKLOCAL(&args->f_id.dst_ip6))
1176 		return (in6_getscopezone(args->ifp, IPV6_ADDR_SCOPE_LINKLOCAL));
1177 
1178 	return (0);
1179 }
1180 
1181 /*
1182  * Lookup IPv6 state.
1183  * Must be called in critical section.
1184  */
1185 static struct dyn_ipv6_state *
1186 dyn_lookup_ipv6_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1187     const void *ulp, struct ipfw_dyn_info *info, int pktlen)
1188 {
1189 	struct dyn_ipv6_state *s;
1190 	uint32_t version, bucket;
1191 
1192 	bucket = DYN_BUCKET(info->hashval, V_curr_dyn_buckets);
1193 	info->version = DYN_BUCKET_VERSION(bucket, ipv6_add);
1194 restart:
1195 	version = DYN_BUCKET_VERSION(bucket, ipv6_del);
1196 	CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
1197 		DYNSTATE_PROTECT(s);
1198 		if (version != DYN_BUCKET_VERSION(bucket, ipv6_del))
1199 			goto restart;
1200 		if (s->proto != pkt->proto || s->zoneid != zoneid)
1201 			continue;
1202 		if (info->kidx != 0 && s->kidx != info->kidx)
1203 			continue;
1204 		if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1205 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1206 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1207 			info->direction = MATCH_FORWARD;
1208 			break;
1209 		}
1210 		if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1211 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->dst_ip6) &&
1212 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->src_ip6)) {
1213 			info->direction = MATCH_REVERSE;
1214 			break;
1215 		}
1216 	}
1217 	if (s != NULL)
1218 		dyn_update_proto_state(s->data, pkt, ulp, pktlen,
1219 		    info->direction);
1220 	return (s);
1221 }
1222 
1223 /*
1224  * Lookup IPv6 state.
1225  * Simplifed version is used to check that matching state doesn't exist.
1226  */
1227 static int
1228 dyn_lookup_ipv6_state_locked(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1229     const void *ulp, int pktlen, uint32_t bucket, uint16_t kidx)
1230 {
1231 	struct dyn_ipv6_state *s;
1232 	int dir;
1233 
1234 	dir = MATCH_NONE;
1235 	DYN_BUCKET_ASSERT(bucket);
1236 	CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
1237 		if (s->proto != pkt->proto || s->kidx != kidx ||
1238 		    s->zoneid != zoneid)
1239 			continue;
1240 		if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1241 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1242 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1243 			dir = MATCH_FORWARD;
1244 			break;
1245 		}
1246 		if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1247 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->dst_ip6) &&
1248 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->src_ip6)) {
1249 			dir = MATCH_REVERSE;
1250 			break;
1251 		}
1252 	}
1253 	if (s != NULL)
1254 		dyn_update_proto_state(s->data, pkt, ulp, pktlen, dir);
1255 	return (s != NULL);
1256 }
1257 
1258 static struct dyn_ipv6_state *
1259 dyn_lookup_ipv6_parent(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1260     const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t hashval)
1261 {
1262 	struct dyn_ipv6_state *s;
1263 	uint32_t version, bucket;
1264 
1265 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1266 restart:
1267 	version = DYN_BUCKET_VERSION(bucket, ipv6_parent_del);
1268 	CK_SLIST_FOREACH(s, &V_dyn_ipv6_parent[bucket], entry) {
1269 		DYNSTATE_PROTECT(s);
1270 		if (version != DYN_BUCKET_VERSION(bucket, ipv6_parent_del))
1271 			goto restart;
1272 		/*
1273 		 * NOTE: we do not need to check kidx, because parent rule
1274 		 * can not create states with different kidx.
1275 		 * Also parent rule always created for forward direction.
1276 		 */
1277 		if (s->limit->parent == rule &&
1278 		    s->limit->ruleid == ruleid &&
1279 		    s->limit->rulenum == rulenum &&
1280 		    s->proto == pkt->proto &&
1281 		    s->sport == pkt->src_port &&
1282 		    s->dport == pkt->dst_port && s->zoneid == zoneid &&
1283 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1284 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1285 			if (s->limit->expire != time_uptime +
1286 			    V_dyn_short_lifetime)
1287 				ck_pr_store_32(&s->limit->expire,
1288 				    time_uptime + V_dyn_short_lifetime);
1289 			break;
1290 		}
1291 	}
1292 	return (s);
1293 }
1294 
1295 static struct dyn_ipv6_state *
1296 dyn_lookup_ipv6_parent_locked(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1297     const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t bucket)
1298 {
1299 	struct dyn_ipv6_state *s;
1300 
1301 	DYN_BUCKET_ASSERT(bucket);
1302 	CK_SLIST_FOREACH(s, &V_dyn_ipv6_parent[bucket], entry) {
1303 		if (s->limit->parent == rule &&
1304 		    s->limit->ruleid == ruleid &&
1305 		    s->limit->rulenum == rulenum &&
1306 		    s->proto == pkt->proto &&
1307 		    s->sport == pkt->src_port &&
1308 		    s->dport == pkt->dst_port && s->zoneid == zoneid &&
1309 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1310 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6))
1311 			break;
1312 	}
1313 	return (s);
1314 }
1315 
1316 #endif /* INET6 */
1317 
1318 /*
1319  * Lookup dynamic state.
1320  *  pkt - filled by ipfw_chk() ipfw_flow_id;
1321  *  ulp - determined by ipfw_chk() upper level protocol header;
1322  *  dyn_info - info about matched state to return back;
1323  * Returns pointer to state's parent rule and dyn_info. If there is
1324  * no state, NULL is returned.
1325  * On match ipfw_dyn_lookup() updates state's counters.
1326  */
1327 struct ip_fw *
1328 ipfw_dyn_lookup_state(const struct ip_fw_args *args, const void *ulp,
1329     int pktlen, const ipfw_insn *cmd, struct ipfw_dyn_info *info)
1330 {
1331 	struct dyn_data *data;
1332 	struct ip_fw *rule;
1333 
1334 	IPFW_RLOCK_ASSERT(&V_layer3_chain);
1335 
1336 	data = NULL;
1337 	rule = NULL;
1338 	info->kidx = cmd->arg1;
1339 	info->direction = MATCH_NONE;
1340 	info->hashval = hash_packet(&args->f_id);
1341 
1342 	DYNSTATE_CRITICAL_ENTER();
1343 	if (IS_IP4_FLOW_ID(&args->f_id)) {
1344 		struct dyn_ipv4_state *s;
1345 
1346 		s = dyn_lookup_ipv4_state(&args->f_id, ulp, info, pktlen);
1347 		if (s != NULL) {
1348 			/*
1349 			 * Dynamic states are created using the same 5-tuple,
1350 			 * so it is assumed, that parent rule for O_LIMIT
1351 			 * state has the same address family.
1352 			 */
1353 			data = s->data;
1354 			if (s->type == O_LIMIT) {
1355 				s = data->parent;
1356 				rule = s->limit->parent;
1357 			} else
1358 				rule = data->parent;
1359 		}
1360 	}
1361 #ifdef INET6
1362 	else if (IS_IP6_FLOW_ID(&args->f_id)) {
1363 		struct dyn_ipv6_state *s;
1364 
1365 		s = dyn_lookup_ipv6_state(&args->f_id, dyn_getscopeid(args),
1366 		    ulp, info, pktlen);
1367 		if (s != NULL) {
1368 			data = s->data;
1369 			if (s->type == O_LIMIT) {
1370 				s = data->parent;
1371 				rule = s->limit->parent;
1372 			} else
1373 				rule = data->parent;
1374 		}
1375 	}
1376 #endif
1377 	if (data != NULL) {
1378 		/*
1379 		 * If cached chain id is the same, we can avoid rule index
1380 		 * lookup. Otherwise do lookup and update chain_id and f_pos.
1381 		 * It is safe even if there is concurrent thread that want
1382 		 * update the same state, because chain->id can be changed
1383 		 * only under IPFW_WLOCK().
1384 		 */
1385 		if (data->chain_id != V_layer3_chain.id) {
1386 			data->f_pos = ipfw_find_rule(&V_layer3_chain,
1387 			    data->rulenum, data->ruleid);
1388 			/*
1389 			 * Check that found state has not orphaned.
1390 			 * When chain->id being changed the parent
1391 			 * rule can be deleted. If found rule doesn't
1392 			 * match the parent pointer, consider this
1393 			 * result as MATCH_NONE and return NULL.
1394 			 *
1395 			 * This will lead to creation of new similar state
1396 			 * that will be added into head of this bucket.
1397 			 * And the state that we currently have matched
1398 			 * should be deleted by dyn_expire_states().
1399 			 *
1400 			 * In case when dyn_keep_states is enabled, return
1401 			 * pointer to deleted rule and f_pos value
1402 			 * corresponding to penultimate rule.
1403 			 * When we have enabled V_dyn_keep_states, states
1404 			 * that become orphaned will get the DYN_REFERENCED
1405 			 * flag and rule will keep around. So we can return
1406 			 * it. But since it is not in the rules map, we need
1407 			 * return such f_pos value, so after the state
1408 			 * handling if the search will continue, the next rule
1409 			 * will be the last one - the default rule.
1410 			 */
1411 			if (V_layer3_chain.map[data->f_pos] == rule) {
1412 				data->chain_id = V_layer3_chain.id;
1413 				info->f_pos = data->f_pos;
1414 			} else if (V_dyn_keep_states != 0) {
1415 				/*
1416 				 * The original rule pointer is still usable.
1417 				 * So, we return it, but f_pos need to be
1418 				 * changed to point to the penultimate rule.
1419 				 */
1420 				MPASS(V_layer3_chain.n_rules > 1);
1421 				data->chain_id = V_layer3_chain.id;
1422 				data->f_pos = V_layer3_chain.n_rules - 2;
1423 				info->f_pos = data->f_pos;
1424 			} else {
1425 				rule = NULL;
1426 				info->direction = MATCH_NONE;
1427 				DYN_DEBUG("rule %p  [%u, %u] is considered "
1428 				    "invalid in data %p", rule, data->ruleid,
1429 				    data->rulenum, data);
1430 				/* info->f_pos doesn't matter here. */
1431 			}
1432 		} else
1433 			info->f_pos = data->f_pos;
1434 	}
1435 	DYNSTATE_CRITICAL_EXIT();
1436 #if 0
1437 	/*
1438 	 * Return MATCH_NONE if parent rule is in disabled set.
1439 	 * This will lead to creation of new similar state that
1440 	 * will be added into head of this bucket.
1441 	 *
1442 	 * XXXAE: we need to be able update state's set when parent
1443 	 *	  rule set is changed.
1444 	 */
1445 	if (rule != NULL && (V_set_disable & (1 << rule->set))) {
1446 		rule = NULL;
1447 		info->direction = MATCH_NONE;
1448 	}
1449 #endif
1450 	return (rule);
1451 }
1452 
1453 static struct dyn_parent *
1454 dyn_alloc_parent(void *parent, uint32_t ruleid, uint16_t rulenum,
1455     uint32_t hashval)
1456 {
1457 	struct dyn_parent *limit;
1458 
1459 	limit = uma_zalloc(V_dyn_parent_zone, M_NOWAIT | M_ZERO);
1460 	if (limit == NULL) {
1461 		if (last_log != time_uptime) {
1462 			last_log = time_uptime;
1463 			log(LOG_DEBUG,
1464 			    "ipfw: Cannot allocate parent dynamic state, "
1465 			    "consider increasing "
1466 			    "net.inet.ip.fw.dyn_parent_max\n");
1467 		}
1468 		return (NULL);
1469 	}
1470 
1471 	limit->parent = parent;
1472 	limit->ruleid = ruleid;
1473 	limit->rulenum = rulenum;
1474 	limit->hashval = hashval;
1475 	limit->expire = time_uptime + V_dyn_short_lifetime;
1476 	return (limit);
1477 }
1478 
1479 static struct dyn_data *
1480 dyn_alloc_dyndata(void *parent, uint32_t ruleid, uint16_t rulenum,
1481     const struct ipfw_flow_id *pkt, const void *ulp, int pktlen,
1482     uint32_t hashval, uint16_t fibnum)
1483 {
1484 	struct dyn_data *data;
1485 
1486 	data = uma_zalloc(V_dyn_data_zone, M_NOWAIT | M_ZERO);
1487 	if (data == NULL) {
1488 		if (last_log != time_uptime) {
1489 			last_log = time_uptime;
1490 			log(LOG_DEBUG,
1491 			    "ipfw: Cannot allocate dynamic state, "
1492 			    "consider increasing net.inet.ip.fw.dyn_max\n");
1493 		}
1494 		return (NULL);
1495 	}
1496 
1497 	data->parent = parent;
1498 	data->ruleid = ruleid;
1499 	data->rulenum = rulenum;
1500 	data->fibnum = fibnum;
1501 	data->hashval = hashval;
1502 	data->expire = time_uptime + V_dyn_syn_lifetime;
1503 	dyn_update_proto_state(data, pkt, ulp, pktlen, MATCH_FORWARD);
1504 	return (data);
1505 }
1506 
1507 static struct dyn_ipv4_state *
1508 dyn_alloc_ipv4_state(const struct ipfw_flow_id *pkt, uint16_t kidx,
1509     uint8_t type)
1510 {
1511 	struct dyn_ipv4_state *s;
1512 
1513 	s = uma_zalloc(V_dyn_ipv4_zone, M_NOWAIT | M_ZERO);
1514 	if (s == NULL)
1515 		return (NULL);
1516 
1517 	s->type = type;
1518 	s->kidx = kidx;
1519 	s->proto = pkt->proto;
1520 	s->sport = pkt->src_port;
1521 	s->dport = pkt->dst_port;
1522 	s->src = pkt->src_ip;
1523 	s->dst = pkt->dst_ip;
1524 	return (s);
1525 }
1526 
1527 /*
1528  * Add IPv4 parent state.
1529  * Returns pointer to parent state. When it is not NULL we are in
1530  * critical section and pointer protected by hazard pointer.
1531  * When some error occurs, it returns NULL and exit from critical section
1532  * is not needed.
1533  */
1534 static struct dyn_ipv4_state *
1535 dyn_add_ipv4_parent(void *rule, uint32_t ruleid, uint16_t rulenum,
1536     const struct ipfw_flow_id *pkt, uint32_t hashval, uint32_t version,
1537     uint16_t kidx)
1538 {
1539 	struct dyn_ipv4_state *s;
1540 	struct dyn_parent *limit;
1541 	uint32_t bucket;
1542 
1543 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1544 	DYN_BUCKET_LOCK(bucket);
1545 	if (version != DYN_BUCKET_VERSION(bucket, ipv4_parent_add)) {
1546 		/*
1547 		 * Bucket version has been changed since last lookup,
1548 		 * do lookup again to be sure that state does not exist.
1549 		 */
1550 		s = dyn_lookup_ipv4_parent_locked(pkt, rule, ruleid,
1551 		    rulenum, bucket);
1552 		if (s != NULL) {
1553 			/*
1554 			 * Simultaneous thread has already created this
1555 			 * state. Just return it.
1556 			 */
1557 			DYNSTATE_CRITICAL_ENTER();
1558 			DYNSTATE_PROTECT(s);
1559 			DYN_BUCKET_UNLOCK(bucket);
1560 			return (s);
1561 		}
1562 	}
1563 
1564 	limit = dyn_alloc_parent(rule, ruleid, rulenum, hashval);
1565 	if (limit == NULL) {
1566 		DYN_BUCKET_UNLOCK(bucket);
1567 		return (NULL);
1568 	}
1569 
1570 	s = dyn_alloc_ipv4_state(pkt, kidx, O_LIMIT_PARENT);
1571 	if (s == NULL) {
1572 		DYN_BUCKET_UNLOCK(bucket);
1573 		uma_zfree(V_dyn_parent_zone, limit);
1574 		return (NULL);
1575 	}
1576 
1577 	s->limit = limit;
1578 	CK_SLIST_INSERT_HEAD(&V_dyn_ipv4_parent[bucket], s, entry);
1579 	DYN_COUNT_INC(dyn_parent_count);
1580 	DYN_BUCKET_VERSION_BUMP(bucket, ipv4_parent_add);
1581 	DYNSTATE_CRITICAL_ENTER();
1582 	DYNSTATE_PROTECT(s);
1583 	DYN_BUCKET_UNLOCK(bucket);
1584 	return (s);
1585 }
1586 
1587 static int
1588 dyn_add_ipv4_state(void *parent, uint32_t ruleid, uint16_t rulenum,
1589     const struct ipfw_flow_id *pkt, const void *ulp, int pktlen,
1590     uint32_t hashval, struct ipfw_dyn_info *info, uint16_t fibnum,
1591     uint16_t kidx, uint8_t type)
1592 {
1593 	struct dyn_ipv4_state *s;
1594 	void *data;
1595 	uint32_t bucket;
1596 
1597 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1598 	DYN_BUCKET_LOCK(bucket);
1599 	if (info->direction == MATCH_UNKNOWN ||
1600 	    info->kidx != kidx ||
1601 	    info->hashval != hashval ||
1602 	    info->version != DYN_BUCKET_VERSION(bucket, ipv4_add)) {
1603 		/*
1604 		 * Bucket version has been changed since last lookup,
1605 		 * do lookup again to be sure that state does not exist.
1606 		 */
1607 		if (dyn_lookup_ipv4_state_locked(pkt, ulp, pktlen,
1608 		    bucket, kidx) != 0) {
1609 			DYN_BUCKET_UNLOCK(bucket);
1610 			return (EEXIST);
1611 		}
1612 	}
1613 
1614 	data = dyn_alloc_dyndata(parent, ruleid, rulenum, pkt, ulp,
1615 	    pktlen, hashval, fibnum);
1616 	if (data == NULL) {
1617 		DYN_BUCKET_UNLOCK(bucket);
1618 		return (ENOMEM);
1619 	}
1620 
1621 	s = dyn_alloc_ipv4_state(pkt, kidx, type);
1622 	if (s == NULL) {
1623 		DYN_BUCKET_UNLOCK(bucket);
1624 		uma_zfree(V_dyn_data_zone, data);
1625 		return (ENOMEM);
1626 	}
1627 
1628 	s->data = data;
1629 	CK_SLIST_INSERT_HEAD(&V_dyn_ipv4[bucket], s, entry);
1630 	DYN_COUNT_INC(dyn_count);
1631 	DYN_BUCKET_VERSION_BUMP(bucket, ipv4_add);
1632 	DYN_BUCKET_UNLOCK(bucket);
1633 	return (0);
1634 }
1635 
1636 #ifdef INET6
1637 static struct dyn_ipv6_state *
1638 dyn_alloc_ipv6_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1639     uint16_t kidx, uint8_t type)
1640 {
1641 	struct dyn_ipv6_state *s;
1642 
1643 	s = uma_zalloc(V_dyn_ipv6_zone, M_NOWAIT | M_ZERO);
1644 	if (s == NULL)
1645 		return (NULL);
1646 
1647 	s->type = type;
1648 	s->kidx = kidx;
1649 	s->zoneid = zoneid;
1650 	s->proto = pkt->proto;
1651 	s->sport = pkt->src_port;
1652 	s->dport = pkt->dst_port;
1653 	s->src = pkt->src_ip6;
1654 	s->dst = pkt->dst_ip6;
1655 	return (s);
1656 }
1657 
1658 /*
1659  * Add IPv6 parent state.
1660  * Returns pointer to parent state. When it is not NULL we are in
1661  * critical section and pointer protected by hazard pointer.
1662  * When some error occurs, it return NULL and exit from critical section
1663  * is not needed.
1664  */
1665 static struct dyn_ipv6_state *
1666 dyn_add_ipv6_parent(void *rule, uint32_t ruleid, uint16_t rulenum,
1667     const struct ipfw_flow_id *pkt, uint32_t zoneid, uint32_t hashval,
1668     uint32_t version, uint16_t kidx)
1669 {
1670 	struct dyn_ipv6_state *s;
1671 	struct dyn_parent *limit;
1672 	uint32_t bucket;
1673 
1674 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1675 	DYN_BUCKET_LOCK(bucket);
1676 	if (version != DYN_BUCKET_VERSION(bucket, ipv6_parent_add)) {
1677 		/*
1678 		 * Bucket version has been changed since last lookup,
1679 		 * do lookup again to be sure that state does not exist.
1680 		 */
1681 		s = dyn_lookup_ipv6_parent_locked(pkt, zoneid, rule, ruleid,
1682 		    rulenum, bucket);
1683 		if (s != NULL) {
1684 			/*
1685 			 * Simultaneous thread has already created this
1686 			 * state. Just return it.
1687 			 */
1688 			DYNSTATE_CRITICAL_ENTER();
1689 			DYNSTATE_PROTECT(s);
1690 			DYN_BUCKET_UNLOCK(bucket);
1691 			return (s);
1692 		}
1693 	}
1694 
1695 	limit = dyn_alloc_parent(rule, ruleid, rulenum, hashval);
1696 	if (limit == NULL) {
1697 		DYN_BUCKET_UNLOCK(bucket);
1698 		return (NULL);
1699 	}
1700 
1701 	s = dyn_alloc_ipv6_state(pkt, zoneid, kidx, O_LIMIT_PARENT);
1702 	if (s == NULL) {
1703 		DYN_BUCKET_UNLOCK(bucket);
1704 		uma_zfree(V_dyn_parent_zone, limit);
1705 		return (NULL);
1706 	}
1707 
1708 	s->limit = limit;
1709 	CK_SLIST_INSERT_HEAD(&V_dyn_ipv6_parent[bucket], s, entry);
1710 	DYN_COUNT_INC(dyn_parent_count);
1711 	DYN_BUCKET_VERSION_BUMP(bucket, ipv6_parent_add);
1712 	DYNSTATE_CRITICAL_ENTER();
1713 	DYNSTATE_PROTECT(s);
1714 	DYN_BUCKET_UNLOCK(bucket);
1715 	return (s);
1716 }
1717 
1718 static int
1719 dyn_add_ipv6_state(void *parent, uint32_t ruleid, uint16_t rulenum,
1720     const struct ipfw_flow_id *pkt, uint32_t zoneid, const void *ulp,
1721     int pktlen, uint32_t hashval, struct ipfw_dyn_info *info,
1722     uint16_t fibnum, uint16_t kidx, uint8_t type)
1723 {
1724 	struct dyn_ipv6_state *s;
1725 	struct dyn_data *data;
1726 	uint32_t bucket;
1727 
1728 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1729 	DYN_BUCKET_LOCK(bucket);
1730 	if (info->direction == MATCH_UNKNOWN ||
1731 	    info->kidx != kidx ||
1732 	    info->hashval != hashval ||
1733 	    info->version != DYN_BUCKET_VERSION(bucket, ipv6_add)) {
1734 		/*
1735 		 * Bucket version has been changed since last lookup,
1736 		 * do lookup again to be sure that state does not exist.
1737 		 */
1738 		if (dyn_lookup_ipv6_state_locked(pkt, zoneid, ulp, pktlen,
1739 		    bucket, kidx) != 0) {
1740 			DYN_BUCKET_UNLOCK(bucket);
1741 			return (EEXIST);
1742 		}
1743 	}
1744 
1745 	data = dyn_alloc_dyndata(parent, ruleid, rulenum, pkt, ulp,
1746 	    pktlen, hashval, fibnum);
1747 	if (data == NULL) {
1748 		DYN_BUCKET_UNLOCK(bucket);
1749 		return (ENOMEM);
1750 	}
1751 
1752 	s = dyn_alloc_ipv6_state(pkt, zoneid, kidx, type);
1753 	if (s == NULL) {
1754 		DYN_BUCKET_UNLOCK(bucket);
1755 		uma_zfree(V_dyn_data_zone, data);
1756 		return (ENOMEM);
1757 	}
1758 
1759 	s->data = data;
1760 	CK_SLIST_INSERT_HEAD(&V_dyn_ipv6[bucket], s, entry);
1761 	DYN_COUNT_INC(dyn_count);
1762 	DYN_BUCKET_VERSION_BUMP(bucket, ipv6_add);
1763 	DYN_BUCKET_UNLOCK(bucket);
1764 	return (0);
1765 }
1766 #endif /* INET6 */
1767 
1768 static void *
1769 dyn_get_parent_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1770     struct ip_fw *rule, uint32_t hashval, uint32_t limit, uint16_t kidx)
1771 {
1772 	char sbuf[24];
1773 	struct dyn_parent *p;
1774 	void *ret;
1775 	uint32_t bucket, version;
1776 
1777 	p = NULL;
1778 	ret = NULL;
1779 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1780 	DYNSTATE_CRITICAL_ENTER();
1781 	if (IS_IP4_FLOW_ID(pkt)) {
1782 		struct dyn_ipv4_state *s;
1783 
1784 		version = DYN_BUCKET_VERSION(bucket, ipv4_parent_add);
1785 		s = dyn_lookup_ipv4_parent(pkt, rule, rule->id,
1786 		    rule->rulenum, bucket);
1787 		if (s == NULL) {
1788 			/*
1789 			 * Exit from critical section because dyn_add_parent()
1790 			 * will acquire bucket lock.
1791 			 */
1792 			DYNSTATE_CRITICAL_EXIT();
1793 
1794 			s = dyn_add_ipv4_parent(rule, rule->id,
1795 			    rule->rulenum, pkt, hashval, version, kidx);
1796 			if (s == NULL)
1797 				return (NULL);
1798 			/* Now we are in critical section again. */
1799 		}
1800 		ret = s;
1801 		p = s->limit;
1802 	}
1803 #ifdef INET6
1804 	else if (IS_IP6_FLOW_ID(pkt)) {
1805 		struct dyn_ipv6_state *s;
1806 
1807 		version = DYN_BUCKET_VERSION(bucket, ipv6_parent_add);
1808 		s = dyn_lookup_ipv6_parent(pkt, zoneid, rule, rule->id,
1809 		    rule->rulenum, bucket);
1810 		if (s == NULL) {
1811 			/*
1812 			 * Exit from critical section because dyn_add_parent()
1813 			 * can acquire bucket mutex.
1814 			 */
1815 			DYNSTATE_CRITICAL_EXIT();
1816 
1817 			s = dyn_add_ipv6_parent(rule, rule->id,
1818 			    rule->rulenum, pkt, zoneid, hashval, version,
1819 			    kidx);
1820 			if (s == NULL)
1821 				return (NULL);
1822 			/* Now we are in critical section again. */
1823 		}
1824 		ret = s;
1825 		p = s->limit;
1826 	}
1827 #endif
1828 	else {
1829 		DYNSTATE_CRITICAL_EXIT();
1830 		return (NULL);
1831 	}
1832 
1833 	/* Check the limit */
1834 	if (DPARENT_COUNT(p) >= limit) {
1835 		DYNSTATE_CRITICAL_EXIT();
1836 		if (V_fw_verbose && last_log != time_uptime) {
1837 			last_log = time_uptime;
1838 			snprintf(sbuf, sizeof(sbuf), "%u drop session",
1839 			    rule->rulenum);
1840 			print_dyn_rule_flags(pkt, O_LIMIT,
1841 			    LOG_SECURITY | LOG_DEBUG, sbuf,
1842 			    "too many entries");
1843 		}
1844 		return (NULL);
1845 	}
1846 
1847 	/* Take new session into account. */
1848 	DPARENT_COUNT_INC(p);
1849 	/*
1850 	 * We must exit from critical section because the following code
1851 	 * can acquire bucket mutex.
1852 	 * We rely on the 'count' field. The state will not expire
1853 	 * until it has some child states, i.e. 'count' field is not zero.
1854 	 * Return state pointer, it will be used by child states as parent.
1855 	 */
1856 	DYNSTATE_CRITICAL_EXIT();
1857 	return (ret);
1858 }
1859 
1860 static int
1861 dyn_install_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1862     uint16_t fibnum, const void *ulp, int pktlen, struct ip_fw *rule,
1863     struct ipfw_dyn_info *info, uint32_t limit, uint16_t limit_mask,
1864     uint16_t kidx, uint8_t type)
1865 {
1866 	struct ipfw_flow_id id;
1867 	uint32_t hashval, parent_hashval, ruleid, rulenum;
1868 	int ret;
1869 
1870 	MPASS(type == O_LIMIT || type == O_KEEP_STATE);
1871 
1872 	ruleid = rule->id;
1873 	rulenum = rule->rulenum;
1874 	if (type == O_LIMIT) {
1875 		/* Create masked flow id and calculate bucket */
1876 		id.addr_type = pkt->addr_type;
1877 		id.proto = pkt->proto;
1878 		id.fib = fibnum; /* unused */
1879 		id.src_port = (limit_mask & DYN_SRC_PORT) ?
1880 		    pkt->src_port: 0;
1881 		id.dst_port = (limit_mask & DYN_DST_PORT) ?
1882 		    pkt->dst_port: 0;
1883 		if (IS_IP4_FLOW_ID(pkt)) {
1884 			id.src_ip = (limit_mask & DYN_SRC_ADDR) ?
1885 			    pkt->src_ip: 0;
1886 			id.dst_ip = (limit_mask & DYN_DST_ADDR) ?
1887 			    pkt->dst_ip: 0;
1888 		}
1889 #ifdef INET6
1890 		else if (IS_IP6_FLOW_ID(pkt)) {
1891 			if (limit_mask & DYN_SRC_ADDR)
1892 				id.src_ip6 = pkt->src_ip6;
1893 			else
1894 				memset(&id.src_ip6, 0, sizeof(id.src_ip6));
1895 			if (limit_mask & DYN_DST_ADDR)
1896 				id.dst_ip6 = pkt->dst_ip6;
1897 			else
1898 				memset(&id.dst_ip6, 0, sizeof(id.dst_ip6));
1899 		}
1900 #endif
1901 		else
1902 			return (EAFNOSUPPORT);
1903 
1904 		parent_hashval = hash_parent(&id, rule);
1905 		rule = dyn_get_parent_state(&id, zoneid, rule, parent_hashval,
1906 		    limit, kidx);
1907 		if (rule == NULL) {
1908 #if 0
1909 			if (V_fw_verbose && last_log != time_uptime) {
1910 				last_log = time_uptime;
1911 				snprintf(sbuf, sizeof(sbuf),
1912 				    "%u drop session", rule->rulenum);
1913 			print_dyn_rule_flags(pkt, O_LIMIT,
1914 			    LOG_SECURITY | LOG_DEBUG, sbuf,
1915 			    "too many entries");
1916 			}
1917 #endif
1918 			return (EACCES);
1919 		}
1920 		/*
1921 		 * Limit is not reached, create new state.
1922 		 * Now rule points to parent state.
1923 		 */
1924 	}
1925 
1926 	hashval = hash_packet(pkt);
1927 	if (IS_IP4_FLOW_ID(pkt))
1928 		ret = dyn_add_ipv4_state(rule, ruleid, rulenum, pkt,
1929 		    ulp, pktlen, hashval, info, fibnum, kidx, type);
1930 #ifdef INET6
1931 	else if (IS_IP6_FLOW_ID(pkt))
1932 		ret = dyn_add_ipv6_state(rule, ruleid, rulenum, pkt,
1933 		    zoneid, ulp, pktlen, hashval, info, fibnum, kidx, type);
1934 #endif /* INET6 */
1935 	else
1936 		ret = EAFNOSUPPORT;
1937 
1938 	if (type == O_LIMIT) {
1939 		if (ret != 0) {
1940 			/*
1941 			 * We failed to create child state for O_LIMIT
1942 			 * opcode. Since we already counted it in the parent,
1943 			 * we must revert counter back. The 'rule' points to
1944 			 * parent state, use it to get dyn_parent.
1945 			 *
1946 			 * XXXAE: it should be safe to use 'rule' pointer
1947 			 * without extra lookup, parent state is referenced
1948 			 * and should not be freed.
1949 			 */
1950 			if (IS_IP4_FLOW_ID(&id))
1951 				DPARENT_COUNT_DEC(
1952 				    ((struct dyn_ipv4_state *)rule)->limit);
1953 #ifdef INET6
1954 			else if (IS_IP6_FLOW_ID(&id))
1955 				DPARENT_COUNT_DEC(
1956 				    ((struct dyn_ipv6_state *)rule)->limit);
1957 #endif
1958 		}
1959 	}
1960 	/*
1961 	 * EEXIST means that simultaneous thread has created this
1962 	 * state. Consider this as success.
1963 	 *
1964 	 * XXXAE: should we invalidate 'info' content here?
1965 	 */
1966 	if (ret == EEXIST)
1967 		return (0);
1968 	return (ret);
1969 }
1970 
1971 /*
1972  * Install dynamic state.
1973  *  chain - ipfw's instance;
1974  *  rule - the parent rule that installs the state;
1975  *  cmd - opcode that installs the state;
1976  *  args - ipfw arguments;
1977  *  ulp - upper level protocol header;
1978  *  pktlen - packet length;
1979  *  info - dynamic state lookup info;
1980  *  tablearg - tablearg id.
1981  *
1982  * Returns non-zero value (failure) if state is not installed because
1983  * of errors or because session limitations are enforced.
1984  */
1985 int
1986 ipfw_dyn_install_state(struct ip_fw_chain *chain, struct ip_fw *rule,
1987     const ipfw_insn_limit *cmd, const struct ip_fw_args *args,
1988     const void *ulp, int pktlen, struct ipfw_dyn_info *info,
1989     uint32_t tablearg)
1990 {
1991 	uint32_t limit;
1992 	uint16_t limit_mask;
1993 
1994 	if (cmd->o.opcode == O_LIMIT) {
1995 		limit = IP_FW_ARG_TABLEARG(chain, cmd->conn_limit, limit);
1996 		limit_mask = cmd->limit_mask;
1997 	} else {
1998 		limit = 0;
1999 		limit_mask = 0;
2000 	}
2001 	return (dyn_install_state(&args->f_id,
2002 #ifdef INET6
2003 	    IS_IP6_FLOW_ID(&args->f_id) ? dyn_getscopeid(args):
2004 #endif
2005 	    0, M_GETFIB(args->m), ulp, pktlen, rule, info, limit,
2006 	    limit_mask, cmd->o.arg1, cmd->o.opcode));
2007 }
2008 
2009 /*
2010  * Free safe to remove state entries from expired lists.
2011  */
2012 static void
2013 dyn_free_states(struct ip_fw_chain *chain)
2014 {
2015 	struct dyn_ipv4_state *s4, *s4n;
2016 #ifdef INET6
2017 	struct dyn_ipv6_state *s6, *s6n;
2018 #endif
2019 	int cached_count, i;
2020 
2021 	/*
2022 	 * We keep pointers to objects that are in use on each CPU
2023 	 * in the per-cpu dyn_hp pointer. When object is going to be
2024 	 * removed, first of it is unlinked from the corresponding
2025 	 * list. This leads to changing of dyn_bucket_xxx_delver version.
2026 	 * Unlinked objects is placed into corresponding dyn_expired_xxx
2027 	 * list. Reader that is going to dereference object pointer checks
2028 	 * dyn_bucket_xxx_delver version before and after storing pointer
2029 	 * into dyn_hp. If version is the same, the object is protected
2030 	 * from freeing and it is safe to dereference. Othervise reader
2031 	 * tries to iterate list again from the beginning, but this object
2032 	 * now unlinked and thus will not be accessible.
2033 	 *
2034 	 * Copy dyn_hp pointers for each CPU into dyn_hp_cache array.
2035 	 * It does not matter that some pointer can be changed in
2036 	 * time while we are copying. We need to check, that objects
2037 	 * removed in the previous pass are not in use. And if dyn_hp
2038 	 * pointer does not contain it in the time when we are copying,
2039 	 * it will not appear there, because it is already unlinked.
2040 	 * And for new pointers we will not free objects that will be
2041 	 * unlinked in this pass.
2042 	 */
2043 	cached_count = 0;
2044 	CPU_FOREACH(i) {
2045 		dyn_hp_cache[cached_count] = DYNSTATE_GET(i);
2046 		if (dyn_hp_cache[cached_count] != NULL)
2047 			cached_count++;
2048 	}
2049 
2050 	/*
2051 	 * Free expired states that are safe to free.
2052 	 * Check each entry from previous pass in the dyn_expired_xxx
2053 	 * list, if pointer to the object is in the dyn_hp_cache array,
2054 	 * keep it until next pass. Otherwise it is safe to free the
2055 	 * object.
2056 	 *
2057 	 * XXXAE: optimize this to use SLIST_REMOVE_AFTER.
2058 	 */
2059 #define	DYN_FREE_STATES(s, next, name)		do {			\
2060 	s = SLIST_FIRST(&V_dyn_expired_ ## name);			\
2061 	while (s != NULL) {						\
2062 		next = SLIST_NEXT(s, expired);				\
2063 		for (i = 0; i < cached_count; i++)			\
2064 			if (dyn_hp_cache[i] == s)			\
2065 				break;					\
2066 		if (i == cached_count) {				\
2067 			if (s->type == O_LIMIT_PARENT &&		\
2068 			    s->limit->count != 0) {			\
2069 				s = next;				\
2070 				continue;				\
2071 			}						\
2072 			SLIST_REMOVE(&V_dyn_expired_ ## name,		\
2073 			    s, dyn_ ## name ## _state, expired);	\
2074 			if (s->type == O_LIMIT_PARENT)			\
2075 				uma_zfree(V_dyn_parent_zone, s->limit);	\
2076 			else						\
2077 				uma_zfree(V_dyn_data_zone, s->data);	\
2078 			uma_zfree(V_dyn_ ## name ## _zone, s);		\
2079 		}							\
2080 		s = next;						\
2081 	}								\
2082 } while (0)
2083 
2084 	/*
2085 	 * Protect access to expired lists with DYN_EXPIRED_LOCK.
2086 	 * Userland can invoke ipfw_expire_dyn_states() to delete
2087 	 * specific states, this will lead to modification of expired
2088 	 * lists.
2089 	 *
2090 	 * XXXAE: do we need DYN_EXPIRED_LOCK? We can just use
2091 	 *	  IPFW_UH_WLOCK to protect access to these lists.
2092 	 */
2093 	DYN_EXPIRED_LOCK();
2094 	DYN_FREE_STATES(s4, s4n, ipv4);
2095 #ifdef INET6
2096 	DYN_FREE_STATES(s6, s6n, ipv6);
2097 #endif
2098 	DYN_EXPIRED_UNLOCK();
2099 #undef DYN_FREE_STATES
2100 }
2101 
2102 /*
2103  * Returns:
2104  * 0 when state is not matched by specified range;
2105  * 1 when state is matched by specified range;
2106  * 2 when state is matched by specified range and requested deletion of
2107  *   dynamic states.
2108  */
2109 static int
2110 dyn_match_range(uint16_t rulenum, uint8_t set, const ipfw_range_tlv *rt)
2111 {
2112 
2113 	MPASS(rt != NULL);
2114 	/* flush all states */
2115 	if (rt->flags & IPFW_RCFLAG_ALL) {
2116 		if (rt->flags & IPFW_RCFLAG_DYNAMIC)
2117 			return (2); /* forced */
2118 		return (1);
2119 	}
2120 	if ((rt->flags & IPFW_RCFLAG_SET) != 0 && set != rt->set)
2121 		return (0);
2122 	if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
2123 	    (rulenum < rt->start_rule || rulenum > rt->end_rule))
2124 		return (0);
2125 	if (rt->flags & IPFW_RCFLAG_DYNAMIC)
2126 		return (2);
2127 	return (1);
2128 }
2129 
2130 static void
2131 dyn_acquire_rule(struct ip_fw_chain *ch, struct dyn_data *data,
2132     struct ip_fw *rule, uint16_t kidx)
2133 {
2134 	struct dyn_state_obj *obj;
2135 
2136 	/*
2137 	 * Do not acquire reference twice.
2138 	 * This can happen when rule deletion executed for
2139 	 * the same range, but different ruleset id.
2140 	 */
2141 	if (data->flags & DYN_REFERENCED)
2142 		return;
2143 
2144 	IPFW_UH_WLOCK_ASSERT(ch);
2145 	MPASS(kidx != 0);
2146 
2147 	data->flags |= DYN_REFERENCED;
2148 	/* Reference the named object */
2149 	obj = SRV_OBJECT(ch, kidx);
2150 	obj->no.refcnt++;
2151 	MPASS(obj->no.etlv == IPFW_TLV_STATE_NAME);
2152 
2153 	/* Reference the parent rule */
2154 	rule->refcnt++;
2155 }
2156 
2157 static void
2158 dyn_release_rule(struct ip_fw_chain *ch, struct dyn_data *data,
2159     struct ip_fw *rule, uint16_t kidx)
2160 {
2161 	struct dyn_state_obj *obj;
2162 
2163 	IPFW_UH_WLOCK_ASSERT(ch);
2164 	MPASS(kidx != 0);
2165 
2166 	obj = SRV_OBJECT(ch, kidx);
2167 	if (obj->no.refcnt == 1)
2168 		dyn_destroy(ch, &obj->no);
2169 	else
2170 		obj->no.refcnt--;
2171 
2172 	if (--rule->refcnt == 1)
2173 		ipfw_free_rule(rule);
2174 }
2175 
2176 /*
2177  * We do not keep O_LIMIT_PARENT states when V_dyn_keep_states is enabled.
2178  * O_LIMIT state is created when new connection is going to be established
2179  * and there is no matching state. So, since the old parent rule was deleted
2180  * we can't create new states with old parent, and thus we can not account
2181  * new connections with already established connections, and can not do
2182  * proper limiting.
2183  */
2184 static int
2185 dyn_match_ipv4_state(struct ip_fw_chain *ch, struct dyn_ipv4_state *s,
2186     const ipfw_range_tlv *rt)
2187 {
2188 	struct ip_fw *rule;
2189 	int ret;
2190 
2191 	if (s->type == O_LIMIT_PARENT) {
2192 		rule = s->limit->parent;
2193 		return (dyn_match_range(s->limit->rulenum, rule->set, rt));
2194 	}
2195 
2196 	rule = s->data->parent;
2197 	if (s->type == O_LIMIT)
2198 		rule = ((struct dyn_ipv4_state *)rule)->limit->parent;
2199 
2200 	ret = dyn_match_range(s->data->rulenum, rule->set, rt);
2201 	if (ret == 0 || V_dyn_keep_states == 0 || ret > 1)
2202 		return (ret);
2203 
2204 	dyn_acquire_rule(ch, s->data, rule, s->kidx);
2205 	return (0);
2206 }
2207 
2208 #ifdef INET6
2209 static int
2210 dyn_match_ipv6_state(struct ip_fw_chain *ch, struct dyn_ipv6_state *s,
2211     const ipfw_range_tlv *rt)
2212 {
2213 	struct ip_fw *rule;
2214 	int ret;
2215 
2216 	if (s->type == O_LIMIT_PARENT) {
2217 		rule = s->limit->parent;
2218 		return (dyn_match_range(s->limit->rulenum, rule->set, rt));
2219 	}
2220 
2221 	rule = s->data->parent;
2222 	if (s->type == O_LIMIT)
2223 		rule = ((struct dyn_ipv6_state *)rule)->limit->parent;
2224 
2225 	ret = dyn_match_range(s->data->rulenum, rule->set, rt);
2226 	if (ret == 0 || V_dyn_keep_states == 0 || ret > 1)
2227 		return (ret);
2228 
2229 	dyn_acquire_rule(ch, s->data, rule, s->kidx);
2230 	return (0);
2231 }
2232 #endif
2233 
2234 /*
2235  * Unlink expired entries from states lists.
2236  * @rt can be used to specify the range of states for deletion.
2237  */
2238 static void
2239 dyn_expire_states(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
2240 {
2241 	struct dyn_ipv4_slist expired_ipv4;
2242 #ifdef INET6
2243 	struct dyn_ipv6_slist expired_ipv6;
2244 	struct dyn_ipv6_state *s6, *s6n, *s6p;
2245 #endif
2246 	struct dyn_ipv4_state *s4, *s4n, *s4p;
2247 	void *rule;
2248 	int bucket, removed, length, max_length;
2249 
2250 	IPFW_UH_WLOCK_ASSERT(ch);
2251 
2252 	/*
2253 	 * Unlink expired states from each bucket.
2254 	 * With acquired bucket lock iterate entries of each lists:
2255 	 * ipv4, ipv4_parent, ipv6, and ipv6_parent. Check expired time
2256 	 * and unlink entry from the list, link entry into temporary
2257 	 * expired_xxx lists then bump "del" bucket version.
2258 	 *
2259 	 * When an entry is removed, corresponding states counter is
2260 	 * decremented. If entry has O_LIMIT type, parent's reference
2261 	 * counter is decremented.
2262 	 *
2263 	 * NOTE: this function can be called from userspace context
2264 	 * when user deletes rules. In this case all matched states
2265 	 * will be forcedly unlinked. O_LIMIT_PARENT states will be kept
2266 	 * in the expired lists until reference counter become zero.
2267 	 */
2268 #define	DYN_UNLINK_STATES(s, prev, next, exp, af, name, extra)	do {	\
2269 	length = 0;							\
2270 	removed = 0;							\
2271 	prev = NULL;							\
2272 	s = CK_SLIST_FIRST(&V_dyn_ ## name [bucket]);			\
2273 	while (s != NULL) {						\
2274 		next = CK_SLIST_NEXT(s, entry);				\
2275 		if ((TIME_LEQ((s)->exp, time_uptime) && extra) ||	\
2276 		    (rt != NULL &&					\
2277 		     dyn_match_ ## af ## _state(ch, s, rt))) {		\
2278 			if (prev != NULL)				\
2279 				CK_SLIST_REMOVE_AFTER(prev, entry);	\
2280 			else						\
2281 				CK_SLIST_REMOVE_HEAD(			\
2282 				    &V_dyn_ ## name [bucket], entry);	\
2283 			removed++;					\
2284 			SLIST_INSERT_HEAD(&expired_ ## af, s, expired);	\
2285 			if (s->type == O_LIMIT_PARENT)			\
2286 				DYN_COUNT_DEC(dyn_parent_count);	\
2287 			else {						\
2288 				DYN_COUNT_DEC(dyn_count);		\
2289 				if (s->data->flags & DYN_REFERENCED) {	\
2290 					rule = s->data->parent;		\
2291 					if (s->type == O_LIMIT)		\
2292 						rule = ((__typeof(s))	\
2293 						    rule)->limit->parent;\
2294 					dyn_release_rule(ch, s->data,	\
2295 					    rule, s->kidx);		\
2296 				}					\
2297 				if (s->type == O_LIMIT)	{		\
2298 					s = s->data->parent;		\
2299 					DPARENT_COUNT_DEC(s->limit);	\
2300 				}					\
2301 			}						\
2302 		} else {						\
2303 			prev = s;					\
2304 			length++;					\
2305 		}							\
2306 		s = next;						\
2307 	}								\
2308 	if (removed != 0)						\
2309 		DYN_BUCKET_VERSION_BUMP(bucket, name ## _del);		\
2310 	if (length > max_length)				\
2311 		max_length = length;				\
2312 } while (0)
2313 
2314 	SLIST_INIT(&expired_ipv4);
2315 #ifdef INET6
2316 	SLIST_INIT(&expired_ipv6);
2317 #endif
2318 	max_length = 0;
2319 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2320 		DYN_BUCKET_LOCK(bucket);
2321 		DYN_UNLINK_STATES(s4, s4p, s4n, data->expire, ipv4, ipv4, 1);
2322 		DYN_UNLINK_STATES(s4, s4p, s4n, limit->expire, ipv4,
2323 		    ipv4_parent, (s4->limit->count == 0));
2324 #ifdef INET6
2325 		DYN_UNLINK_STATES(s6, s6p, s6n, data->expire, ipv6, ipv6, 1);
2326 		DYN_UNLINK_STATES(s6, s6p, s6n, limit->expire, ipv6,
2327 		    ipv6_parent, (s6->limit->count == 0));
2328 #endif
2329 		DYN_BUCKET_UNLOCK(bucket);
2330 	}
2331 	/* Update curr_max_length for statistics. */
2332 	V_curr_max_length = max_length;
2333 	/*
2334 	 * Concatenate temporary lists with global expired lists.
2335 	 */
2336 	DYN_EXPIRED_LOCK();
2337 	SLIST_CONCAT(&V_dyn_expired_ipv4, &expired_ipv4,
2338 	    dyn_ipv4_state, expired);
2339 #ifdef INET6
2340 	SLIST_CONCAT(&V_dyn_expired_ipv6, &expired_ipv6,
2341 	    dyn_ipv6_state, expired);
2342 #endif
2343 	DYN_EXPIRED_UNLOCK();
2344 #undef DYN_UNLINK_STATES
2345 #undef DYN_UNREF_STATES
2346 }
2347 
2348 static struct mbuf *
2349 dyn_mgethdr(int len, uint16_t fibnum)
2350 {
2351 	struct mbuf *m;
2352 
2353 	m = m_gethdr(M_NOWAIT, MT_DATA);
2354 	if (m == NULL)
2355 		return (NULL);
2356 #ifdef MAC
2357 	mac_netinet_firewall_send(m);
2358 #endif
2359 	M_SETFIB(m, fibnum);
2360 	m->m_data += max_linkhdr;
2361 	m->m_flags |= M_SKIP_FIREWALL;
2362 	m->m_len = m->m_pkthdr.len = len;
2363 	bzero(m->m_data, len);
2364 	return (m);
2365 }
2366 
2367 static void
2368 dyn_make_keepalive_ipv4(struct mbuf *m, in_addr_t src, in_addr_t dst,
2369     uint32_t seq, uint32_t ack, uint16_t sport, uint16_t dport)
2370 {
2371 	struct tcphdr *tcp;
2372 	struct ip *ip;
2373 
2374 	ip = mtod(m, struct ip *);
2375 	ip->ip_v = 4;
2376 	ip->ip_hl = sizeof(*ip) >> 2;
2377 	ip->ip_tos = IPTOS_LOWDELAY;
2378 	ip->ip_len = htons(m->m_len);
2379 	ip->ip_off |= htons(IP_DF);
2380 	ip->ip_ttl = V_ip_defttl;
2381 	ip->ip_p = IPPROTO_TCP;
2382 	ip->ip_src.s_addr = htonl(src);
2383 	ip->ip_dst.s_addr = htonl(dst);
2384 
2385 	tcp = mtodo(m, sizeof(struct ip));
2386 	tcp->th_sport = htons(sport);
2387 	tcp->th_dport = htons(dport);
2388 	tcp->th_off = sizeof(struct tcphdr) >> 2;
2389 	tcp->th_seq = htonl(seq);
2390 	tcp->th_ack = htonl(ack);
2391 	tcp->th_flags = TH_ACK;
2392 	tcp->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2393 	    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
2394 
2395 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2396 	m->m_pkthdr.csum_flags = CSUM_TCP;
2397 }
2398 
2399 static void
2400 dyn_enqueue_keepalive_ipv4(struct mbufq *q, const struct dyn_ipv4_state *s)
2401 {
2402 	struct mbuf *m;
2403 
2404 	if ((s->data->state & ACK_FWD) == 0 && s->data->ack_fwd > 0) {
2405 		m = dyn_mgethdr(sizeof(struct ip) + sizeof(struct tcphdr),
2406 		    s->data->fibnum);
2407 		if (m != NULL) {
2408 			dyn_make_keepalive_ipv4(m, s->dst, s->src,
2409 			    s->data->ack_fwd - 1, s->data->ack_rev,
2410 			    s->dport, s->sport);
2411 			if (mbufq_enqueue(q, m)) {
2412 				m_freem(m);
2413 				log(LOG_DEBUG, "ipfw: limit for IPv4 "
2414 				    "keepalive queue is reached.\n");
2415 				return;
2416 			}
2417 		}
2418 	}
2419 
2420 	if ((s->data->state & ACK_REV) == 0 && s->data->ack_rev > 0) {
2421 		m = dyn_mgethdr(sizeof(struct ip) + sizeof(struct tcphdr),
2422 		    s->data->fibnum);
2423 		if (m != NULL) {
2424 			dyn_make_keepalive_ipv4(m, s->src, s->dst,
2425 			    s->data->ack_rev - 1, s->data->ack_fwd,
2426 			    s->sport, s->dport);
2427 			if (mbufq_enqueue(q, m)) {
2428 				m_freem(m);
2429 				log(LOG_DEBUG, "ipfw: limit for IPv4 "
2430 				    "keepalive queue is reached.\n");
2431 				return;
2432 			}
2433 		}
2434 	}
2435 }
2436 
2437 /*
2438  * Prepare and send keep-alive packets.
2439  */
2440 static void
2441 dyn_send_keepalive_ipv4(struct ip_fw_chain *chain)
2442 {
2443 	struct mbufq q;
2444 	struct mbuf *m;
2445 	struct dyn_ipv4_state *s;
2446 	uint32_t bucket;
2447 
2448 	mbufq_init(&q, INT_MAX);
2449 	IPFW_UH_RLOCK(chain);
2450 	/*
2451 	 * It is safe to not use hazard pointer and just do lockless
2452 	 * access to the lists, because states entries can not be deleted
2453 	 * while we hold IPFW_UH_RLOCK.
2454 	 */
2455 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2456 		CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
2457 			/*
2458 			 * Only established TCP connections that will
2459 			 * become expired withing dyn_keepalive_interval.
2460 			 */
2461 			if (s->proto != IPPROTO_TCP ||
2462 			    (s->data->state & BOTH_SYN) != BOTH_SYN ||
2463 			    TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
2464 				s->data->expire))
2465 				continue;
2466 			dyn_enqueue_keepalive_ipv4(&q, s);
2467 		}
2468 	}
2469 	IPFW_UH_RUNLOCK(chain);
2470 	while ((m = mbufq_dequeue(&q)) != NULL)
2471 		ip_output(m, NULL, NULL, 0, NULL, NULL);
2472 }
2473 
2474 #ifdef INET6
2475 static void
2476 dyn_make_keepalive_ipv6(struct mbuf *m, const struct in6_addr *src,
2477     const struct in6_addr *dst, uint32_t zoneid, uint32_t seq, uint32_t ack,
2478     uint16_t sport, uint16_t dport)
2479 {
2480 	struct tcphdr *tcp;
2481 	struct ip6_hdr *ip6;
2482 
2483 	ip6 = mtod(m, struct ip6_hdr *);
2484 	ip6->ip6_vfc |= IPV6_VERSION;
2485 	ip6->ip6_plen = htons(sizeof(struct tcphdr));
2486 	ip6->ip6_nxt = IPPROTO_TCP;
2487 	ip6->ip6_hlim = IPV6_DEFHLIM;
2488 	ip6->ip6_src = *src;
2489 	if (IN6_IS_ADDR_LINKLOCAL(src))
2490 		ip6->ip6_src.s6_addr16[1] = htons(zoneid & 0xffff);
2491 	ip6->ip6_dst = *dst;
2492 	if (IN6_IS_ADDR_LINKLOCAL(dst))
2493 		ip6->ip6_dst.s6_addr16[1] = htons(zoneid & 0xffff);
2494 
2495 	tcp = mtodo(m, sizeof(struct ip6_hdr));
2496 	tcp->th_sport = htons(sport);
2497 	tcp->th_dport = htons(dport);
2498 	tcp->th_off = sizeof(struct tcphdr) >> 2;
2499 	tcp->th_seq = htonl(seq);
2500 	tcp->th_ack = htonl(ack);
2501 	tcp->th_flags = TH_ACK;
2502 	tcp->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr),
2503 	    IPPROTO_TCP, 0);
2504 
2505 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2506 	m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2507 }
2508 
2509 static void
2510 dyn_enqueue_keepalive_ipv6(struct mbufq *q, const struct dyn_ipv6_state *s)
2511 {
2512 	struct mbuf *m;
2513 
2514 	if ((s->data->state & ACK_FWD) == 0 && s->data->ack_fwd > 0) {
2515 		m = dyn_mgethdr(sizeof(struct ip6_hdr) +
2516 		    sizeof(struct tcphdr), s->data->fibnum);
2517 		if (m != NULL) {
2518 			dyn_make_keepalive_ipv6(m, &s->dst, &s->src,
2519 			    s->zoneid, s->data->ack_fwd - 1, s->data->ack_rev,
2520 			    s->dport, s->sport);
2521 			if (mbufq_enqueue(q, m)) {
2522 				m_freem(m);
2523 				log(LOG_DEBUG, "ipfw: limit for IPv6 "
2524 				    "keepalive queue is reached.\n");
2525 				return;
2526 			}
2527 		}
2528 	}
2529 
2530 	if ((s->data->state & ACK_REV) == 0 && s->data->ack_rev > 0) {
2531 		m = dyn_mgethdr(sizeof(struct ip6_hdr) +
2532 		    sizeof(struct tcphdr), s->data->fibnum);
2533 		if (m != NULL) {
2534 			dyn_make_keepalive_ipv6(m, &s->src, &s->dst,
2535 			    s->zoneid, s->data->ack_rev - 1, s->data->ack_fwd,
2536 			    s->sport, s->dport);
2537 			if (mbufq_enqueue(q, m)) {
2538 				m_freem(m);
2539 				log(LOG_DEBUG, "ipfw: limit for IPv6 "
2540 				    "keepalive queue is reached.\n");
2541 				return;
2542 			}
2543 		}
2544 	}
2545 }
2546 
2547 static void
2548 dyn_send_keepalive_ipv6(struct ip_fw_chain *chain)
2549 {
2550 	struct mbufq q;
2551 	struct mbuf *m;
2552 	struct dyn_ipv6_state *s;
2553 	uint32_t bucket;
2554 
2555 	mbufq_init(&q, INT_MAX);
2556 	IPFW_UH_RLOCK(chain);
2557 	/*
2558 	 * It is safe to not use hazard pointer and just do lockless
2559 	 * access to the lists, because states entries can not be deleted
2560 	 * while we hold IPFW_UH_RLOCK.
2561 	 */
2562 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2563 		CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
2564 			/*
2565 			 * Only established TCP connections that will
2566 			 * become expired withing dyn_keepalive_interval.
2567 			 */
2568 			if (s->proto != IPPROTO_TCP ||
2569 			    (s->data->state & BOTH_SYN) != BOTH_SYN ||
2570 			    TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
2571 				s->data->expire))
2572 				continue;
2573 			dyn_enqueue_keepalive_ipv6(&q, s);
2574 		}
2575 	}
2576 	IPFW_UH_RUNLOCK(chain);
2577 	while ((m = mbufq_dequeue(&q)) != NULL)
2578 		ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2579 }
2580 #endif /* INET6 */
2581 
2582 static void
2583 dyn_grow_hashtable(struct ip_fw_chain *chain, uint32_t new, int flags)
2584 {
2585 #ifdef INET6
2586 	struct dyn_ipv6ck_slist *ipv6, *ipv6_parent;
2587 	uint32_t *ipv6_add, *ipv6_del, *ipv6_parent_add, *ipv6_parent_del;
2588 	struct dyn_ipv6_state *s6;
2589 #endif
2590 	struct dyn_ipv4ck_slist *ipv4, *ipv4_parent;
2591 	uint32_t *ipv4_add, *ipv4_del, *ipv4_parent_add, *ipv4_parent_del;
2592 	struct dyn_ipv4_state *s4;
2593 	struct mtx *bucket_lock;
2594 	void *tmp;
2595 	uint32_t bucket;
2596 
2597 	MPASS(powerof2(new));
2598 	DYN_DEBUG("grow hash size %u -> %u", V_curr_dyn_buckets, new);
2599 	/*
2600 	 * Allocate and initialize new lists.
2601 	 */
2602 	bucket_lock = malloc(new * sizeof(struct mtx), M_IPFW,
2603 	    flags | M_ZERO);
2604 	if (bucket_lock == NULL)
2605 		return;
2606 
2607 	ipv4 = ipv4_parent = NULL;
2608 	ipv4_add = ipv4_del = ipv4_parent_add = ipv4_parent_del = NULL;
2609 #ifdef INET6
2610 	ipv6 = ipv6_parent = NULL;
2611 	ipv6_add = ipv6_del = ipv6_parent_add = ipv6_parent_del = NULL;
2612 #endif
2613 
2614 	ipv4 = malloc(new * sizeof(struct dyn_ipv4ck_slist), M_IPFW,
2615 	    flags | M_ZERO);
2616 	if (ipv4 == NULL)
2617 		goto bad;
2618 	ipv4_parent = malloc(new * sizeof(struct dyn_ipv4ck_slist), M_IPFW,
2619 	    flags | M_ZERO);
2620 	if (ipv4_parent == NULL)
2621 		goto bad;
2622 	ipv4_add = malloc(new * sizeof(uint32_t), M_IPFW, flags | M_ZERO);
2623 	if (ipv4_add == NULL)
2624 		goto bad;
2625 	ipv4_del = malloc(new * sizeof(uint32_t), M_IPFW, flags | M_ZERO);
2626 	if (ipv4_del == NULL)
2627 		goto bad;
2628 	ipv4_parent_add = malloc(new * sizeof(uint32_t), M_IPFW,
2629 	    flags | M_ZERO);
2630 	if (ipv4_parent_add == NULL)
2631 		goto bad;
2632 	ipv4_parent_del = malloc(new * sizeof(uint32_t), M_IPFW,
2633 	    flags | M_ZERO);
2634 	if (ipv4_parent_del == NULL)
2635 		goto bad;
2636 #ifdef INET6
2637 	ipv6 = malloc(new * sizeof(struct dyn_ipv6ck_slist), M_IPFW,
2638 	    flags | M_ZERO);
2639 	if (ipv6 == NULL)
2640 		goto bad;
2641 	ipv6_parent = malloc(new * sizeof(struct dyn_ipv6ck_slist), M_IPFW,
2642 	    flags | M_ZERO);
2643 	if (ipv6_parent == NULL)
2644 		goto bad;
2645 	ipv6_add = malloc(new * sizeof(uint32_t), M_IPFW, flags | M_ZERO);
2646 	if (ipv6_add == NULL)
2647 		goto bad;
2648 	ipv6_del = malloc(new * sizeof(uint32_t), M_IPFW, flags | M_ZERO);
2649 	if (ipv6_del == NULL)
2650 		goto bad;
2651 	ipv6_parent_add = malloc(new * sizeof(uint32_t), M_IPFW,
2652 	    flags | M_ZERO);
2653 	if (ipv6_parent_add == NULL)
2654 		goto bad;
2655 	ipv6_parent_del = malloc(new * sizeof(uint32_t), M_IPFW,
2656 	    flags | M_ZERO);
2657 	if (ipv6_parent_del == NULL)
2658 		goto bad;
2659 #endif
2660 	for (bucket = 0; bucket < new; bucket++) {
2661 		DYN_BUCKET_LOCK_INIT(bucket_lock, bucket);
2662 		CK_SLIST_INIT(&ipv4[bucket]);
2663 		CK_SLIST_INIT(&ipv4_parent[bucket]);
2664 #ifdef INET6
2665 		CK_SLIST_INIT(&ipv6[bucket]);
2666 		CK_SLIST_INIT(&ipv6_parent[bucket]);
2667 #endif
2668 	}
2669 
2670 #define DYN_RELINK_STATES(s, hval, i, head, ohead)	do {		\
2671 	while ((s = CK_SLIST_FIRST(&V_dyn_ ## ohead[i])) != NULL) {	\
2672 		CK_SLIST_REMOVE_HEAD(&V_dyn_ ## ohead[i], entry);	\
2673 		CK_SLIST_INSERT_HEAD(&head[DYN_BUCKET(s->hval, new)],	\
2674 		    s, entry);						\
2675 	}								\
2676 } while (0)
2677 	/*
2678 	 * Prevent rules changing from userland.
2679 	 */
2680 	IPFW_UH_WLOCK(chain);
2681 	/*
2682 	 * Hold traffic processing until we finish resize to
2683 	 * prevent access to states lists.
2684 	 */
2685 	IPFW_WLOCK(chain);
2686 	/* Re-link all dynamic states */
2687 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2688 		DYN_RELINK_STATES(s4, data->hashval, bucket, ipv4, ipv4);
2689 		DYN_RELINK_STATES(s4, limit->hashval, bucket, ipv4_parent,
2690 		    ipv4_parent);
2691 #ifdef INET6
2692 		DYN_RELINK_STATES(s6, data->hashval, bucket, ipv6, ipv6);
2693 		DYN_RELINK_STATES(s6, limit->hashval, bucket, ipv6_parent,
2694 		    ipv6_parent);
2695 #endif
2696 	}
2697 
2698 #define	DYN_SWAP_PTR(old, new, tmp)	do {		\
2699 	tmp = old;					\
2700 	old = new;					\
2701 	new = tmp;					\
2702 } while (0)
2703 	/* Swap pointers */
2704 	DYN_SWAP_PTR(V_dyn_bucket_lock, bucket_lock, tmp);
2705 	DYN_SWAP_PTR(V_dyn_ipv4, ipv4, tmp);
2706 	DYN_SWAP_PTR(V_dyn_ipv4_parent, ipv4_parent, tmp);
2707 	DYN_SWAP_PTR(V_dyn_ipv4_add, ipv4_add, tmp);
2708 	DYN_SWAP_PTR(V_dyn_ipv4_parent_add, ipv4_parent_add, tmp);
2709 	DYN_SWAP_PTR(V_dyn_ipv4_del, ipv4_del, tmp);
2710 	DYN_SWAP_PTR(V_dyn_ipv4_parent_del, ipv4_parent_del, tmp);
2711 
2712 #ifdef INET6
2713 	DYN_SWAP_PTR(V_dyn_ipv6, ipv6, tmp);
2714 	DYN_SWAP_PTR(V_dyn_ipv6_parent, ipv6_parent, tmp);
2715 	DYN_SWAP_PTR(V_dyn_ipv6_add, ipv6_add, tmp);
2716 	DYN_SWAP_PTR(V_dyn_ipv6_parent_add, ipv6_parent_add, tmp);
2717 	DYN_SWAP_PTR(V_dyn_ipv6_del, ipv6_del, tmp);
2718 	DYN_SWAP_PTR(V_dyn_ipv6_parent_del, ipv6_parent_del, tmp);
2719 #endif
2720 	bucket = V_curr_dyn_buckets;
2721 	V_curr_dyn_buckets = new;
2722 
2723 	IPFW_WUNLOCK(chain);
2724 	IPFW_UH_WUNLOCK(chain);
2725 
2726 	/* Release old resources */
2727 	while (bucket-- != 0)
2728 		DYN_BUCKET_LOCK_DESTROY(bucket_lock, bucket);
2729 bad:
2730 	free(bucket_lock, M_IPFW);
2731 	free(ipv4, M_IPFW);
2732 	free(ipv4_parent, M_IPFW);
2733 	free(ipv4_add, M_IPFW);
2734 	free(ipv4_parent_add, M_IPFW);
2735 	free(ipv4_del, M_IPFW);
2736 	free(ipv4_parent_del, M_IPFW);
2737 #ifdef INET6
2738 	free(ipv6, M_IPFW);
2739 	free(ipv6_parent, M_IPFW);
2740 	free(ipv6_add, M_IPFW);
2741 	free(ipv6_parent_add, M_IPFW);
2742 	free(ipv6_del, M_IPFW);
2743 	free(ipv6_parent_del, M_IPFW);
2744 #endif
2745 }
2746 
2747 /*
2748  * This function is used to perform various maintenance
2749  * on dynamic hash lists. Currently it is called every second.
2750  */
2751 static void
2752 dyn_tick(void *vnetx)
2753 {
2754 	struct epoch_tracker et;
2755 	uint32_t buckets;
2756 
2757 	CURVNET_SET((struct vnet *)vnetx);
2758 	/*
2759 	 * First free states unlinked in previous passes.
2760 	 */
2761 	dyn_free_states(&V_layer3_chain);
2762 	/*
2763 	 * Now unlink others expired states.
2764 	 * We use IPFW_UH_WLOCK to avoid concurrent call of
2765 	 * dyn_expire_states(). It is the only function that does
2766 	 * deletion of state entries from states lists.
2767 	 */
2768 	IPFW_UH_WLOCK(&V_layer3_chain);
2769 	dyn_expire_states(&V_layer3_chain, NULL);
2770 	IPFW_UH_WUNLOCK(&V_layer3_chain);
2771 	/*
2772 	 * Send keepalives if they are enabled and the time has come.
2773 	 */
2774 	if (V_dyn_keepalive != 0 &&
2775 	    V_dyn_keepalive_last + V_dyn_keepalive_period <= time_uptime) {
2776 		V_dyn_keepalive_last = time_uptime;
2777 		NET_EPOCH_ENTER(et);
2778 		dyn_send_keepalive_ipv4(&V_layer3_chain);
2779 #ifdef INET6
2780 		dyn_send_keepalive_ipv6(&V_layer3_chain);
2781 #endif
2782 		NET_EPOCH_EXIT(et);
2783 	}
2784 	/*
2785 	 * Check if we need to resize the hash:
2786 	 * if current number of states exceeds number of buckets in hash,
2787 	 * and dyn_buckets_max permits to grow the number of buckets, then
2788 	 * do it. Grow hash size to the minimum power of 2 which is bigger
2789 	 * than current states count.
2790 	 */
2791 	if (V_curr_dyn_buckets < V_dyn_buckets_max &&
2792 	    (V_curr_dyn_buckets < V_dyn_count / 2 || (
2793 	    V_curr_dyn_buckets < V_dyn_count && V_curr_max_length > 8))) {
2794 		buckets = 1 << fls(V_dyn_count);
2795 		if (buckets > V_dyn_buckets_max)
2796 			buckets = V_dyn_buckets_max;
2797 		dyn_grow_hashtable(&V_layer3_chain, buckets, M_NOWAIT);
2798 	}
2799 
2800 	callout_reset_on(&V_dyn_timeout, hz, dyn_tick, vnetx, 0);
2801 	CURVNET_RESTORE();
2802 }
2803 
2804 void
2805 ipfw_expire_dyn_states(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
2806 {
2807 	/*
2808 	 * Do not perform any checks if we currently have no dynamic states
2809 	 */
2810 	if (V_dyn_count == 0)
2811 		return;
2812 
2813 	IPFW_UH_WLOCK_ASSERT(chain);
2814 	dyn_expire_states(chain, rt);
2815 }
2816 
2817 /*
2818  * Pass through all states and reset eaction for orphaned rules.
2819  */
2820 void
2821 ipfw_dyn_reset_eaction(struct ip_fw_chain *ch, uint16_t eaction_id,
2822     uint16_t default_id, uint16_t instance_id)
2823 {
2824 #ifdef INET6
2825 	struct dyn_ipv6_state *s6;
2826 #endif
2827 	struct dyn_ipv4_state *s4;
2828 	struct ip_fw *rule;
2829 	uint32_t bucket;
2830 
2831 #define	DYN_RESET_EACTION(s, h, b)					\
2832 	CK_SLIST_FOREACH(s, &V_dyn_ ## h[b], entry) {			\
2833 		if ((s->data->flags & DYN_REFERENCED) == 0)		\
2834 			continue;					\
2835 		rule = s->data->parent;					\
2836 		if (s->type == O_LIMIT)					\
2837 			rule = ((__typeof(s))rule)->limit->parent;	\
2838 		ipfw_reset_eaction(ch, rule, eaction_id,		\
2839 		    default_id, instance_id);				\
2840 	}
2841 
2842 	IPFW_UH_WLOCK_ASSERT(ch);
2843 	if (V_dyn_count == 0)
2844 		return;
2845 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2846 		DYN_RESET_EACTION(s4, ipv4, bucket);
2847 #ifdef INET6
2848 		DYN_RESET_EACTION(s6, ipv6, bucket);
2849 #endif
2850 	}
2851 }
2852 
2853 /*
2854  * Returns size of dynamic states in legacy format
2855  */
2856 int
2857 ipfw_dyn_len(void)
2858 {
2859 
2860 	return ((V_dyn_count + V_dyn_parent_count) * sizeof(ipfw_dyn_rule));
2861 }
2862 
2863 /*
2864  * Returns number of dynamic states.
2865  * Marks every named object index used by dynamic states with bit in @bmask.
2866  * Returns number of named objects accounted in bmask via @nocnt.
2867  * Used by dump format v1 (current).
2868  */
2869 uint32_t
2870 ipfw_dyn_get_count(uint32_t *bmask, int *nocnt)
2871 {
2872 #ifdef INET6
2873 	struct dyn_ipv6_state *s6;
2874 #endif
2875 	struct dyn_ipv4_state *s4;
2876 	uint32_t bucket;
2877 
2878 #define	DYN_COUNT_OBJECTS(s, h, b)					\
2879 	CK_SLIST_FOREACH(s, &V_dyn_ ## h[b], entry) {			\
2880 		MPASS(s->kidx != 0);					\
2881 		if (ipfw_mark_object_kidx(bmask, IPFW_TLV_STATE_NAME,	\
2882 		    s->kidx) != 0)					\
2883 			(*nocnt)++;					\
2884 	}
2885 
2886 	IPFW_UH_RLOCK_ASSERT(&V_layer3_chain);
2887 
2888 	/* No need to pass through all the buckets. */
2889 	*nocnt = 0;
2890 	if (V_dyn_count + V_dyn_parent_count == 0)
2891 		return (0);
2892 
2893 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2894 		DYN_COUNT_OBJECTS(s4, ipv4, bucket);
2895 #ifdef INET6
2896 		DYN_COUNT_OBJECTS(s6, ipv6, bucket);
2897 #endif
2898 	}
2899 
2900 	return (V_dyn_count + V_dyn_parent_count);
2901 }
2902 
2903 /*
2904  * Check if rule contains at least one dynamic opcode.
2905  *
2906  * Returns 1 if such opcode is found, 0 otherwise.
2907  */
2908 int
2909 ipfw_is_dyn_rule(struct ip_fw *rule)
2910 {
2911 	int cmdlen, l;
2912 	ipfw_insn *cmd;
2913 
2914 	l = rule->cmd_len;
2915 	cmd = rule->cmd;
2916 	cmdlen = 0;
2917 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2918 		cmdlen = F_LEN(cmd);
2919 
2920 		switch (cmd->opcode) {
2921 		case O_LIMIT:
2922 		case O_KEEP_STATE:
2923 		case O_PROBE_STATE:
2924 		case O_CHECK_STATE:
2925 			return (1);
2926 		}
2927 	}
2928 
2929 	return (0);
2930 }
2931 
2932 static void
2933 dyn_export_parent(const struct dyn_parent *p, uint16_t kidx, uint8_t set,
2934     ipfw_dyn_rule *dst)
2935 {
2936 
2937 	dst->dyn_type = O_LIMIT_PARENT;
2938 	dst->kidx = kidx;
2939 	dst->count = (uint16_t)DPARENT_COUNT(p);
2940 	dst->expire = TIME_LEQ(p->expire, time_uptime) ?  0:
2941 	    p->expire - time_uptime;
2942 
2943 	/* 'rule' is used to pass up the rule number and set */
2944 	memcpy(&dst->rule, &p->rulenum, sizeof(p->rulenum));
2945 
2946 	/* store set number into high word of dst->rule pointer. */
2947 	memcpy((char *)&dst->rule + sizeof(p->rulenum), &set, sizeof(set));
2948 
2949 	/* unused fields */
2950 	dst->pcnt = 0;
2951 	dst->bcnt = 0;
2952 	dst->parent = NULL;
2953 	dst->state = 0;
2954 	dst->ack_fwd = 0;
2955 	dst->ack_rev = 0;
2956 	dst->bucket = p->hashval;
2957 	/*
2958 	 * The legacy userland code will interpret a NULL here as a marker
2959 	 * for the last dynamic rule.
2960 	 */
2961 	dst->next = (ipfw_dyn_rule *)1;
2962 }
2963 
2964 static void
2965 dyn_export_data(const struct dyn_data *data, uint16_t kidx, uint8_t type,
2966     uint8_t set, ipfw_dyn_rule *dst)
2967 {
2968 
2969 	dst->dyn_type = type;
2970 	dst->kidx = kidx;
2971 	dst->pcnt = data->pcnt_fwd + data->pcnt_rev;
2972 	dst->bcnt = data->bcnt_fwd + data->bcnt_rev;
2973 	dst->expire = TIME_LEQ(data->expire, time_uptime) ?  0:
2974 	    data->expire - time_uptime;
2975 
2976 	/* 'rule' is used to pass up the rule number and set */
2977 	memcpy(&dst->rule, &data->rulenum, sizeof(data->rulenum));
2978 
2979 	/* store set number into high word of dst->rule pointer. */
2980 	memcpy((char *)&dst->rule + sizeof(data->rulenum), &set, sizeof(set));
2981 
2982 	dst->state = data->state;
2983 	if (data->flags & DYN_REFERENCED)
2984 		dst->state |= IPFW_DYN_ORPHANED;
2985 
2986 	/* unused fields */
2987 	dst->parent = NULL;
2988 	dst->ack_fwd = data->ack_fwd;
2989 	dst->ack_rev = data->ack_rev;
2990 	dst->count = 0;
2991 	dst->bucket = data->hashval;
2992 	/*
2993 	 * The legacy userland code will interpret a NULL here as a marker
2994 	 * for the last dynamic rule.
2995 	 */
2996 	dst->next = (ipfw_dyn_rule *)1;
2997 }
2998 
2999 static void
3000 dyn_export_ipv4_state(const struct dyn_ipv4_state *s, ipfw_dyn_rule *dst)
3001 {
3002 	struct ip_fw *rule;
3003 
3004 	switch (s->type) {
3005 	case O_LIMIT_PARENT:
3006 		rule = s->limit->parent;
3007 		dyn_export_parent(s->limit, s->kidx, rule->set, dst);
3008 		break;
3009 	default:
3010 		rule = s->data->parent;
3011 		if (s->type == O_LIMIT)
3012 			rule = ((struct dyn_ipv4_state *)rule)->limit->parent;
3013 		dyn_export_data(s->data, s->kidx, s->type, rule->set, dst);
3014 	}
3015 
3016 	dst->id.dst_ip = s->dst;
3017 	dst->id.src_ip = s->src;
3018 	dst->id.dst_port = s->dport;
3019 	dst->id.src_port = s->sport;
3020 	dst->id.fib = s->data->fibnum;
3021 	dst->id.proto = s->proto;
3022 	dst->id._flags = 0;
3023 	dst->id.addr_type = 4;
3024 
3025 	memset(&dst->id.dst_ip6, 0, sizeof(dst->id.dst_ip6));
3026 	memset(&dst->id.src_ip6, 0, sizeof(dst->id.src_ip6));
3027 	dst->id.flow_id6 = dst->id.extra = 0;
3028 }
3029 
3030 #ifdef INET6
3031 static void
3032 dyn_export_ipv6_state(const struct dyn_ipv6_state *s, ipfw_dyn_rule *dst)
3033 {
3034 	struct ip_fw *rule;
3035 
3036 	switch (s->type) {
3037 	case O_LIMIT_PARENT:
3038 		rule = s->limit->parent;
3039 		dyn_export_parent(s->limit, s->kidx, rule->set, dst);
3040 		break;
3041 	default:
3042 		rule = s->data->parent;
3043 		if (s->type == O_LIMIT)
3044 			rule = ((struct dyn_ipv6_state *)rule)->limit->parent;
3045 		dyn_export_data(s->data, s->kidx, s->type, rule->set, dst);
3046 	}
3047 
3048 	dst->id.src_ip6 = s->src;
3049 	dst->id.dst_ip6 = s->dst;
3050 	dst->id.dst_port = s->dport;
3051 	dst->id.src_port = s->sport;
3052 	dst->id.fib = s->data->fibnum;
3053 	dst->id.proto = s->proto;
3054 	dst->id._flags = 0;
3055 	dst->id.addr_type = 6;
3056 
3057 	dst->id.dst_ip = dst->id.src_ip = 0;
3058 	dst->id.flow_id6 = dst->id.extra = 0;
3059 }
3060 #endif /* INET6 */
3061 
3062 /*
3063  * Fills the buffer given by @sd with dynamic states.
3064  * Used by dump format v1 (current).
3065  *
3066  * Returns 0 on success.
3067  */
3068 int
3069 ipfw_dump_states(struct ip_fw_chain *chain, struct sockopt_data *sd)
3070 {
3071 #ifdef INET6
3072 	struct dyn_ipv6_state *s6;
3073 #endif
3074 	struct dyn_ipv4_state *s4;
3075 	ipfw_obj_dyntlv *dst, *last;
3076 	ipfw_obj_ctlv *ctlv;
3077 	uint32_t bucket;
3078 
3079 	if (V_dyn_count == 0)
3080 		return (0);
3081 
3082 	/*
3083 	 * IPFW_UH_RLOCK garantees that another userland request
3084 	 * and callout thread will not delete entries from states
3085 	 * lists.
3086 	 */
3087 	IPFW_UH_RLOCK_ASSERT(chain);
3088 
3089 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
3090 	if (ctlv == NULL)
3091 		return (ENOMEM);
3092 	ctlv->head.type = IPFW_TLV_DYNSTATE_LIST;
3093 	ctlv->objsize = sizeof(ipfw_obj_dyntlv);
3094 	last = NULL;
3095 
3096 #define	DYN_EXPORT_STATES(s, af, h, b)				\
3097 	CK_SLIST_FOREACH(s, &V_dyn_ ## h[b], entry) {			\
3098 		dst = (ipfw_obj_dyntlv *)ipfw_get_sopt_space(sd,	\
3099 		    sizeof(ipfw_obj_dyntlv));				\
3100 		if (dst == NULL)					\
3101 			return (ENOMEM);				\
3102 		dyn_export_ ## af ## _state(s, &dst->state);		\
3103 		dst->head.length = sizeof(ipfw_obj_dyntlv);		\
3104 		dst->head.type = IPFW_TLV_DYN_ENT;			\
3105 		last = dst;						\
3106 	}
3107 
3108 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
3109 		DYN_EXPORT_STATES(s4, ipv4, ipv4_parent, bucket);
3110 		DYN_EXPORT_STATES(s4, ipv4, ipv4, bucket);
3111 #ifdef INET6
3112 		DYN_EXPORT_STATES(s6, ipv6, ipv6_parent, bucket);
3113 		DYN_EXPORT_STATES(s6, ipv6, ipv6, bucket);
3114 #endif /* INET6 */
3115 	}
3116 
3117 	/* mark last dynamic rule */
3118 	if (last != NULL)
3119 		last->head.flags = IPFW_DF_LAST; /* XXX: unused */
3120 	return (0);
3121 #undef DYN_EXPORT_STATES
3122 }
3123 
3124 /*
3125  * Fill given buffer with dynamic states (legacy format).
3126  * IPFW_UH_RLOCK has to be held while calling.
3127  */
3128 void
3129 ipfw_get_dynamic(struct ip_fw_chain *chain, char **pbp, const char *ep)
3130 {
3131 #ifdef INET6
3132 	struct dyn_ipv6_state *s6;
3133 #endif
3134 	struct dyn_ipv4_state *s4;
3135 	ipfw_dyn_rule *p, *last = NULL;
3136 	char *bp;
3137 	uint32_t bucket;
3138 
3139 	if (V_dyn_count == 0)
3140 		return;
3141 	bp = *pbp;
3142 
3143 	IPFW_UH_RLOCK_ASSERT(chain);
3144 
3145 #define	DYN_EXPORT_STATES(s, af, head, b)				\
3146 	CK_SLIST_FOREACH(s, &V_dyn_ ## head[b], entry) {		\
3147 		if (bp + sizeof(*p) > ep)				\
3148 			break;						\
3149 		p = (ipfw_dyn_rule *)bp;				\
3150 		dyn_export_ ## af ## _state(s, p);			\
3151 		last = p;						\
3152 		bp += sizeof(*p);					\
3153 	}
3154 
3155 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
3156 		DYN_EXPORT_STATES(s4, ipv4, ipv4_parent, bucket);
3157 		DYN_EXPORT_STATES(s4, ipv4, ipv4, bucket);
3158 #ifdef INET6
3159 		DYN_EXPORT_STATES(s6, ipv6, ipv6_parent, bucket);
3160 		DYN_EXPORT_STATES(s6, ipv6, ipv6, bucket);
3161 #endif /* INET6 */
3162 	}
3163 
3164 	if (last != NULL) /* mark last dynamic rule */
3165 		last->next = NULL;
3166 	*pbp = bp;
3167 #undef DYN_EXPORT_STATES
3168 }
3169 
3170 void
3171 ipfw_dyn_init(struct ip_fw_chain *chain)
3172 {
3173 
3174 #ifdef IPFIREWALL_JENKINSHASH
3175 	V_dyn_hashseed = arc4random();
3176 #endif
3177 	V_dyn_max = 16384;		/* max # of states */
3178 	V_dyn_parent_max = 4096;	/* max # of parent states */
3179 	V_dyn_buckets_max = 8192;	/* must be power of 2 */
3180 
3181 	V_dyn_ack_lifetime = 300;
3182 	V_dyn_syn_lifetime = 20;
3183 	V_dyn_fin_lifetime = 1;
3184 	V_dyn_rst_lifetime = 1;
3185 	V_dyn_udp_lifetime = 10;
3186 	V_dyn_short_lifetime = 5;
3187 
3188 	V_dyn_keepalive_interval = 20;
3189 	V_dyn_keepalive_period = 5;
3190 	V_dyn_keepalive = 1;		/* send keepalives */
3191 	V_dyn_keepalive_last = time_uptime;
3192 
3193 	V_dyn_data_zone = uma_zcreate("IPFW dynamic states data",
3194 	    sizeof(struct dyn_data), NULL, NULL, NULL, NULL,
3195 	    UMA_ALIGN_PTR, 0);
3196 	uma_zone_set_max(V_dyn_data_zone, V_dyn_max);
3197 
3198 	V_dyn_parent_zone = uma_zcreate("IPFW parent dynamic states",
3199 	    sizeof(struct dyn_parent), NULL, NULL, NULL, NULL,
3200 	    UMA_ALIGN_PTR, 0);
3201 	uma_zone_set_max(V_dyn_parent_zone, V_dyn_parent_max);
3202 
3203 	SLIST_INIT(&V_dyn_expired_ipv4);
3204 	V_dyn_ipv4 = NULL;
3205 	V_dyn_ipv4_parent = NULL;
3206 	V_dyn_ipv4_zone = uma_zcreate("IPFW IPv4 dynamic states",
3207 	    sizeof(struct dyn_ipv4_state), NULL, NULL, NULL, NULL,
3208 	    UMA_ALIGN_PTR, 0);
3209 
3210 #ifdef INET6
3211 	SLIST_INIT(&V_dyn_expired_ipv6);
3212 	V_dyn_ipv6 = NULL;
3213 	V_dyn_ipv6_parent = NULL;
3214 	V_dyn_ipv6_zone = uma_zcreate("IPFW IPv6 dynamic states",
3215 	    sizeof(struct dyn_ipv6_state), NULL, NULL, NULL, NULL,
3216 	    UMA_ALIGN_PTR, 0);
3217 #endif
3218 
3219 	/* Initialize buckets. */
3220 	V_curr_dyn_buckets = 0;
3221 	V_dyn_bucket_lock = NULL;
3222 	dyn_grow_hashtable(chain, 256, M_WAITOK);
3223 
3224 	if (IS_DEFAULT_VNET(curvnet))
3225 		dyn_hp_cache = malloc(mp_ncpus * sizeof(void *), M_IPFW,
3226 		    M_WAITOK | M_ZERO);
3227 
3228 	DYN_EXPIRED_LOCK_INIT();
3229 	callout_init(&V_dyn_timeout, 1);
3230 	callout_reset(&V_dyn_timeout, hz, dyn_tick, curvnet);
3231 	IPFW_ADD_OBJ_REWRITER(IS_DEFAULT_VNET(curvnet), dyn_opcodes);
3232 }
3233 
3234 void
3235 ipfw_dyn_uninit(int pass)
3236 {
3237 #ifdef INET6
3238 	struct dyn_ipv6_state *s6;
3239 #endif
3240 	struct dyn_ipv4_state *s4;
3241 	int bucket;
3242 
3243 	if (pass == 0) {
3244 		callout_drain(&V_dyn_timeout);
3245 		return;
3246 	}
3247 	IPFW_DEL_OBJ_REWRITER(IS_DEFAULT_VNET(curvnet), dyn_opcodes);
3248 	DYN_EXPIRED_LOCK_DESTROY();
3249 
3250 #define	DYN_FREE_STATES_FORCED(CK, s, af, name, en)	do {		\
3251 	while ((s = CK ## SLIST_FIRST(&V_dyn_ ## name)) != NULL) {	\
3252 		CK ## SLIST_REMOVE_HEAD(&V_dyn_ ## name, en);	\
3253 		if (s->type == O_LIMIT_PARENT)				\
3254 			uma_zfree(V_dyn_parent_zone, s->limit);		\
3255 		else							\
3256 			uma_zfree(V_dyn_data_zone, s->data);		\
3257 		uma_zfree(V_dyn_ ## af ## _zone, s);			\
3258 	}								\
3259 } while (0)
3260 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
3261 		DYN_BUCKET_LOCK_DESTROY(V_dyn_bucket_lock, bucket);
3262 
3263 		DYN_FREE_STATES_FORCED(CK_, s4, ipv4, ipv4[bucket], entry);
3264 		DYN_FREE_STATES_FORCED(CK_, s4, ipv4, ipv4_parent[bucket],
3265 		    entry);
3266 #ifdef INET6
3267 		DYN_FREE_STATES_FORCED(CK_, s6, ipv6, ipv6[bucket], entry);
3268 		DYN_FREE_STATES_FORCED(CK_, s6, ipv6, ipv6_parent[bucket],
3269 		    entry);
3270 #endif /* INET6 */
3271 	}
3272 	DYN_FREE_STATES_FORCED(, s4, ipv4, expired_ipv4, expired);
3273 #ifdef INET6
3274 	DYN_FREE_STATES_FORCED(, s6, ipv6, expired_ipv6, expired);
3275 #endif
3276 #undef DYN_FREE_STATES_FORCED
3277 
3278 	uma_zdestroy(V_dyn_ipv4_zone);
3279 	uma_zdestroy(V_dyn_data_zone);
3280 	uma_zdestroy(V_dyn_parent_zone);
3281 #ifdef INET6
3282 	uma_zdestroy(V_dyn_ipv6_zone);
3283 	free(V_dyn_ipv6, M_IPFW);
3284 	free(V_dyn_ipv6_parent, M_IPFW);
3285 	free(V_dyn_ipv6_add, M_IPFW);
3286 	free(V_dyn_ipv6_parent_add, M_IPFW);
3287 	free(V_dyn_ipv6_del, M_IPFW);
3288 	free(V_dyn_ipv6_parent_del, M_IPFW);
3289 #endif
3290 	free(V_dyn_bucket_lock, M_IPFW);
3291 	free(V_dyn_ipv4, M_IPFW);
3292 	free(V_dyn_ipv4_parent, M_IPFW);
3293 	free(V_dyn_ipv4_add, M_IPFW);
3294 	free(V_dyn_ipv4_parent_add, M_IPFW);
3295 	free(V_dyn_ipv4_del, M_IPFW);
3296 	free(V_dyn_ipv4_parent_del, M_IPFW);
3297 	if (IS_DEFAULT_VNET(curvnet))
3298 		free(dyn_hp_cache, M_IPFW);
3299 }
3300