xref: /freebsd/sys/netpfil/pf/pf_ioctl.c (revision dbaad75f2834f40bfe74ebe393d2101967052036)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2001 Daniel Hartmeier
5  * Copyright (c) 2002,2003 Henning Brauer
6  * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  *    - Redistributions of source code must retain the above copyright
14  *      notice, this list of conditions and the following disclaimer.
15  *    - Redistributions in binary form must reproduce the above
16  *      copyright notice, this list of conditions and the following
17  *      disclaimer in the documentation and/or other materials provided
18  *      with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
28  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31  * POSSIBILITY OF SUCH DAMAGE.
32  *
33  * Effort sponsored in part by the Defense Advanced Research Projects
34  * Agency (DARPA) and Air Force Research Laboratory, Air Force
35  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
36  *
37  *	$OpenBSD: pf_ioctl.c,v 1.213 2009/02/15 21:46:12 mbalmer Exp $
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include "opt_inet.h"
44 #include "opt_inet6.h"
45 #include "opt_bpf.h"
46 #include "opt_pf.h"
47 
48 #include <sys/param.h>
49 #include <sys/_bitset.h>
50 #include <sys/bitset.h>
51 #include <sys/bus.h>
52 #include <sys/conf.h>
53 #include <sys/endian.h>
54 #include <sys/fcntl.h>
55 #include <sys/filio.h>
56 #include <sys/hash.h>
57 #include <sys/interrupt.h>
58 #include <sys/jail.h>
59 #include <sys/kernel.h>
60 #include <sys/kthread.h>
61 #include <sys/lock.h>
62 #include <sys/mbuf.h>
63 #include <sys/module.h>
64 #include <sys/nv.h>
65 #include <sys/proc.h>
66 #include <sys/sdt.h>
67 #include <sys/smp.h>
68 #include <sys/socket.h>
69 #include <sys/sysctl.h>
70 #include <sys/md5.h>
71 #include <sys/ucred.h>
72 
73 #include <net/if.h>
74 #include <net/if_var.h>
75 #include <net/vnet.h>
76 #include <net/route.h>
77 #include <net/pfil.h>
78 #include <net/pfvar.h>
79 #include <net/if_pfsync.h>
80 #include <net/if_pflog.h>
81 
82 #include <netinet/in.h>
83 #include <netinet/ip.h>
84 #include <netinet/ip_var.h>
85 #include <netinet6/ip6_var.h>
86 #include <netinet/ip_icmp.h>
87 #include <netpfil/pf/pf_nv.h>
88 
89 #ifdef INET6
90 #include <netinet/ip6.h>
91 #endif /* INET6 */
92 
93 #ifdef ALTQ
94 #include <net/altq/altq.h>
95 #endif
96 
97 SDT_PROBE_DEFINE3(pf, ioctl, ioctl, error, "int", "int", "int");
98 SDT_PROBE_DEFINE3(pf, ioctl, function, error, "char *", "int", "int");
99 SDT_PROBE_DEFINE2(pf, ioctl, addrule, error, "int", "int");
100 SDT_PROBE_DEFINE2(pf, ioctl, nvchk, error, "int", "int");
101 
102 static struct pf_kpool	*pf_get_kpool(const char *, u_int32_t, u_int8_t,
103 			    u_int32_t, u_int8_t, u_int8_t, u_int8_t);
104 
105 static void		 pf_mv_kpool(struct pf_kpalist *, struct pf_kpalist *);
106 static void		 pf_empty_kpool(struct pf_kpalist *);
107 static int		 pfioctl(struct cdev *, u_long, caddr_t, int,
108 			    struct thread *);
109 #ifdef ALTQ
110 static int		 pf_begin_altq(u_int32_t *);
111 static int		 pf_rollback_altq(u_int32_t);
112 static int		 pf_commit_altq(u_int32_t);
113 static int		 pf_enable_altq(struct pf_altq *);
114 static int		 pf_disable_altq(struct pf_altq *);
115 static u_int32_t	 pf_qname2qid(const char *);
116 static void		 pf_qid_unref(u_int32_t);
117 #endif /* ALTQ */
118 static int		 pf_begin_rules(u_int32_t *, int, const char *);
119 static int		 pf_rollback_rules(u_int32_t, int, char *);
120 static int		 pf_setup_pfsync_matching(struct pf_kruleset *);
121 static void		 pf_hash_rule(MD5_CTX *, struct pf_krule *);
122 static void		 pf_hash_rule_addr(MD5_CTX *, struct pf_rule_addr *);
123 static int		 pf_commit_rules(u_int32_t, int, char *);
124 static int		 pf_addr_setup(struct pf_kruleset *,
125 			    struct pf_addr_wrap *, sa_family_t);
126 static void		 pf_addr_copyout(struct pf_addr_wrap *);
127 static void		 pf_src_node_copy(const struct pf_ksrc_node *,
128 			    struct pf_src_node *);
129 #ifdef ALTQ
130 static int		 pf_export_kaltq(struct pf_altq *,
131 			    struct pfioc_altq_v1 *, size_t);
132 static int		 pf_import_kaltq(struct pfioc_altq_v1 *,
133 			    struct pf_altq *, size_t);
134 #endif /* ALTQ */
135 
136 VNET_DEFINE(struct pf_krule,	pf_default_rule);
137 
138 #ifdef ALTQ
139 VNET_DEFINE_STATIC(int,		pf_altq_running);
140 #define	V_pf_altq_running	VNET(pf_altq_running)
141 #endif
142 
143 #define	TAGID_MAX	 50000
144 struct pf_tagname {
145 	TAILQ_ENTRY(pf_tagname)	namehash_entries;
146 	TAILQ_ENTRY(pf_tagname)	taghash_entries;
147 	char			name[PF_TAG_NAME_SIZE];
148 	uint16_t		tag;
149 	int			ref;
150 };
151 
152 struct pf_tagset {
153 	TAILQ_HEAD(, pf_tagname)	*namehash;
154 	TAILQ_HEAD(, pf_tagname)	*taghash;
155 	unsigned int			 mask;
156 	uint32_t			 seed;
157 	BITSET_DEFINE(, TAGID_MAX)	 avail;
158 };
159 
160 VNET_DEFINE(struct pf_tagset, pf_tags);
161 #define	V_pf_tags	VNET(pf_tags)
162 static unsigned int	pf_rule_tag_hashsize;
163 #define	PF_RULE_TAG_HASH_SIZE_DEFAULT	128
164 SYSCTL_UINT(_net_pf, OID_AUTO, rule_tag_hashsize, CTLFLAG_RDTUN,
165     &pf_rule_tag_hashsize, PF_RULE_TAG_HASH_SIZE_DEFAULT,
166     "Size of pf(4) rule tag hashtable");
167 
168 #ifdef ALTQ
169 VNET_DEFINE(struct pf_tagset, pf_qids);
170 #define	V_pf_qids	VNET(pf_qids)
171 static unsigned int	pf_queue_tag_hashsize;
172 #define	PF_QUEUE_TAG_HASH_SIZE_DEFAULT	128
173 SYSCTL_UINT(_net_pf, OID_AUTO, queue_tag_hashsize, CTLFLAG_RDTUN,
174     &pf_queue_tag_hashsize, PF_QUEUE_TAG_HASH_SIZE_DEFAULT,
175     "Size of pf(4) queue tag hashtable");
176 #endif
177 VNET_DEFINE(uma_zone_t,	 pf_tag_z);
178 #define	V_pf_tag_z		 VNET(pf_tag_z)
179 static MALLOC_DEFINE(M_PFALTQ, "pf_altq", "pf(4) altq configuration db");
180 static MALLOC_DEFINE(M_PFRULE, "pf_rule", "pf(4) rules");
181 
182 #if (PF_QNAME_SIZE != PF_TAG_NAME_SIZE)
183 #error PF_QNAME_SIZE must be equal to PF_TAG_NAME_SIZE
184 #endif
185 
186 static void		 pf_init_tagset(struct pf_tagset *, unsigned int *,
187 			    unsigned int);
188 static void		 pf_cleanup_tagset(struct pf_tagset *);
189 static uint16_t		 tagname2hashindex(const struct pf_tagset *, const char *);
190 static uint16_t		 tag2hashindex(const struct pf_tagset *, uint16_t);
191 static u_int16_t	 tagname2tag(struct pf_tagset *, const char *);
192 static u_int16_t	 pf_tagname2tag(const char *);
193 static void		 tag_unref(struct pf_tagset *, u_int16_t);
194 
195 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
196 
197 struct cdev *pf_dev;
198 
199 /*
200  * XXX - These are new and need to be checked when moveing to a new version
201  */
202 static void		 pf_clear_all_states(void);
203 static unsigned int	 pf_clear_states(const struct pf_kstate_kill *);
204 static void		 pf_killstates(struct pf_kstate_kill *,
205 			    unsigned int *);
206 static int		 pf_killstates_row(struct pf_kstate_kill *,
207 			    struct pf_idhash *);
208 static int		 pf_killstates_nv(struct pfioc_nv *);
209 static int		 pf_clearstates_nv(struct pfioc_nv *);
210 static int		 pf_getstate(struct pfioc_nv *);
211 static int		 pf_getstates(struct pfioc_nv *);
212 static int		 pf_clear_tables(void);
213 static void		 pf_clear_srcnodes(struct pf_ksrc_node *);
214 static void		 pf_kill_srcnodes(struct pfioc_src_node_kill *);
215 static int		 pf_keepcounters(struct pfioc_nv *);
216 static void		 pf_tbladdr_copyout(struct pf_addr_wrap *);
217 
218 /*
219  * Wrapper functions for pfil(9) hooks
220  */
221 #ifdef INET
222 static pfil_return_t pf_check_in(struct mbuf **m, struct ifnet *ifp,
223     int flags, void *ruleset __unused, struct inpcb *inp);
224 static pfil_return_t pf_check_out(struct mbuf **m, struct ifnet *ifp,
225     int flags, void *ruleset __unused, struct inpcb *inp);
226 #endif
227 #ifdef INET6
228 static pfil_return_t pf_check6_in(struct mbuf **m, struct ifnet *ifp,
229     int flags, void *ruleset __unused, struct inpcb *inp);
230 static pfil_return_t pf_check6_out(struct mbuf **m, struct ifnet *ifp,
231     int flags, void *ruleset __unused, struct inpcb *inp);
232 #endif
233 
234 static void		hook_pf(void);
235 static void		dehook_pf(void);
236 static int		shutdown_pf(void);
237 static int		pf_load(void);
238 static void		pf_unload(void);
239 
240 static struct cdevsw pf_cdevsw = {
241 	.d_ioctl =	pfioctl,
242 	.d_name =	PF_NAME,
243 	.d_version =	D_VERSION,
244 };
245 
246 volatile VNET_DEFINE_STATIC(int, pf_pfil_hooked);
247 #define V_pf_pfil_hooked	VNET(pf_pfil_hooked)
248 
249 /*
250  * We need a flag that is neither hooked nor running to know when
251  * the VNET is "valid".  We primarily need this to control (global)
252  * external event, e.g., eventhandlers.
253  */
254 VNET_DEFINE(int, pf_vnet_active);
255 #define V_pf_vnet_active	VNET(pf_vnet_active)
256 
257 int pf_end_threads;
258 struct proc *pf_purge_proc;
259 
260 struct rmlock			pf_rules_lock;
261 struct sx			pf_ioctl_lock;
262 struct sx			pf_end_lock;
263 
264 /* pfsync */
265 VNET_DEFINE(pfsync_state_import_t *, pfsync_state_import_ptr);
266 VNET_DEFINE(pfsync_insert_state_t *, pfsync_insert_state_ptr);
267 VNET_DEFINE(pfsync_update_state_t *, pfsync_update_state_ptr);
268 VNET_DEFINE(pfsync_delete_state_t *, pfsync_delete_state_ptr);
269 VNET_DEFINE(pfsync_clear_states_t *, pfsync_clear_states_ptr);
270 VNET_DEFINE(pfsync_defer_t *, pfsync_defer_ptr);
271 pfsync_detach_ifnet_t *pfsync_detach_ifnet_ptr;
272 
273 /* pflog */
274 pflog_packet_t			*pflog_packet_ptr = NULL;
275 
276 extern u_long	pf_ioctl_maxcount;
277 
278 static void
279 pfattach_vnet(void)
280 {
281 	u_int32_t *my_timeout = V_pf_default_rule.timeout;
282 
283 	pf_initialize();
284 	pfr_initialize();
285 	pfi_initialize_vnet();
286 	pf_normalize_init();
287 
288 	V_pf_limits[PF_LIMIT_STATES].limit = PFSTATE_HIWAT;
289 	V_pf_limits[PF_LIMIT_SRC_NODES].limit = PFSNODE_HIWAT;
290 
291 	RB_INIT(&V_pf_anchors);
292 	pf_init_kruleset(&pf_main_ruleset);
293 
294 	/* default rule should never be garbage collected */
295 	V_pf_default_rule.entries.tqe_prev = &V_pf_default_rule.entries.tqe_next;
296 #ifdef PF_DEFAULT_TO_DROP
297 	V_pf_default_rule.action = PF_DROP;
298 #else
299 	V_pf_default_rule.action = PF_PASS;
300 #endif
301 	V_pf_default_rule.nr = -1;
302 	V_pf_default_rule.rtableid = -1;
303 
304 	V_pf_default_rule.evaluations = counter_u64_alloc(M_WAITOK);
305 	for (int i = 0; i < 2; i++) {
306 		V_pf_default_rule.packets[i] = counter_u64_alloc(M_WAITOK);
307 		V_pf_default_rule.bytes[i] = counter_u64_alloc(M_WAITOK);
308 	}
309 	V_pf_default_rule.states_cur = counter_u64_alloc(M_WAITOK);
310 	V_pf_default_rule.states_tot = counter_u64_alloc(M_WAITOK);
311 	V_pf_default_rule.src_nodes = counter_u64_alloc(M_WAITOK);
312 
313 	/* initialize default timeouts */
314 	my_timeout[PFTM_TCP_FIRST_PACKET] = PFTM_TCP_FIRST_PACKET_VAL;
315 	my_timeout[PFTM_TCP_OPENING] = PFTM_TCP_OPENING_VAL;
316 	my_timeout[PFTM_TCP_ESTABLISHED] = PFTM_TCP_ESTABLISHED_VAL;
317 	my_timeout[PFTM_TCP_CLOSING] = PFTM_TCP_CLOSING_VAL;
318 	my_timeout[PFTM_TCP_FIN_WAIT] = PFTM_TCP_FIN_WAIT_VAL;
319 	my_timeout[PFTM_TCP_CLOSED] = PFTM_TCP_CLOSED_VAL;
320 	my_timeout[PFTM_UDP_FIRST_PACKET] = PFTM_UDP_FIRST_PACKET_VAL;
321 	my_timeout[PFTM_UDP_SINGLE] = PFTM_UDP_SINGLE_VAL;
322 	my_timeout[PFTM_UDP_MULTIPLE] = PFTM_UDP_MULTIPLE_VAL;
323 	my_timeout[PFTM_ICMP_FIRST_PACKET] = PFTM_ICMP_FIRST_PACKET_VAL;
324 	my_timeout[PFTM_ICMP_ERROR_REPLY] = PFTM_ICMP_ERROR_REPLY_VAL;
325 	my_timeout[PFTM_OTHER_FIRST_PACKET] = PFTM_OTHER_FIRST_PACKET_VAL;
326 	my_timeout[PFTM_OTHER_SINGLE] = PFTM_OTHER_SINGLE_VAL;
327 	my_timeout[PFTM_OTHER_MULTIPLE] = PFTM_OTHER_MULTIPLE_VAL;
328 	my_timeout[PFTM_FRAG] = PFTM_FRAG_VAL;
329 	my_timeout[PFTM_INTERVAL] = PFTM_INTERVAL_VAL;
330 	my_timeout[PFTM_SRC_NODE] = PFTM_SRC_NODE_VAL;
331 	my_timeout[PFTM_TS_DIFF] = PFTM_TS_DIFF_VAL;
332 	my_timeout[PFTM_ADAPTIVE_START] = PFSTATE_ADAPT_START;
333 	my_timeout[PFTM_ADAPTIVE_END] = PFSTATE_ADAPT_END;
334 
335 	bzero(&V_pf_status, sizeof(V_pf_status));
336 	V_pf_status.debug = PF_DEBUG_URGENT;
337 
338 	V_pf_pfil_hooked = 0;
339 
340 	/* XXX do our best to avoid a conflict */
341 	V_pf_status.hostid = arc4random();
342 
343 	for (int i = 0; i < PFRES_MAX; i++)
344 		V_pf_status.counters[i] = counter_u64_alloc(M_WAITOK);
345 	for (int i = 0; i < LCNT_MAX; i++)
346 		V_pf_status.lcounters[i] = counter_u64_alloc(M_WAITOK);
347 	for (int i = 0; i < FCNT_MAX; i++)
348 		V_pf_status.fcounters[i] = counter_u64_alloc(M_WAITOK);
349 	for (int i = 0; i < SCNT_MAX; i++)
350 		V_pf_status.scounters[i] = counter_u64_alloc(M_WAITOK);
351 
352 	if (swi_add(&V_pf_swi_ie, "pf send", pf_intr, curvnet, SWI_NET,
353 	    INTR_MPSAFE, &V_pf_swi_cookie) != 0)
354 		/* XXXGL: leaked all above. */
355 		return;
356 }
357 
358 static struct pf_kpool *
359 pf_get_kpool(const char *anchor, u_int32_t ticket, u_int8_t rule_action,
360     u_int32_t rule_number, u_int8_t r_last, u_int8_t active,
361     u_int8_t check_ticket)
362 {
363 	struct pf_kruleset	*ruleset;
364 	struct pf_krule		*rule;
365 	int			 rs_num;
366 
367 	ruleset = pf_find_kruleset(anchor);
368 	if (ruleset == NULL)
369 		return (NULL);
370 	rs_num = pf_get_ruleset_number(rule_action);
371 	if (rs_num >= PF_RULESET_MAX)
372 		return (NULL);
373 	if (active) {
374 		if (check_ticket && ticket !=
375 		    ruleset->rules[rs_num].active.ticket)
376 			return (NULL);
377 		if (r_last)
378 			rule = TAILQ_LAST(ruleset->rules[rs_num].active.ptr,
379 			    pf_krulequeue);
380 		else
381 			rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
382 	} else {
383 		if (check_ticket && ticket !=
384 		    ruleset->rules[rs_num].inactive.ticket)
385 			return (NULL);
386 		if (r_last)
387 			rule = TAILQ_LAST(ruleset->rules[rs_num].inactive.ptr,
388 			    pf_krulequeue);
389 		else
390 			rule = TAILQ_FIRST(ruleset->rules[rs_num].inactive.ptr);
391 	}
392 	if (!r_last) {
393 		while ((rule != NULL) && (rule->nr != rule_number))
394 			rule = TAILQ_NEXT(rule, entries);
395 	}
396 	if (rule == NULL)
397 		return (NULL);
398 
399 	return (&rule->rpool);
400 }
401 
402 static void
403 pf_mv_kpool(struct pf_kpalist *poola, struct pf_kpalist *poolb)
404 {
405 	struct pf_kpooladdr	*mv_pool_pa;
406 
407 	while ((mv_pool_pa = TAILQ_FIRST(poola)) != NULL) {
408 		TAILQ_REMOVE(poola, mv_pool_pa, entries);
409 		TAILQ_INSERT_TAIL(poolb, mv_pool_pa, entries);
410 	}
411 }
412 
413 static void
414 pf_empty_kpool(struct pf_kpalist *poola)
415 {
416 	struct pf_kpooladdr *pa;
417 
418 	while ((pa = TAILQ_FIRST(poola)) != NULL) {
419 		switch (pa->addr.type) {
420 		case PF_ADDR_DYNIFTL:
421 			pfi_dynaddr_remove(pa->addr.p.dyn);
422 			break;
423 		case PF_ADDR_TABLE:
424 			/* XXX: this could be unfinished pooladdr on pabuf */
425 			if (pa->addr.p.tbl != NULL)
426 				pfr_detach_table(pa->addr.p.tbl);
427 			break;
428 		}
429 		if (pa->kif)
430 			pfi_kkif_unref(pa->kif);
431 		TAILQ_REMOVE(poola, pa, entries);
432 		free(pa, M_PFRULE);
433 	}
434 }
435 
436 static void
437 pf_unlink_rule(struct pf_krulequeue *rulequeue, struct pf_krule *rule)
438 {
439 
440 	PF_RULES_WASSERT();
441 
442 	TAILQ_REMOVE(rulequeue, rule, entries);
443 
444 	PF_UNLNKDRULES_LOCK();
445 	rule->rule_ref |= PFRULE_REFS;
446 	TAILQ_INSERT_TAIL(&V_pf_unlinked_rules, rule, entries);
447 	PF_UNLNKDRULES_UNLOCK();
448 }
449 
450 void
451 pf_free_rule(struct pf_krule *rule)
452 {
453 
454 	PF_RULES_WASSERT();
455 
456 	if (rule->tag)
457 		tag_unref(&V_pf_tags, rule->tag);
458 	if (rule->match_tag)
459 		tag_unref(&V_pf_tags, rule->match_tag);
460 #ifdef ALTQ
461 	if (rule->pqid != rule->qid)
462 		pf_qid_unref(rule->pqid);
463 	pf_qid_unref(rule->qid);
464 #endif
465 	switch (rule->src.addr.type) {
466 	case PF_ADDR_DYNIFTL:
467 		pfi_dynaddr_remove(rule->src.addr.p.dyn);
468 		break;
469 	case PF_ADDR_TABLE:
470 		pfr_detach_table(rule->src.addr.p.tbl);
471 		break;
472 	}
473 	switch (rule->dst.addr.type) {
474 	case PF_ADDR_DYNIFTL:
475 		pfi_dynaddr_remove(rule->dst.addr.p.dyn);
476 		break;
477 	case PF_ADDR_TABLE:
478 		pfr_detach_table(rule->dst.addr.p.tbl);
479 		break;
480 	}
481 	if (rule->overload_tbl)
482 		pfr_detach_table(rule->overload_tbl);
483 	if (rule->kif)
484 		pfi_kkif_unref(rule->kif);
485 	pf_kanchor_remove(rule);
486 	pf_empty_kpool(&rule->rpool.list);
487 
488 	pf_krule_free(rule);
489 }
490 
491 static void
492 pf_init_tagset(struct pf_tagset *ts, unsigned int *tunable_size,
493     unsigned int default_size)
494 {
495 	unsigned int i;
496 	unsigned int hashsize;
497 
498 	if (*tunable_size == 0 || !powerof2(*tunable_size))
499 		*tunable_size = default_size;
500 
501 	hashsize = *tunable_size;
502 	ts->namehash = mallocarray(hashsize, sizeof(*ts->namehash), M_PFHASH,
503 	    M_WAITOK);
504 	ts->taghash = mallocarray(hashsize, sizeof(*ts->taghash), M_PFHASH,
505 	    M_WAITOK);
506 	ts->mask = hashsize - 1;
507 	ts->seed = arc4random();
508 	for (i = 0; i < hashsize; i++) {
509 		TAILQ_INIT(&ts->namehash[i]);
510 		TAILQ_INIT(&ts->taghash[i]);
511 	}
512 	BIT_FILL(TAGID_MAX, &ts->avail);
513 }
514 
515 static void
516 pf_cleanup_tagset(struct pf_tagset *ts)
517 {
518 	unsigned int i;
519 	unsigned int hashsize;
520 	struct pf_tagname *t, *tmp;
521 
522 	/*
523 	 * Only need to clean up one of the hashes as each tag is hashed
524 	 * into each table.
525 	 */
526 	hashsize = ts->mask + 1;
527 	for (i = 0; i < hashsize; i++)
528 		TAILQ_FOREACH_SAFE(t, &ts->namehash[i], namehash_entries, tmp)
529 			uma_zfree(V_pf_tag_z, t);
530 
531 	free(ts->namehash, M_PFHASH);
532 	free(ts->taghash, M_PFHASH);
533 }
534 
535 static uint16_t
536 tagname2hashindex(const struct pf_tagset *ts, const char *tagname)
537 {
538 	size_t len;
539 
540 	len = strnlen(tagname, PF_TAG_NAME_SIZE - 1);
541 	return (murmur3_32_hash(tagname, len, ts->seed) & ts->mask);
542 }
543 
544 static uint16_t
545 tag2hashindex(const struct pf_tagset *ts, uint16_t tag)
546 {
547 
548 	return (tag & ts->mask);
549 }
550 
551 static u_int16_t
552 tagname2tag(struct pf_tagset *ts, const char *tagname)
553 {
554 	struct pf_tagname	*tag;
555 	u_int32_t		 index;
556 	u_int16_t		 new_tagid;
557 
558 	PF_RULES_WASSERT();
559 
560 	index = tagname2hashindex(ts, tagname);
561 	TAILQ_FOREACH(tag, &ts->namehash[index], namehash_entries)
562 		if (strcmp(tagname, tag->name) == 0) {
563 			tag->ref++;
564 			return (tag->tag);
565 		}
566 
567 	/*
568 	 * new entry
569 	 *
570 	 * to avoid fragmentation, we do a linear search from the beginning
571 	 * and take the first free slot we find.
572 	 */
573 	new_tagid = BIT_FFS(TAGID_MAX, &ts->avail);
574 	/*
575 	 * Tags are 1-based, with valid tags in the range [1..TAGID_MAX].
576 	 * BIT_FFS() returns a 1-based bit number, with 0 indicating no bits
577 	 * set.  It may also return a bit number greater than TAGID_MAX due
578 	 * to rounding of the number of bits in the vector up to a multiple
579 	 * of the vector word size at declaration/allocation time.
580 	 */
581 	if ((new_tagid == 0) || (new_tagid > TAGID_MAX))
582 		return (0);
583 
584 	/* Mark the tag as in use.  Bits are 0-based for BIT_CLR() */
585 	BIT_CLR(TAGID_MAX, new_tagid - 1, &ts->avail);
586 
587 	/* allocate and fill new struct pf_tagname */
588 	tag = uma_zalloc(V_pf_tag_z, M_NOWAIT);
589 	if (tag == NULL)
590 		return (0);
591 	strlcpy(tag->name, tagname, sizeof(tag->name));
592 	tag->tag = new_tagid;
593 	tag->ref = 1;
594 
595 	/* Insert into namehash */
596 	TAILQ_INSERT_TAIL(&ts->namehash[index], tag, namehash_entries);
597 
598 	/* Insert into taghash */
599 	index = tag2hashindex(ts, new_tagid);
600 	TAILQ_INSERT_TAIL(&ts->taghash[index], tag, taghash_entries);
601 
602 	return (tag->tag);
603 }
604 
605 static void
606 tag_unref(struct pf_tagset *ts, u_int16_t tag)
607 {
608 	struct pf_tagname	*t;
609 	uint16_t		 index;
610 
611 	PF_RULES_WASSERT();
612 
613 	index = tag2hashindex(ts, tag);
614 	TAILQ_FOREACH(t, &ts->taghash[index], taghash_entries)
615 		if (tag == t->tag) {
616 			if (--t->ref == 0) {
617 				TAILQ_REMOVE(&ts->taghash[index], t,
618 				    taghash_entries);
619 				index = tagname2hashindex(ts, t->name);
620 				TAILQ_REMOVE(&ts->namehash[index], t,
621 				    namehash_entries);
622 				/* Bits are 0-based for BIT_SET() */
623 				BIT_SET(TAGID_MAX, tag - 1, &ts->avail);
624 				uma_zfree(V_pf_tag_z, t);
625 			}
626 			break;
627 		}
628 }
629 
630 static u_int16_t
631 pf_tagname2tag(const char *tagname)
632 {
633 	return (tagname2tag(&V_pf_tags, tagname));
634 }
635 
636 #ifdef ALTQ
637 static u_int32_t
638 pf_qname2qid(const char *qname)
639 {
640 	return ((u_int32_t)tagname2tag(&V_pf_qids, qname));
641 }
642 
643 static void
644 pf_qid_unref(u_int32_t qid)
645 {
646 	tag_unref(&V_pf_qids, (u_int16_t)qid);
647 }
648 
649 static int
650 pf_begin_altq(u_int32_t *ticket)
651 {
652 	struct pf_altq	*altq, *tmp;
653 	int		 error = 0;
654 
655 	PF_RULES_WASSERT();
656 
657 	/* Purge the old altq lists */
658 	TAILQ_FOREACH_SAFE(altq, V_pf_altq_ifs_inactive, entries, tmp) {
659 		if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
660 			/* detach and destroy the discipline */
661 			error = altq_remove(altq);
662 		}
663 		free(altq, M_PFALTQ);
664 	}
665 	TAILQ_INIT(V_pf_altq_ifs_inactive);
666 	TAILQ_FOREACH_SAFE(altq, V_pf_altqs_inactive, entries, tmp) {
667 		pf_qid_unref(altq->qid);
668 		free(altq, M_PFALTQ);
669 	}
670 	TAILQ_INIT(V_pf_altqs_inactive);
671 	if (error)
672 		return (error);
673 	*ticket = ++V_ticket_altqs_inactive;
674 	V_altqs_inactive_open = 1;
675 	return (0);
676 }
677 
678 static int
679 pf_rollback_altq(u_int32_t ticket)
680 {
681 	struct pf_altq	*altq, *tmp;
682 	int		 error = 0;
683 
684 	PF_RULES_WASSERT();
685 
686 	if (!V_altqs_inactive_open || ticket != V_ticket_altqs_inactive)
687 		return (0);
688 	/* Purge the old altq lists */
689 	TAILQ_FOREACH_SAFE(altq, V_pf_altq_ifs_inactive, entries, tmp) {
690 		if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
691 			/* detach and destroy the discipline */
692 			error = altq_remove(altq);
693 		}
694 		free(altq, M_PFALTQ);
695 	}
696 	TAILQ_INIT(V_pf_altq_ifs_inactive);
697 	TAILQ_FOREACH_SAFE(altq, V_pf_altqs_inactive, entries, tmp) {
698 		pf_qid_unref(altq->qid);
699 		free(altq, M_PFALTQ);
700 	}
701 	TAILQ_INIT(V_pf_altqs_inactive);
702 	V_altqs_inactive_open = 0;
703 	return (error);
704 }
705 
706 static int
707 pf_commit_altq(u_int32_t ticket)
708 {
709 	struct pf_altqqueue	*old_altqs, *old_altq_ifs;
710 	struct pf_altq		*altq, *tmp;
711 	int			 err, error = 0;
712 
713 	PF_RULES_WASSERT();
714 
715 	if (!V_altqs_inactive_open || ticket != V_ticket_altqs_inactive)
716 		return (EBUSY);
717 
718 	/* swap altqs, keep the old. */
719 	old_altqs = V_pf_altqs_active;
720 	old_altq_ifs = V_pf_altq_ifs_active;
721 	V_pf_altqs_active = V_pf_altqs_inactive;
722 	V_pf_altq_ifs_active = V_pf_altq_ifs_inactive;
723 	V_pf_altqs_inactive = old_altqs;
724 	V_pf_altq_ifs_inactive = old_altq_ifs;
725 	V_ticket_altqs_active = V_ticket_altqs_inactive;
726 
727 	/* Attach new disciplines */
728 	TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries) {
729 		if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
730 			/* attach the discipline */
731 			error = altq_pfattach(altq);
732 			if (error == 0 && V_pf_altq_running)
733 				error = pf_enable_altq(altq);
734 			if (error != 0)
735 				return (error);
736 		}
737 	}
738 
739 	/* Purge the old altq lists */
740 	TAILQ_FOREACH_SAFE(altq, V_pf_altq_ifs_inactive, entries, tmp) {
741 		if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
742 			/* detach and destroy the discipline */
743 			if (V_pf_altq_running)
744 				error = pf_disable_altq(altq);
745 			err = altq_pfdetach(altq);
746 			if (err != 0 && error == 0)
747 				error = err;
748 			err = altq_remove(altq);
749 			if (err != 0 && error == 0)
750 				error = err;
751 		}
752 		free(altq, M_PFALTQ);
753 	}
754 	TAILQ_INIT(V_pf_altq_ifs_inactive);
755 	TAILQ_FOREACH_SAFE(altq, V_pf_altqs_inactive, entries, tmp) {
756 		pf_qid_unref(altq->qid);
757 		free(altq, M_PFALTQ);
758 	}
759 	TAILQ_INIT(V_pf_altqs_inactive);
760 
761 	V_altqs_inactive_open = 0;
762 	return (error);
763 }
764 
765 static int
766 pf_enable_altq(struct pf_altq *altq)
767 {
768 	struct ifnet		*ifp;
769 	struct tb_profile	 tb;
770 	int			 error = 0;
771 
772 	if ((ifp = ifunit(altq->ifname)) == NULL)
773 		return (EINVAL);
774 
775 	if (ifp->if_snd.altq_type != ALTQT_NONE)
776 		error = altq_enable(&ifp->if_snd);
777 
778 	/* set tokenbucket regulator */
779 	if (error == 0 && ifp != NULL && ALTQ_IS_ENABLED(&ifp->if_snd)) {
780 		tb.rate = altq->ifbandwidth;
781 		tb.depth = altq->tbrsize;
782 		error = tbr_set(&ifp->if_snd, &tb);
783 	}
784 
785 	return (error);
786 }
787 
788 static int
789 pf_disable_altq(struct pf_altq *altq)
790 {
791 	struct ifnet		*ifp;
792 	struct tb_profile	 tb;
793 	int			 error;
794 
795 	if ((ifp = ifunit(altq->ifname)) == NULL)
796 		return (EINVAL);
797 
798 	/*
799 	 * when the discipline is no longer referenced, it was overridden
800 	 * by a new one.  if so, just return.
801 	 */
802 	if (altq->altq_disc != ifp->if_snd.altq_disc)
803 		return (0);
804 
805 	error = altq_disable(&ifp->if_snd);
806 
807 	if (error == 0) {
808 		/* clear tokenbucket regulator */
809 		tb.rate = 0;
810 		error = tbr_set(&ifp->if_snd, &tb);
811 	}
812 
813 	return (error);
814 }
815 
816 static int
817 pf_altq_ifnet_event_add(struct ifnet *ifp, int remove, u_int32_t ticket,
818     struct pf_altq *altq)
819 {
820 	struct ifnet	*ifp1;
821 	int		 error = 0;
822 
823 	/* Deactivate the interface in question */
824 	altq->local_flags &= ~PFALTQ_FLAG_IF_REMOVED;
825 	if ((ifp1 = ifunit(altq->ifname)) == NULL ||
826 	    (remove && ifp1 == ifp)) {
827 		altq->local_flags |= PFALTQ_FLAG_IF_REMOVED;
828 	} else {
829 		error = altq_add(ifp1, altq);
830 
831 		if (ticket != V_ticket_altqs_inactive)
832 			error = EBUSY;
833 
834 		if (error)
835 			free(altq, M_PFALTQ);
836 	}
837 
838 	return (error);
839 }
840 
841 void
842 pf_altq_ifnet_event(struct ifnet *ifp, int remove)
843 {
844 	struct pf_altq	*a1, *a2, *a3;
845 	u_int32_t	 ticket;
846 	int		 error = 0;
847 
848 	/*
849 	 * No need to re-evaluate the configuration for events on interfaces
850 	 * that do not support ALTQ, as it's not possible for such
851 	 * interfaces to be part of the configuration.
852 	 */
853 	if (!ALTQ_IS_READY(&ifp->if_snd))
854 		return;
855 
856 	/* Interrupt userland queue modifications */
857 	if (V_altqs_inactive_open)
858 		pf_rollback_altq(V_ticket_altqs_inactive);
859 
860 	/* Start new altq ruleset */
861 	if (pf_begin_altq(&ticket))
862 		return;
863 
864 	/* Copy the current active set */
865 	TAILQ_FOREACH(a1, V_pf_altq_ifs_active, entries) {
866 		a2 = malloc(sizeof(*a2), M_PFALTQ, M_NOWAIT);
867 		if (a2 == NULL) {
868 			error = ENOMEM;
869 			break;
870 		}
871 		bcopy(a1, a2, sizeof(struct pf_altq));
872 
873 		error = pf_altq_ifnet_event_add(ifp, remove, ticket, a2);
874 		if (error)
875 			break;
876 
877 		TAILQ_INSERT_TAIL(V_pf_altq_ifs_inactive, a2, entries);
878 	}
879 	if (error)
880 		goto out;
881 	TAILQ_FOREACH(a1, V_pf_altqs_active, entries) {
882 		a2 = malloc(sizeof(*a2), M_PFALTQ, M_NOWAIT);
883 		if (a2 == NULL) {
884 			error = ENOMEM;
885 			break;
886 		}
887 		bcopy(a1, a2, sizeof(struct pf_altq));
888 
889 		if ((a2->qid = pf_qname2qid(a2->qname)) == 0) {
890 			error = EBUSY;
891 			free(a2, M_PFALTQ);
892 			break;
893 		}
894 		a2->altq_disc = NULL;
895 		TAILQ_FOREACH(a3, V_pf_altq_ifs_inactive, entries) {
896 			if (strncmp(a3->ifname, a2->ifname,
897 				IFNAMSIZ) == 0) {
898 				a2->altq_disc = a3->altq_disc;
899 				break;
900 			}
901 		}
902 		error = pf_altq_ifnet_event_add(ifp, remove, ticket, a2);
903 		if (error)
904 			break;
905 
906 		TAILQ_INSERT_TAIL(V_pf_altqs_inactive, a2, entries);
907 	}
908 
909 out:
910 	if (error != 0)
911 		pf_rollback_altq(ticket);
912 	else
913 		pf_commit_altq(ticket);
914 }
915 #endif /* ALTQ */
916 
917 static int
918 pf_begin_rules(u_int32_t *ticket, int rs_num, const char *anchor)
919 {
920 	struct pf_kruleset	*rs;
921 	struct pf_krule		*rule;
922 
923 	PF_RULES_WASSERT();
924 
925 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
926 		return (EINVAL);
927 	rs = pf_find_or_create_kruleset(anchor);
928 	if (rs == NULL)
929 		return (EINVAL);
930 	while ((rule = TAILQ_FIRST(rs->rules[rs_num].inactive.ptr)) != NULL) {
931 		pf_unlink_rule(rs->rules[rs_num].inactive.ptr, rule);
932 		rs->rules[rs_num].inactive.rcount--;
933 	}
934 	*ticket = ++rs->rules[rs_num].inactive.ticket;
935 	rs->rules[rs_num].inactive.open = 1;
936 	return (0);
937 }
938 
939 static int
940 pf_rollback_rules(u_int32_t ticket, int rs_num, char *anchor)
941 {
942 	struct pf_kruleset	*rs;
943 	struct pf_krule		*rule;
944 
945 	PF_RULES_WASSERT();
946 
947 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
948 		return (EINVAL);
949 	rs = pf_find_kruleset(anchor);
950 	if (rs == NULL || !rs->rules[rs_num].inactive.open ||
951 	    rs->rules[rs_num].inactive.ticket != ticket)
952 		return (0);
953 	while ((rule = TAILQ_FIRST(rs->rules[rs_num].inactive.ptr)) != NULL) {
954 		pf_unlink_rule(rs->rules[rs_num].inactive.ptr, rule);
955 		rs->rules[rs_num].inactive.rcount--;
956 	}
957 	rs->rules[rs_num].inactive.open = 0;
958 	return (0);
959 }
960 
961 #define PF_MD5_UPD(st, elm)						\
962 		MD5Update(ctx, (u_int8_t *) &(st)->elm, sizeof((st)->elm))
963 
964 #define PF_MD5_UPD_STR(st, elm)						\
965 		MD5Update(ctx, (u_int8_t *) (st)->elm, strlen((st)->elm))
966 
967 #define PF_MD5_UPD_HTONL(st, elm, stor) do {				\
968 		(stor) = htonl((st)->elm);				\
969 		MD5Update(ctx, (u_int8_t *) &(stor), sizeof(u_int32_t));\
970 } while (0)
971 
972 #define PF_MD5_UPD_HTONS(st, elm, stor) do {				\
973 		(stor) = htons((st)->elm);				\
974 		MD5Update(ctx, (u_int8_t *) &(stor), sizeof(u_int16_t));\
975 } while (0)
976 
977 static void
978 pf_hash_rule_addr(MD5_CTX *ctx, struct pf_rule_addr *pfr)
979 {
980 	PF_MD5_UPD(pfr, addr.type);
981 	switch (pfr->addr.type) {
982 		case PF_ADDR_DYNIFTL:
983 			PF_MD5_UPD(pfr, addr.v.ifname);
984 			PF_MD5_UPD(pfr, addr.iflags);
985 			break;
986 		case PF_ADDR_TABLE:
987 			PF_MD5_UPD(pfr, addr.v.tblname);
988 			break;
989 		case PF_ADDR_ADDRMASK:
990 			/* XXX ignore af? */
991 			PF_MD5_UPD(pfr, addr.v.a.addr.addr32);
992 			PF_MD5_UPD(pfr, addr.v.a.mask.addr32);
993 			break;
994 	}
995 
996 	PF_MD5_UPD(pfr, port[0]);
997 	PF_MD5_UPD(pfr, port[1]);
998 	PF_MD5_UPD(pfr, neg);
999 	PF_MD5_UPD(pfr, port_op);
1000 }
1001 
1002 static void
1003 pf_hash_rule(MD5_CTX *ctx, struct pf_krule *rule)
1004 {
1005 	u_int16_t x;
1006 	u_int32_t y;
1007 
1008 	pf_hash_rule_addr(ctx, &rule->src);
1009 	pf_hash_rule_addr(ctx, &rule->dst);
1010 	for (int i = 0; i < PF_RULE_MAX_LABEL_COUNT; i++)
1011 		PF_MD5_UPD_STR(rule, label[i]);
1012 	PF_MD5_UPD_STR(rule, ifname);
1013 	PF_MD5_UPD_STR(rule, match_tagname);
1014 	PF_MD5_UPD_HTONS(rule, match_tag, x); /* dup? */
1015 	PF_MD5_UPD_HTONL(rule, os_fingerprint, y);
1016 	PF_MD5_UPD_HTONL(rule, prob, y);
1017 	PF_MD5_UPD_HTONL(rule, uid.uid[0], y);
1018 	PF_MD5_UPD_HTONL(rule, uid.uid[1], y);
1019 	PF_MD5_UPD(rule, uid.op);
1020 	PF_MD5_UPD_HTONL(rule, gid.gid[0], y);
1021 	PF_MD5_UPD_HTONL(rule, gid.gid[1], y);
1022 	PF_MD5_UPD(rule, gid.op);
1023 	PF_MD5_UPD_HTONL(rule, rule_flag, y);
1024 	PF_MD5_UPD(rule, action);
1025 	PF_MD5_UPD(rule, direction);
1026 	PF_MD5_UPD(rule, af);
1027 	PF_MD5_UPD(rule, quick);
1028 	PF_MD5_UPD(rule, ifnot);
1029 	PF_MD5_UPD(rule, match_tag_not);
1030 	PF_MD5_UPD(rule, natpass);
1031 	PF_MD5_UPD(rule, keep_state);
1032 	PF_MD5_UPD(rule, proto);
1033 	PF_MD5_UPD(rule, type);
1034 	PF_MD5_UPD(rule, code);
1035 	PF_MD5_UPD(rule, flags);
1036 	PF_MD5_UPD(rule, flagset);
1037 	PF_MD5_UPD(rule, allow_opts);
1038 	PF_MD5_UPD(rule, rt);
1039 	PF_MD5_UPD(rule, tos);
1040 }
1041 
1042 static bool
1043 pf_krule_compare(struct pf_krule *a, struct pf_krule *b)
1044 {
1045 	MD5_CTX		ctx[2];
1046 	u_int8_t	digest[2][PF_MD5_DIGEST_LENGTH];
1047 
1048 	MD5Init(&ctx[0]);
1049 	MD5Init(&ctx[1]);
1050 	pf_hash_rule(&ctx[0], a);
1051 	pf_hash_rule(&ctx[1], b);
1052 	MD5Final(digest[0], &ctx[0]);
1053 	MD5Final(digest[1], &ctx[1]);
1054 
1055 	return (memcmp(digest[0], digest[1], PF_MD5_DIGEST_LENGTH) == 0);
1056 }
1057 
1058 static int
1059 pf_commit_rules(u_int32_t ticket, int rs_num, char *anchor)
1060 {
1061 	struct pf_kruleset	*rs;
1062 	struct pf_krule		*rule, **old_array, *tail;
1063 	struct pf_krulequeue	*old_rules;
1064 	int			 error;
1065 	u_int32_t		 old_rcount;
1066 
1067 	PF_RULES_WASSERT();
1068 
1069 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
1070 		return (EINVAL);
1071 	rs = pf_find_kruleset(anchor);
1072 	if (rs == NULL || !rs->rules[rs_num].inactive.open ||
1073 	    ticket != rs->rules[rs_num].inactive.ticket)
1074 		return (EBUSY);
1075 
1076 	/* Calculate checksum for the main ruleset */
1077 	if (rs == &pf_main_ruleset) {
1078 		error = pf_setup_pfsync_matching(rs);
1079 		if (error != 0)
1080 			return (error);
1081 	}
1082 
1083 	/* Swap rules, keep the old. */
1084 	old_rules = rs->rules[rs_num].active.ptr;
1085 	old_rcount = rs->rules[rs_num].active.rcount;
1086 	old_array = rs->rules[rs_num].active.ptr_array;
1087 
1088 	rs->rules[rs_num].active.ptr =
1089 	    rs->rules[rs_num].inactive.ptr;
1090 	rs->rules[rs_num].active.ptr_array =
1091 	    rs->rules[rs_num].inactive.ptr_array;
1092 	rs->rules[rs_num].active.rcount =
1093 	    rs->rules[rs_num].inactive.rcount;
1094 
1095 	/* Attempt to preserve counter information. */
1096 	if (V_pf_status.keep_counters) {
1097 		TAILQ_FOREACH(rule, rs->rules[rs_num].active.ptr,
1098 		    entries) {
1099 			tail = TAILQ_FIRST(old_rules);
1100 			while ((tail != NULL) && ! pf_krule_compare(tail, rule))
1101 				tail = TAILQ_NEXT(tail, entries);
1102 			if (tail != NULL) {
1103 				counter_u64_add(rule->evaluations,
1104 				    counter_u64_fetch(tail->evaluations));
1105 				counter_u64_add(rule->packets[0],
1106 				    counter_u64_fetch(tail->packets[0]));
1107 				counter_u64_add(rule->packets[1],
1108 				    counter_u64_fetch(tail->packets[1]));
1109 				counter_u64_add(rule->bytes[0],
1110 				    counter_u64_fetch(tail->bytes[0]));
1111 				counter_u64_add(rule->bytes[1],
1112 				    counter_u64_fetch(tail->bytes[1]));
1113 			}
1114 		}
1115 	}
1116 
1117 	rs->rules[rs_num].inactive.ptr = old_rules;
1118 	rs->rules[rs_num].inactive.ptr_array = old_array;
1119 	rs->rules[rs_num].inactive.rcount = old_rcount;
1120 
1121 	rs->rules[rs_num].active.ticket =
1122 	    rs->rules[rs_num].inactive.ticket;
1123 	pf_calc_skip_steps(rs->rules[rs_num].active.ptr);
1124 
1125 	/* Purge the old rule list. */
1126 	while ((rule = TAILQ_FIRST(old_rules)) != NULL)
1127 		pf_unlink_rule(old_rules, rule);
1128 	if (rs->rules[rs_num].inactive.ptr_array)
1129 		free(rs->rules[rs_num].inactive.ptr_array, M_TEMP);
1130 	rs->rules[rs_num].inactive.ptr_array = NULL;
1131 	rs->rules[rs_num].inactive.rcount = 0;
1132 	rs->rules[rs_num].inactive.open = 0;
1133 	pf_remove_if_empty_kruleset(rs);
1134 
1135 	return (0);
1136 }
1137 
1138 static int
1139 pf_setup_pfsync_matching(struct pf_kruleset *rs)
1140 {
1141 	MD5_CTX			 ctx;
1142 	struct pf_krule		*rule;
1143 	int			 rs_cnt;
1144 	u_int8_t		 digest[PF_MD5_DIGEST_LENGTH];
1145 
1146 	MD5Init(&ctx);
1147 	for (rs_cnt = 0; rs_cnt < PF_RULESET_MAX; rs_cnt++) {
1148 		/* XXX PF_RULESET_SCRUB as well? */
1149 		if (rs_cnt == PF_RULESET_SCRUB)
1150 			continue;
1151 
1152 		if (rs->rules[rs_cnt].inactive.ptr_array)
1153 			free(rs->rules[rs_cnt].inactive.ptr_array, M_TEMP);
1154 		rs->rules[rs_cnt].inactive.ptr_array = NULL;
1155 
1156 		if (rs->rules[rs_cnt].inactive.rcount) {
1157 			rs->rules[rs_cnt].inactive.ptr_array =
1158 			    malloc(sizeof(caddr_t) *
1159 			    rs->rules[rs_cnt].inactive.rcount,
1160 			    M_TEMP, M_NOWAIT);
1161 
1162 			if (!rs->rules[rs_cnt].inactive.ptr_array)
1163 				return (ENOMEM);
1164 		}
1165 
1166 		TAILQ_FOREACH(rule, rs->rules[rs_cnt].inactive.ptr,
1167 		    entries) {
1168 			pf_hash_rule(&ctx, rule);
1169 			(rs->rules[rs_cnt].inactive.ptr_array)[rule->nr] = rule;
1170 		}
1171 	}
1172 
1173 	MD5Final(digest, &ctx);
1174 	memcpy(V_pf_status.pf_chksum, digest, sizeof(V_pf_status.pf_chksum));
1175 	return (0);
1176 }
1177 
1178 static int
1179 pf_addr_setup(struct pf_kruleset *ruleset, struct pf_addr_wrap *addr,
1180     sa_family_t af)
1181 {
1182 	int error = 0;
1183 
1184 	switch (addr->type) {
1185 	case PF_ADDR_TABLE:
1186 		addr->p.tbl = pfr_attach_table(ruleset, addr->v.tblname);
1187 		if (addr->p.tbl == NULL)
1188 			error = ENOMEM;
1189 		break;
1190 	case PF_ADDR_DYNIFTL:
1191 		error = pfi_dynaddr_setup(addr, af);
1192 		break;
1193 	}
1194 
1195 	return (error);
1196 }
1197 
1198 static void
1199 pf_addr_copyout(struct pf_addr_wrap *addr)
1200 {
1201 
1202 	switch (addr->type) {
1203 	case PF_ADDR_DYNIFTL:
1204 		pfi_dynaddr_copyout(addr);
1205 		break;
1206 	case PF_ADDR_TABLE:
1207 		pf_tbladdr_copyout(addr);
1208 		break;
1209 	}
1210 }
1211 
1212 static void
1213 pf_src_node_copy(const struct pf_ksrc_node *in, struct pf_src_node *out)
1214 {
1215 	int	secs = time_uptime, diff;
1216 
1217 	bzero(out, sizeof(struct pf_src_node));
1218 
1219 	bcopy(&in->addr, &out->addr, sizeof(struct pf_addr));
1220 	bcopy(&in->raddr, &out->raddr, sizeof(struct pf_addr));
1221 
1222 	if (in->rule.ptr != NULL)
1223 		out->rule.nr = in->rule.ptr->nr;
1224 
1225 	for (int i = 0; i < 2; i++) {
1226 		out->bytes[i] = counter_u64_fetch(in->bytes[i]);
1227 		out->packets[i] = counter_u64_fetch(in->packets[i]);
1228 	}
1229 
1230 	out->states = in->states;
1231 	out->conn = in->conn;
1232 	out->af = in->af;
1233 	out->ruletype = in->ruletype;
1234 
1235 	out->creation = secs - in->creation;
1236 	if (out->expire > secs)
1237 		out->expire -= secs;
1238 	else
1239 		out->expire = 0;
1240 
1241 	/* Adjust the connection rate estimate. */
1242 	diff = secs - in->conn_rate.last;
1243 	if (diff >= in->conn_rate.seconds)
1244 		out->conn_rate.count = 0;
1245 	else
1246 		out->conn_rate.count -=
1247 		    in->conn_rate.count * diff /
1248 		    in->conn_rate.seconds;
1249 }
1250 
1251 #ifdef ALTQ
1252 /*
1253  * Handle export of struct pf_kaltq to user binaries that may be using any
1254  * version of struct pf_altq.
1255  */
1256 static int
1257 pf_export_kaltq(struct pf_altq *q, struct pfioc_altq_v1 *pa, size_t ioc_size)
1258 {
1259 	u_int32_t version;
1260 
1261 	if (ioc_size == sizeof(struct pfioc_altq_v0))
1262 		version = 0;
1263 	else
1264 		version = pa->version;
1265 
1266 	if (version > PFIOC_ALTQ_VERSION)
1267 		return (EINVAL);
1268 
1269 #define ASSIGN(x) exported_q->x = q->x
1270 #define COPY(x) \
1271 	bcopy(&q->x, &exported_q->x, min(sizeof(q->x), sizeof(exported_q->x)))
1272 #define SATU16(x) (u_int32_t)uqmin((x), USHRT_MAX)
1273 #define SATU32(x) (u_int32_t)uqmin((x), UINT_MAX)
1274 
1275 	switch (version) {
1276 	case 0: {
1277 		struct pf_altq_v0 *exported_q =
1278 		    &((struct pfioc_altq_v0 *)pa)->altq;
1279 
1280 		COPY(ifname);
1281 
1282 		ASSIGN(scheduler);
1283 		ASSIGN(tbrsize);
1284 		exported_q->tbrsize = SATU16(q->tbrsize);
1285 		exported_q->ifbandwidth = SATU32(q->ifbandwidth);
1286 
1287 		COPY(qname);
1288 		COPY(parent);
1289 		ASSIGN(parent_qid);
1290 		exported_q->bandwidth = SATU32(q->bandwidth);
1291 		ASSIGN(priority);
1292 		ASSIGN(local_flags);
1293 
1294 		ASSIGN(qlimit);
1295 		ASSIGN(flags);
1296 
1297 		if (q->scheduler == ALTQT_HFSC) {
1298 #define ASSIGN_OPT(x) exported_q->pq_u.hfsc_opts.x = q->pq_u.hfsc_opts.x
1299 #define ASSIGN_OPT_SATU32(x) exported_q->pq_u.hfsc_opts.x = \
1300 			    SATU32(q->pq_u.hfsc_opts.x)
1301 
1302 			ASSIGN_OPT_SATU32(rtsc_m1);
1303 			ASSIGN_OPT(rtsc_d);
1304 			ASSIGN_OPT_SATU32(rtsc_m2);
1305 
1306 			ASSIGN_OPT_SATU32(lssc_m1);
1307 			ASSIGN_OPT(lssc_d);
1308 			ASSIGN_OPT_SATU32(lssc_m2);
1309 
1310 			ASSIGN_OPT_SATU32(ulsc_m1);
1311 			ASSIGN_OPT(ulsc_d);
1312 			ASSIGN_OPT_SATU32(ulsc_m2);
1313 
1314 			ASSIGN_OPT(flags);
1315 
1316 #undef ASSIGN_OPT
1317 #undef ASSIGN_OPT_SATU32
1318 		} else
1319 			COPY(pq_u);
1320 
1321 		ASSIGN(qid);
1322 		break;
1323 	}
1324 	case 1:	{
1325 		struct pf_altq_v1 *exported_q =
1326 		    &((struct pfioc_altq_v1 *)pa)->altq;
1327 
1328 		COPY(ifname);
1329 
1330 		ASSIGN(scheduler);
1331 		ASSIGN(tbrsize);
1332 		ASSIGN(ifbandwidth);
1333 
1334 		COPY(qname);
1335 		COPY(parent);
1336 		ASSIGN(parent_qid);
1337 		ASSIGN(bandwidth);
1338 		ASSIGN(priority);
1339 		ASSIGN(local_flags);
1340 
1341 		ASSIGN(qlimit);
1342 		ASSIGN(flags);
1343 		COPY(pq_u);
1344 
1345 		ASSIGN(qid);
1346 		break;
1347 	}
1348 	default:
1349 		panic("%s: unhandled struct pfioc_altq version", __func__);
1350 		break;
1351 	}
1352 
1353 #undef ASSIGN
1354 #undef COPY
1355 #undef SATU16
1356 #undef SATU32
1357 
1358 	return (0);
1359 }
1360 
1361 /*
1362  * Handle import to struct pf_kaltq of struct pf_altq from user binaries
1363  * that may be using any version of it.
1364  */
1365 static int
1366 pf_import_kaltq(struct pfioc_altq_v1 *pa, struct pf_altq *q, size_t ioc_size)
1367 {
1368 	u_int32_t version;
1369 
1370 	if (ioc_size == sizeof(struct pfioc_altq_v0))
1371 		version = 0;
1372 	else
1373 		version = pa->version;
1374 
1375 	if (version > PFIOC_ALTQ_VERSION)
1376 		return (EINVAL);
1377 
1378 #define ASSIGN(x) q->x = imported_q->x
1379 #define COPY(x) \
1380 	bcopy(&imported_q->x, &q->x, min(sizeof(imported_q->x), sizeof(q->x)))
1381 
1382 	switch (version) {
1383 	case 0: {
1384 		struct pf_altq_v0 *imported_q =
1385 		    &((struct pfioc_altq_v0 *)pa)->altq;
1386 
1387 		COPY(ifname);
1388 
1389 		ASSIGN(scheduler);
1390 		ASSIGN(tbrsize); /* 16-bit -> 32-bit */
1391 		ASSIGN(ifbandwidth); /* 32-bit -> 64-bit */
1392 
1393 		COPY(qname);
1394 		COPY(parent);
1395 		ASSIGN(parent_qid);
1396 		ASSIGN(bandwidth); /* 32-bit -> 64-bit */
1397 		ASSIGN(priority);
1398 		ASSIGN(local_flags);
1399 
1400 		ASSIGN(qlimit);
1401 		ASSIGN(flags);
1402 
1403 		if (imported_q->scheduler == ALTQT_HFSC) {
1404 #define ASSIGN_OPT(x) q->pq_u.hfsc_opts.x = imported_q->pq_u.hfsc_opts.x
1405 
1406 			/*
1407 			 * The m1 and m2 parameters are being copied from
1408 			 * 32-bit to 64-bit.
1409 			 */
1410 			ASSIGN_OPT(rtsc_m1);
1411 			ASSIGN_OPT(rtsc_d);
1412 			ASSIGN_OPT(rtsc_m2);
1413 
1414 			ASSIGN_OPT(lssc_m1);
1415 			ASSIGN_OPT(lssc_d);
1416 			ASSIGN_OPT(lssc_m2);
1417 
1418 			ASSIGN_OPT(ulsc_m1);
1419 			ASSIGN_OPT(ulsc_d);
1420 			ASSIGN_OPT(ulsc_m2);
1421 
1422 			ASSIGN_OPT(flags);
1423 
1424 #undef ASSIGN_OPT
1425 		} else
1426 			COPY(pq_u);
1427 
1428 		ASSIGN(qid);
1429 		break;
1430 	}
1431 	case 1: {
1432 		struct pf_altq_v1 *imported_q =
1433 		    &((struct pfioc_altq_v1 *)pa)->altq;
1434 
1435 		COPY(ifname);
1436 
1437 		ASSIGN(scheduler);
1438 		ASSIGN(tbrsize);
1439 		ASSIGN(ifbandwidth);
1440 
1441 		COPY(qname);
1442 		COPY(parent);
1443 		ASSIGN(parent_qid);
1444 		ASSIGN(bandwidth);
1445 		ASSIGN(priority);
1446 		ASSIGN(local_flags);
1447 
1448 		ASSIGN(qlimit);
1449 		ASSIGN(flags);
1450 		COPY(pq_u);
1451 
1452 		ASSIGN(qid);
1453 		break;
1454 	}
1455 	default:
1456 		panic("%s: unhandled struct pfioc_altq version", __func__);
1457 		break;
1458 	}
1459 
1460 #undef ASSIGN
1461 #undef COPY
1462 
1463 	return (0);
1464 }
1465 
1466 static struct pf_altq *
1467 pf_altq_get_nth_active(u_int32_t n)
1468 {
1469 	struct pf_altq		*altq;
1470 	u_int32_t		 nr;
1471 
1472 	nr = 0;
1473 	TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries) {
1474 		if (nr == n)
1475 			return (altq);
1476 		nr++;
1477 	}
1478 
1479 	TAILQ_FOREACH(altq, V_pf_altqs_active, entries) {
1480 		if (nr == n)
1481 			return (altq);
1482 		nr++;
1483 	}
1484 
1485 	return (NULL);
1486 }
1487 #endif /* ALTQ */
1488 
1489 void
1490 pf_krule_free(struct pf_krule *rule)
1491 {
1492 	if (rule == NULL)
1493 		return;
1494 
1495 	counter_u64_free(rule->evaluations);
1496 	for (int i = 0; i < 2; i++) {
1497 		counter_u64_free(rule->packets[i]);
1498 		counter_u64_free(rule->bytes[i]);
1499 	}
1500 	counter_u64_free(rule->states_cur);
1501 	counter_u64_free(rule->states_tot);
1502 	counter_u64_free(rule->src_nodes);
1503 	free(rule, M_PFRULE);
1504 }
1505 
1506 static void
1507 pf_kpooladdr_to_pooladdr(const struct pf_kpooladdr *kpool,
1508     struct pf_pooladdr *pool)
1509 {
1510 
1511 	bzero(pool, sizeof(*pool));
1512 	bcopy(&kpool->addr, &pool->addr, sizeof(pool->addr));
1513 	strlcpy(pool->ifname, kpool->ifname, sizeof(pool->ifname));
1514 }
1515 
1516 static void
1517 pf_pooladdr_to_kpooladdr(const struct pf_pooladdr *pool,
1518     struct pf_kpooladdr *kpool)
1519 {
1520 
1521 	bzero(kpool, sizeof(*kpool));
1522 	bcopy(&pool->addr, &kpool->addr, sizeof(kpool->addr));
1523 	strlcpy(kpool->ifname, pool->ifname, sizeof(kpool->ifname));
1524 }
1525 
1526 static void
1527 pf_kpool_to_pool(const struct pf_kpool *kpool, struct pf_pool *pool)
1528 {
1529 	bzero(pool, sizeof(*pool));
1530 
1531 	bcopy(&kpool->key, &pool->key, sizeof(pool->key));
1532 	bcopy(&kpool->counter, &pool->counter, sizeof(pool->counter));
1533 
1534 	pool->tblidx = kpool->tblidx;
1535 	pool->proxy_port[0] = kpool->proxy_port[0];
1536 	pool->proxy_port[1] = kpool->proxy_port[1];
1537 	pool->opts = kpool->opts;
1538 }
1539 
1540 static int
1541 pf_pool_to_kpool(const struct pf_pool *pool, struct pf_kpool *kpool)
1542 {
1543 	_Static_assert(sizeof(pool->key) == sizeof(kpool->key), "");
1544 	_Static_assert(sizeof(pool->counter) == sizeof(kpool->counter), "");
1545 
1546 	bzero(kpool, sizeof(*kpool));
1547 
1548 	bcopy(&pool->key, &kpool->key, sizeof(kpool->key));
1549 	bcopy(&pool->counter, &kpool->counter, sizeof(kpool->counter));
1550 
1551 	kpool->tblidx = pool->tblidx;
1552 	kpool->proxy_port[0] = pool->proxy_port[0];
1553 	kpool->proxy_port[1] = pool->proxy_port[1];
1554 	kpool->opts = pool->opts;
1555 
1556 	return (0);
1557 }
1558 
1559 static void
1560 pf_krule_to_rule(const struct pf_krule *krule, struct pf_rule *rule)
1561 {
1562 
1563 	bzero(rule, sizeof(*rule));
1564 
1565 	bcopy(&krule->src, &rule->src, sizeof(rule->src));
1566 	bcopy(&krule->dst, &rule->dst, sizeof(rule->dst));
1567 
1568 	for (int i = 0; i < PF_SKIP_COUNT; ++i) {
1569 		if (rule->skip[i].ptr == NULL)
1570 			rule->skip[i].nr = -1;
1571 		else
1572 			rule->skip[i].nr = krule->skip[i].ptr->nr;
1573 	}
1574 
1575 	strlcpy(rule->label, krule->label[0], sizeof(rule->label));
1576 	strlcpy(rule->ifname, krule->ifname, sizeof(rule->ifname));
1577 	strlcpy(rule->qname, krule->qname, sizeof(rule->qname));
1578 	strlcpy(rule->pqname, krule->pqname, sizeof(rule->pqname));
1579 	strlcpy(rule->tagname, krule->tagname, sizeof(rule->tagname));
1580 	strlcpy(rule->match_tagname, krule->match_tagname,
1581 	    sizeof(rule->match_tagname));
1582 	strlcpy(rule->overload_tblname, krule->overload_tblname,
1583 	    sizeof(rule->overload_tblname));
1584 
1585 	pf_kpool_to_pool(&krule->rpool, &rule->rpool);
1586 
1587 	rule->evaluations = counter_u64_fetch(krule->evaluations);
1588 	for (int i = 0; i < 2; i++) {
1589 		rule->packets[i] = counter_u64_fetch(krule->packets[i]);
1590 		rule->bytes[i] = counter_u64_fetch(krule->bytes[i]);
1591 	}
1592 
1593 	/* kif, anchor, overload_tbl are not copied over. */
1594 
1595 	rule->os_fingerprint = krule->os_fingerprint;
1596 
1597 	rule->rtableid = krule->rtableid;
1598 	bcopy(krule->timeout, rule->timeout, sizeof(krule->timeout));
1599 	rule->max_states = krule->max_states;
1600 	rule->max_src_nodes = krule->max_src_nodes;
1601 	rule->max_src_states = krule->max_src_states;
1602 	rule->max_src_conn = krule->max_src_conn;
1603 	rule->max_src_conn_rate.limit = krule->max_src_conn_rate.limit;
1604 	rule->max_src_conn_rate.seconds = krule->max_src_conn_rate.seconds;
1605 	rule->qid = krule->qid;
1606 	rule->pqid = krule->pqid;
1607 	rule->nr = krule->nr;
1608 	rule->prob = krule->prob;
1609 	rule->cuid = krule->cuid;
1610 	rule->cpid = krule->cpid;
1611 
1612 	rule->return_icmp = krule->return_icmp;
1613 	rule->return_icmp6 = krule->return_icmp6;
1614 	rule->max_mss = krule->max_mss;
1615 	rule->tag = krule->tag;
1616 	rule->match_tag = krule->match_tag;
1617 	rule->scrub_flags = krule->scrub_flags;
1618 
1619 	bcopy(&krule->uid, &rule->uid, sizeof(krule->uid));
1620 	bcopy(&krule->gid, &rule->gid, sizeof(krule->gid));
1621 
1622 	rule->rule_flag = krule->rule_flag;
1623 	rule->action = krule->action;
1624 	rule->direction = krule->direction;
1625 	rule->log = krule->log;
1626 	rule->logif = krule->logif;
1627 	rule->quick = krule->quick;
1628 	rule->ifnot = krule->ifnot;
1629 	rule->match_tag_not = krule->match_tag_not;
1630 	rule->natpass = krule->natpass;
1631 
1632 	rule->keep_state = krule->keep_state;
1633 	rule->af = krule->af;
1634 	rule->proto = krule->proto;
1635 	rule->type = krule->type;
1636 	rule->code = krule->code;
1637 	rule->flags = krule->flags;
1638 	rule->flagset = krule->flagset;
1639 	rule->min_ttl = krule->min_ttl;
1640 	rule->allow_opts = krule->allow_opts;
1641 	rule->rt = krule->rt;
1642 	rule->return_ttl = krule->return_ttl;
1643 	rule->tos = krule->tos;
1644 	rule->set_tos = krule->set_tos;
1645 	rule->anchor_relative = krule->anchor_relative;
1646 	rule->anchor_wildcard = krule->anchor_wildcard;
1647 
1648 	rule->flush = krule->flush;
1649 	rule->prio = krule->prio;
1650 	rule->set_prio[0] = krule->set_prio[0];
1651 	rule->set_prio[1] = krule->set_prio[1];
1652 
1653 	bcopy(&krule->divert, &rule->divert, sizeof(krule->divert));
1654 
1655 	rule->u_states_cur = counter_u64_fetch(krule->states_cur);
1656 	rule->u_states_tot = counter_u64_fetch(krule->states_tot);
1657 	rule->u_src_nodes = counter_u64_fetch(krule->src_nodes);
1658 }
1659 
1660 static int
1661 pf_rule_to_krule(const struct pf_rule *rule, struct pf_krule *krule)
1662 {
1663 	int ret;
1664 
1665 #ifndef INET
1666 	if (rule->af == AF_INET) {
1667 		return (EAFNOSUPPORT);
1668 	}
1669 #endif /* INET */
1670 #ifndef INET6
1671 	if (rule->af == AF_INET6) {
1672 		return (EAFNOSUPPORT);
1673 	}
1674 #endif /* INET6 */
1675 
1676 	ret = pf_check_rule_addr(&rule->src);
1677 	if (ret != 0)
1678 		return (ret);
1679 	ret = pf_check_rule_addr(&rule->dst);
1680 	if (ret != 0)
1681 		return (ret);
1682 
1683 	bzero(krule, sizeof(*krule));
1684 
1685 	bcopy(&rule->src, &krule->src, sizeof(rule->src));
1686 	bcopy(&rule->dst, &krule->dst, sizeof(rule->dst));
1687 
1688 	strlcpy(krule->label[0], rule->label, sizeof(rule->label));
1689 	strlcpy(krule->ifname, rule->ifname, sizeof(rule->ifname));
1690 	strlcpy(krule->qname, rule->qname, sizeof(rule->qname));
1691 	strlcpy(krule->pqname, rule->pqname, sizeof(rule->pqname));
1692 	strlcpy(krule->tagname, rule->tagname, sizeof(rule->tagname));
1693 	strlcpy(krule->match_tagname, rule->match_tagname,
1694 	    sizeof(rule->match_tagname));
1695 	strlcpy(krule->overload_tblname, rule->overload_tblname,
1696 	    sizeof(rule->overload_tblname));
1697 
1698 	ret = pf_pool_to_kpool(&rule->rpool, &krule->rpool);
1699 	if (ret != 0)
1700 		return (ret);
1701 
1702 	/* Don't allow userspace to set evaulations, packets or bytes. */
1703 	/* kif, anchor, overload_tbl are not copied over. */
1704 
1705 	krule->os_fingerprint = rule->os_fingerprint;
1706 
1707 	krule->rtableid = rule->rtableid;
1708 	bcopy(rule->timeout, krule->timeout, sizeof(krule->timeout));
1709 	krule->max_states = rule->max_states;
1710 	krule->max_src_nodes = rule->max_src_nodes;
1711 	krule->max_src_states = rule->max_src_states;
1712 	krule->max_src_conn = rule->max_src_conn;
1713 	krule->max_src_conn_rate.limit = rule->max_src_conn_rate.limit;
1714 	krule->max_src_conn_rate.seconds = rule->max_src_conn_rate.seconds;
1715 	krule->qid = rule->qid;
1716 	krule->pqid = rule->pqid;
1717 	krule->nr = rule->nr;
1718 	krule->prob = rule->prob;
1719 	krule->cuid = rule->cuid;
1720 	krule->cpid = rule->cpid;
1721 
1722 	krule->return_icmp = rule->return_icmp;
1723 	krule->return_icmp6 = rule->return_icmp6;
1724 	krule->max_mss = rule->max_mss;
1725 	krule->tag = rule->tag;
1726 	krule->match_tag = rule->match_tag;
1727 	krule->scrub_flags = rule->scrub_flags;
1728 
1729 	bcopy(&rule->uid, &krule->uid, sizeof(krule->uid));
1730 	bcopy(&rule->gid, &krule->gid, sizeof(krule->gid));
1731 
1732 	krule->rule_flag = rule->rule_flag;
1733 	krule->action = rule->action;
1734 	krule->direction = rule->direction;
1735 	krule->log = rule->log;
1736 	krule->logif = rule->logif;
1737 	krule->quick = rule->quick;
1738 	krule->ifnot = rule->ifnot;
1739 	krule->match_tag_not = rule->match_tag_not;
1740 	krule->natpass = rule->natpass;
1741 
1742 	krule->keep_state = rule->keep_state;
1743 	krule->af = rule->af;
1744 	krule->proto = rule->proto;
1745 	krule->type = rule->type;
1746 	krule->code = rule->code;
1747 	krule->flags = rule->flags;
1748 	krule->flagset = rule->flagset;
1749 	krule->min_ttl = rule->min_ttl;
1750 	krule->allow_opts = rule->allow_opts;
1751 	krule->rt = rule->rt;
1752 	krule->return_ttl = rule->return_ttl;
1753 	krule->tos = rule->tos;
1754 	krule->set_tos = rule->set_tos;
1755 	krule->anchor_relative = rule->anchor_relative;
1756 	krule->anchor_wildcard = rule->anchor_wildcard;
1757 
1758 	krule->flush = rule->flush;
1759 	krule->prio = rule->prio;
1760 	krule->set_prio[0] = rule->set_prio[0];
1761 	krule->set_prio[1] = rule->set_prio[1];
1762 
1763 	bcopy(&rule->divert, &krule->divert, sizeof(krule->divert));
1764 
1765 	return (0);
1766 }
1767 
1768 static int
1769 pf_state_kill_to_kstate_kill(const struct pfioc_state_kill *psk,
1770     struct pf_kstate_kill *kill)
1771 {
1772 	bzero(kill, sizeof(*kill));
1773 
1774 	bcopy(&psk->psk_pfcmp, &kill->psk_pfcmp, sizeof(kill->psk_pfcmp));
1775 	kill->psk_af = psk->psk_af;
1776 	kill->psk_proto = psk->psk_proto;
1777 	bcopy(&psk->psk_src, &kill->psk_src, sizeof(kill->psk_src));
1778 	bcopy(&psk->psk_dst, &kill->psk_dst, sizeof(kill->psk_dst));
1779 	strlcpy(kill->psk_ifname, psk->psk_ifname, sizeof(kill->psk_ifname));
1780 	strlcpy(kill->psk_label, psk->psk_label, sizeof(kill->psk_label));
1781 
1782 	return (0);
1783 }
1784 
1785 static int
1786 pf_ioctl_addrule(struct pf_krule *rule, uint32_t ticket,
1787     uint32_t pool_ticket, const char *anchor, const char *anchor_call,
1788     struct thread *td)
1789 {
1790 	struct pf_kruleset	*ruleset;
1791 	struct pf_krule		*tail;
1792 	struct pf_kpooladdr	*pa;
1793 	struct pfi_kkif		*kif = NULL;
1794 	int			 rs_num;
1795 	int			 error = 0;
1796 
1797 	if ((rule->return_icmp >> 8) > ICMP_MAXTYPE) {
1798 		error = EINVAL;
1799 		goto errout_unlocked;
1800 	}
1801 
1802 #define	ERROUT(x)	ERROUT_FUNCTION(errout, x)
1803 
1804 	if (rule->ifname[0])
1805 		kif = pf_kkif_create(M_WAITOK);
1806 	rule->evaluations = counter_u64_alloc(M_WAITOK);
1807 	for (int i = 0; i < 2; i++) {
1808 		rule->packets[i] = counter_u64_alloc(M_WAITOK);
1809 		rule->bytes[i] = counter_u64_alloc(M_WAITOK);
1810 	}
1811 	rule->states_cur = counter_u64_alloc(M_WAITOK);
1812 	rule->states_tot = counter_u64_alloc(M_WAITOK);
1813 	rule->src_nodes = counter_u64_alloc(M_WAITOK);
1814 	rule->cuid = td->td_ucred->cr_ruid;
1815 	rule->cpid = td->td_proc ? td->td_proc->p_pid : 0;
1816 	TAILQ_INIT(&rule->rpool.list);
1817 
1818 	PF_RULES_WLOCK();
1819 	ruleset = pf_find_kruleset(anchor);
1820 	if (ruleset == NULL)
1821 		ERROUT(EINVAL);
1822 	rs_num = pf_get_ruleset_number(rule->action);
1823 	if (rs_num >= PF_RULESET_MAX)
1824 		ERROUT(EINVAL);
1825 	if (ticket != ruleset->rules[rs_num].inactive.ticket) {
1826 		DPFPRINTF(PF_DEBUG_MISC,
1827 		    ("ticket: %d != [%d]%d\n", ticket, rs_num,
1828 		    ruleset->rules[rs_num].inactive.ticket));
1829 		ERROUT(EBUSY);
1830 	}
1831 	if (pool_ticket != V_ticket_pabuf) {
1832 		DPFPRINTF(PF_DEBUG_MISC,
1833 		    ("pool_ticket: %d != %d\n", pool_ticket,
1834 		    V_ticket_pabuf));
1835 		ERROUT(EBUSY);
1836 	}
1837 
1838 	tail = TAILQ_LAST(ruleset->rules[rs_num].inactive.ptr,
1839 	    pf_krulequeue);
1840 	if (tail)
1841 		rule->nr = tail->nr + 1;
1842 	else
1843 		rule->nr = 0;
1844 	if (rule->ifname[0]) {
1845 		rule->kif = pfi_kkif_attach(kif, rule->ifname);
1846 		kif = NULL;
1847 		pfi_kkif_ref(rule->kif);
1848 	} else
1849 		rule->kif = NULL;
1850 
1851 	if (rule->rtableid > 0 && rule->rtableid >= rt_numfibs)
1852 		error = EBUSY;
1853 
1854 #ifdef ALTQ
1855 	/* set queue IDs */
1856 	if (rule->qname[0] != 0) {
1857 		if ((rule->qid = pf_qname2qid(rule->qname)) == 0)
1858 			error = EBUSY;
1859 		else if (rule->pqname[0] != 0) {
1860 			if ((rule->pqid =
1861 			    pf_qname2qid(rule->pqname)) == 0)
1862 				error = EBUSY;
1863 		} else
1864 			rule->pqid = rule->qid;
1865 	}
1866 #endif
1867 	if (rule->tagname[0])
1868 		if ((rule->tag = pf_tagname2tag(rule->tagname)) == 0)
1869 			error = EBUSY;
1870 	if (rule->match_tagname[0])
1871 		if ((rule->match_tag =
1872 		    pf_tagname2tag(rule->match_tagname)) == 0)
1873 			error = EBUSY;
1874 	if (rule->rt && !rule->direction)
1875 		error = EINVAL;
1876 	if (!rule->log)
1877 		rule->logif = 0;
1878 	if (rule->logif >= PFLOGIFS_MAX)
1879 		error = EINVAL;
1880 	if (pf_addr_setup(ruleset, &rule->src.addr, rule->af))
1881 		error = ENOMEM;
1882 	if (pf_addr_setup(ruleset, &rule->dst.addr, rule->af))
1883 		error = ENOMEM;
1884 	if (pf_kanchor_setup(rule, ruleset, anchor_call))
1885 		error = EINVAL;
1886 	if (rule->scrub_flags & PFSTATE_SETPRIO &&
1887 	    (rule->set_prio[0] > PF_PRIO_MAX ||
1888 	    rule->set_prio[1] > PF_PRIO_MAX))
1889 		error = EINVAL;
1890 	TAILQ_FOREACH(pa, &V_pf_pabuf, entries)
1891 		if (pa->addr.type == PF_ADDR_TABLE) {
1892 			pa->addr.p.tbl = pfr_attach_table(ruleset,
1893 			    pa->addr.v.tblname);
1894 			if (pa->addr.p.tbl == NULL)
1895 				error = ENOMEM;
1896 		}
1897 
1898 	rule->overload_tbl = NULL;
1899 	if (rule->overload_tblname[0]) {
1900 		if ((rule->overload_tbl = pfr_attach_table(ruleset,
1901 		    rule->overload_tblname)) == NULL)
1902 			error = EINVAL;
1903 		else
1904 			rule->overload_tbl->pfrkt_flags |=
1905 			    PFR_TFLAG_ACTIVE;
1906 	}
1907 
1908 	pf_mv_kpool(&V_pf_pabuf, &rule->rpool.list);
1909 	if (((((rule->action == PF_NAT) || (rule->action == PF_RDR) ||
1910 	    (rule->action == PF_BINAT)) && rule->anchor == NULL) ||
1911 	    (rule->rt > PF_NOPFROUTE)) &&
1912 	    (TAILQ_FIRST(&rule->rpool.list) == NULL))
1913 		error = EINVAL;
1914 
1915 	if (error) {
1916 		pf_free_rule(rule);
1917 		rule = NULL;
1918 		ERROUT(error);
1919 	}
1920 
1921 	rule->rpool.cur = TAILQ_FIRST(&rule->rpool.list);
1922 	counter_u64_zero(rule->evaluations);
1923 	for (int i = 0; i < 2; i++) {
1924 		counter_u64_zero(rule->packets[i]);
1925 		counter_u64_zero(rule->bytes[i]);
1926 	}
1927 	TAILQ_INSERT_TAIL(ruleset->rules[rs_num].inactive.ptr,
1928 	    rule, entries);
1929 	ruleset->rules[rs_num].inactive.rcount++;
1930 	PF_RULES_WUNLOCK();
1931 
1932 	return (0);
1933 
1934 #undef ERROUT
1935 errout:
1936 	PF_RULES_WUNLOCK();
1937 errout_unlocked:
1938 	pf_kkif_free(kif);
1939 	pf_krule_free(rule);
1940 	return (error);
1941 }
1942 
1943 static bool
1944 pf_label_match(const struct pf_krule *rule, const char *label)
1945 {
1946 	int i = 0;
1947 
1948 	while (*rule->label[i]) {
1949 		if (strcmp(rule->label[i], label) == 0)
1950 			return (true);
1951 		i++;
1952 	}
1953 
1954 	return (false);
1955 }
1956 
1957 static unsigned int
1958 pf_kill_matching_state(struct pf_state_key_cmp *key, int dir)
1959 {
1960 	struct pf_kstate *match;
1961 	int more = 0;
1962 	unsigned int killed = 0;
1963 
1964 	/* Call with unlocked hashrow */
1965 
1966 	match = pf_find_state_all(key, dir, &more);
1967 	if (match && !more) {
1968 		pf_unlink_state(match, 0);
1969 		killed++;
1970 	}
1971 
1972 	return (killed);
1973 }
1974 
1975 static int
1976 pf_killstates_row(struct pf_kstate_kill *psk, struct pf_idhash *ih)
1977 {
1978 	struct pf_kstate	*s;
1979 	struct pf_state_key	*sk;
1980 	struct pf_addr		*srcaddr, *dstaddr;
1981 	struct pf_state_key_cmp	 match_key;
1982 	int			 idx, killed = 0;
1983 	unsigned int		 dir;
1984 	u_int16_t		 srcport, dstport;
1985 	struct pfi_kkif		*kif;
1986 
1987 relock_DIOCKILLSTATES:
1988 	PF_HASHROW_LOCK(ih);
1989 	LIST_FOREACH(s, &ih->states, entry) {
1990 		/* For floating states look at the original kif. */
1991 		kif = s->kif == V_pfi_all ? s->orig_kif : s->kif;
1992 
1993 		sk = s->key[PF_SK_WIRE];
1994 		if (s->direction == PF_OUT) {
1995 			srcaddr = &sk->addr[1];
1996 			dstaddr = &sk->addr[0];
1997 			srcport = sk->port[1];
1998 			dstport = sk->port[0];
1999 		} else {
2000 			srcaddr = &sk->addr[0];
2001 			dstaddr = &sk->addr[1];
2002 			srcport = sk->port[0];
2003 			dstport = sk->port[1];
2004 		}
2005 
2006 		if (psk->psk_af && sk->af != psk->psk_af)
2007 			continue;
2008 
2009 		if (psk->psk_proto && psk->psk_proto != sk->proto)
2010 			continue;
2011 
2012 		if (! PF_MATCHA(psk->psk_src.neg, &psk->psk_src.addr.v.a.addr,
2013 		    &psk->psk_src.addr.v.a.mask, srcaddr, sk->af))
2014 			continue;
2015 
2016 		if (! PF_MATCHA(psk->psk_dst.neg, &psk->psk_dst.addr.v.a.addr,
2017 		    &psk->psk_dst.addr.v.a.mask, dstaddr, sk->af))
2018 			continue;
2019 
2020 		if (!  PF_MATCHA(psk->psk_rt_addr.neg,
2021 		    &psk->psk_rt_addr.addr.v.a.addr,
2022 		    &psk->psk_rt_addr.addr.v.a.mask,
2023 		    &s->rt_addr, sk->af))
2024 			continue;
2025 
2026 		if (psk->psk_src.port_op != 0 &&
2027 		    ! pf_match_port(psk->psk_src.port_op,
2028 		    psk->psk_src.port[0], psk->psk_src.port[1], srcport))
2029 			continue;
2030 
2031 		if (psk->psk_dst.port_op != 0 &&
2032 		    ! pf_match_port(psk->psk_dst.port_op,
2033 		    psk->psk_dst.port[0], psk->psk_dst.port[1], dstport))
2034 			continue;
2035 
2036 		if (psk->psk_label[0] &&
2037 		    ! pf_label_match(s->rule.ptr, psk->psk_label))
2038 			continue;
2039 
2040 		if (psk->psk_ifname[0] && strcmp(psk->psk_ifname,
2041 		    kif->pfik_name))
2042 			continue;
2043 
2044 		if (psk->psk_kill_match) {
2045 			/* Create the key to find matching states, with lock
2046 			 * held. */
2047 
2048 			bzero(&match_key, sizeof(match_key));
2049 
2050 			if (s->direction == PF_OUT) {
2051 				dir = PF_IN;
2052 				idx = PF_SK_STACK;
2053 			} else {
2054 				dir = PF_OUT;
2055 				idx = PF_SK_WIRE;
2056 			}
2057 
2058 			match_key.af = s->key[idx]->af;
2059 			match_key.proto = s->key[idx]->proto;
2060 			PF_ACPY(&match_key.addr[0],
2061 			    &s->key[idx]->addr[1], match_key.af);
2062 			match_key.port[0] = s->key[idx]->port[1];
2063 			PF_ACPY(&match_key.addr[1],
2064 			    &s->key[idx]->addr[0], match_key.af);
2065 			match_key.port[1] = s->key[idx]->port[0];
2066 		}
2067 
2068 		pf_unlink_state(s, PF_ENTER_LOCKED);
2069 		killed++;
2070 
2071 		if (psk->psk_kill_match)
2072 			killed += pf_kill_matching_state(&match_key, dir);
2073 
2074 		goto relock_DIOCKILLSTATES;
2075 	}
2076 	PF_HASHROW_UNLOCK(ih);
2077 
2078 	return (killed);
2079 }
2080 
2081 static int
2082 pfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
2083 {
2084 	int			 error = 0;
2085 	PF_RULES_RLOCK_TRACKER;
2086 
2087 #define	ERROUT_IOCTL(target, x)					\
2088     do {								\
2089 	    error = (x);						\
2090 	    SDT_PROBE3(pf, ioctl, ioctl, error, cmd, error, __LINE__);	\
2091 	    goto target;						\
2092     } while (0)
2093 
2094 
2095 	/* XXX keep in sync with switch() below */
2096 	if (securelevel_gt(td->td_ucred, 2))
2097 		switch (cmd) {
2098 		case DIOCGETRULES:
2099 		case DIOCGETRULE:
2100 		case DIOCGETRULENV:
2101 		case DIOCGETADDRS:
2102 		case DIOCGETADDR:
2103 		case DIOCGETSTATE:
2104 		case DIOCGETSTATENV:
2105 		case DIOCSETSTATUSIF:
2106 		case DIOCGETSTATUS:
2107 		case DIOCCLRSTATUS:
2108 		case DIOCNATLOOK:
2109 		case DIOCSETDEBUG:
2110 		case DIOCGETSTATES:
2111 		case DIOCGETSTATESV2:
2112 		case DIOCGETSTATESNV:
2113 		case DIOCGETTIMEOUT:
2114 		case DIOCCLRRULECTRS:
2115 		case DIOCGETLIMIT:
2116 		case DIOCGETALTQSV0:
2117 		case DIOCGETALTQSV1:
2118 		case DIOCGETALTQV0:
2119 		case DIOCGETALTQV1:
2120 		case DIOCGETQSTATSV0:
2121 		case DIOCGETQSTATSV1:
2122 		case DIOCGETRULESETS:
2123 		case DIOCGETRULESET:
2124 		case DIOCRGETTABLES:
2125 		case DIOCRGETTSTATS:
2126 		case DIOCRCLRTSTATS:
2127 		case DIOCRCLRADDRS:
2128 		case DIOCRADDADDRS:
2129 		case DIOCRDELADDRS:
2130 		case DIOCRSETADDRS:
2131 		case DIOCRGETADDRS:
2132 		case DIOCRGETASTATS:
2133 		case DIOCRCLRASTATS:
2134 		case DIOCRTSTADDRS:
2135 		case DIOCOSFPGET:
2136 		case DIOCGETSRCNODES:
2137 		case DIOCCLRSRCNODES:
2138 		case DIOCIGETIFACES:
2139 		case DIOCGIFSPEEDV0:
2140 		case DIOCGIFSPEEDV1:
2141 		case DIOCSETIFFLAG:
2142 		case DIOCCLRIFFLAG:
2143 			break;
2144 		case DIOCRCLRTABLES:
2145 		case DIOCRADDTABLES:
2146 		case DIOCRDELTABLES:
2147 		case DIOCRSETTFLAGS:
2148 			if (((struct pfioc_table *)addr)->pfrio_flags &
2149 			    PFR_FLAG_DUMMY)
2150 				break; /* dummy operation ok */
2151 			return (EPERM);
2152 		default:
2153 			return (EPERM);
2154 		}
2155 
2156 	if (!(flags & FWRITE))
2157 		switch (cmd) {
2158 		case DIOCGETRULES:
2159 		case DIOCGETADDRS:
2160 		case DIOCGETADDR:
2161 		case DIOCGETSTATE:
2162 		case DIOCGETSTATENV:
2163 		case DIOCGETSTATUS:
2164 		case DIOCGETSTATES:
2165 		case DIOCGETSTATESV2:
2166 		case DIOCGETSTATESNV:
2167 		case DIOCGETTIMEOUT:
2168 		case DIOCGETLIMIT:
2169 		case DIOCGETALTQSV0:
2170 		case DIOCGETALTQSV1:
2171 		case DIOCGETALTQV0:
2172 		case DIOCGETALTQV1:
2173 		case DIOCGETQSTATSV0:
2174 		case DIOCGETQSTATSV1:
2175 		case DIOCGETRULESETS:
2176 		case DIOCGETRULESET:
2177 		case DIOCNATLOOK:
2178 		case DIOCRGETTABLES:
2179 		case DIOCRGETTSTATS:
2180 		case DIOCRGETADDRS:
2181 		case DIOCRGETASTATS:
2182 		case DIOCRTSTADDRS:
2183 		case DIOCOSFPGET:
2184 		case DIOCGETSRCNODES:
2185 		case DIOCIGETIFACES:
2186 		case DIOCGIFSPEEDV1:
2187 		case DIOCGIFSPEEDV0:
2188 		case DIOCGETRULENV:
2189 			break;
2190 		case DIOCRCLRTABLES:
2191 		case DIOCRADDTABLES:
2192 		case DIOCRDELTABLES:
2193 		case DIOCRCLRTSTATS:
2194 		case DIOCRCLRADDRS:
2195 		case DIOCRADDADDRS:
2196 		case DIOCRDELADDRS:
2197 		case DIOCRSETADDRS:
2198 		case DIOCRSETTFLAGS:
2199 			if (((struct pfioc_table *)addr)->pfrio_flags &
2200 			    PFR_FLAG_DUMMY) {
2201 				flags |= FWRITE; /* need write lock for dummy */
2202 				break; /* dummy operation ok */
2203 			}
2204 			return (EACCES);
2205 		case DIOCGETRULE:
2206 			if (((struct pfioc_rule *)addr)->action ==
2207 			    PF_GET_CLR_CNTR)
2208 				return (EACCES);
2209 			break;
2210 		default:
2211 			return (EACCES);
2212 		}
2213 
2214 	CURVNET_SET(TD_TO_VNET(td));
2215 
2216 	switch (cmd) {
2217 	case DIOCSTART:
2218 		sx_xlock(&pf_ioctl_lock);
2219 		if (V_pf_status.running)
2220 			error = EEXIST;
2221 		else {
2222 			int cpu;
2223 
2224 			hook_pf();
2225 			V_pf_status.running = 1;
2226 			V_pf_status.since = time_second;
2227 
2228 			CPU_FOREACH(cpu)
2229 				V_pf_stateid[cpu] = time_second;
2230 
2231 			DPFPRINTF(PF_DEBUG_MISC, ("pf: started\n"));
2232 		}
2233 		break;
2234 
2235 	case DIOCSTOP:
2236 		sx_xlock(&pf_ioctl_lock);
2237 		if (!V_pf_status.running)
2238 			error = ENOENT;
2239 		else {
2240 			V_pf_status.running = 0;
2241 			dehook_pf();
2242 			V_pf_status.since = time_second;
2243 			DPFPRINTF(PF_DEBUG_MISC, ("pf: stopped\n"));
2244 		}
2245 		break;
2246 
2247 	case DIOCADDRULENV: {
2248 		struct pfioc_nv	*nv = (struct pfioc_nv *)addr;
2249 		nvlist_t	*nvl = NULL;
2250 		void		*nvlpacked = NULL;
2251 		struct pf_krule	*rule = NULL;
2252 		const char	*anchor = "", *anchor_call = "";
2253 		uint32_t	 ticket = 0, pool_ticket = 0;
2254 
2255 #define	ERROUT(x)	ERROUT_IOCTL(DIOCADDRULENV_error, x)
2256 
2257 		if (nv->len > pf_ioctl_maxcount)
2258 			ERROUT(ENOMEM);
2259 
2260 		nvlpacked = malloc(nv->len, M_TEMP, M_WAITOK);
2261 		error = copyin(nv->data, nvlpacked, nv->len);
2262 		if (error)
2263 			ERROUT(error);
2264 
2265 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
2266 		if (nvl == NULL)
2267 			ERROUT(EBADMSG);
2268 
2269 		if (! nvlist_exists_number(nvl, "ticket"))
2270 			ERROUT(EINVAL);
2271 		ticket = nvlist_get_number(nvl, "ticket");
2272 
2273 		if (! nvlist_exists_number(nvl, "pool_ticket"))
2274 			ERROUT(EINVAL);
2275 		pool_ticket = nvlist_get_number(nvl, "pool_ticket");
2276 
2277 		if (! nvlist_exists_nvlist(nvl, "rule"))
2278 			ERROUT(EINVAL);
2279 
2280 		rule = malloc(sizeof(*rule), M_PFRULE, M_WAITOK | M_ZERO);
2281 		error = pf_nvrule_to_krule(nvlist_get_nvlist(nvl, "rule"),
2282 		    rule);
2283 		if (error)
2284 			ERROUT(error);
2285 
2286 		if (nvlist_exists_string(nvl, "anchor"))
2287 			anchor = nvlist_get_string(nvl, "anchor");
2288 		if (nvlist_exists_string(nvl, "anchor_call"))
2289 			anchor_call = nvlist_get_string(nvl, "anchor_call");
2290 
2291 		if ((error = nvlist_error(nvl)))
2292 			ERROUT(error);
2293 
2294 		/* Frees rule on error */
2295 		error = pf_ioctl_addrule(rule, ticket, pool_ticket, anchor,
2296 		    anchor_call, td);
2297 
2298 		nvlist_destroy(nvl);
2299 		free(nvlpacked, M_TEMP);
2300 		break;
2301 #undef ERROUT
2302 DIOCADDRULENV_error:
2303 		pf_krule_free(rule);
2304 		nvlist_destroy(nvl);
2305 		free(nvlpacked, M_TEMP);
2306 
2307 		break;
2308 	}
2309 	case DIOCADDRULE: {
2310 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
2311 		struct pf_krule		*rule;
2312 
2313 		rule = malloc(sizeof(*rule), M_PFRULE, M_WAITOK);
2314 		error = pf_rule_to_krule(&pr->rule, rule);
2315 		if (error != 0) {
2316 			free(rule, M_PFRULE);
2317 			break;
2318 		}
2319 
2320 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
2321 
2322 		/* Frees rule on error */
2323 		error = pf_ioctl_addrule(rule, pr->ticket, pr->pool_ticket,
2324 		    pr->anchor, pr->anchor_call, td);
2325 		break;
2326 	}
2327 
2328 	case DIOCGETRULES: {
2329 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
2330 		struct pf_kruleset	*ruleset;
2331 		struct pf_krule		*tail;
2332 		int			 rs_num;
2333 
2334 		PF_RULES_WLOCK();
2335 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
2336 		ruleset = pf_find_kruleset(pr->anchor);
2337 		if (ruleset == NULL) {
2338 			PF_RULES_WUNLOCK();
2339 			error = EINVAL;
2340 			break;
2341 		}
2342 		rs_num = pf_get_ruleset_number(pr->rule.action);
2343 		if (rs_num >= PF_RULESET_MAX) {
2344 			PF_RULES_WUNLOCK();
2345 			error = EINVAL;
2346 			break;
2347 		}
2348 		tail = TAILQ_LAST(ruleset->rules[rs_num].active.ptr,
2349 		    pf_krulequeue);
2350 		if (tail)
2351 			pr->nr = tail->nr + 1;
2352 		else
2353 			pr->nr = 0;
2354 		pr->ticket = ruleset->rules[rs_num].active.ticket;
2355 		PF_RULES_WUNLOCK();
2356 		break;
2357 	}
2358 
2359 	case DIOCGETRULE: {
2360 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
2361 		struct pf_kruleset	*ruleset;
2362 		struct pf_krule		*rule;
2363 		int			 rs_num;
2364 
2365 		PF_RULES_WLOCK();
2366 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
2367 		ruleset = pf_find_kruleset(pr->anchor);
2368 		if (ruleset == NULL) {
2369 			PF_RULES_WUNLOCK();
2370 			error = EINVAL;
2371 			break;
2372 		}
2373 		rs_num = pf_get_ruleset_number(pr->rule.action);
2374 		if (rs_num >= PF_RULESET_MAX) {
2375 			PF_RULES_WUNLOCK();
2376 			error = EINVAL;
2377 			break;
2378 		}
2379 		if (pr->ticket != ruleset->rules[rs_num].active.ticket) {
2380 			PF_RULES_WUNLOCK();
2381 			error = EBUSY;
2382 			break;
2383 		}
2384 		rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
2385 		while ((rule != NULL) && (rule->nr != pr->nr))
2386 			rule = TAILQ_NEXT(rule, entries);
2387 		if (rule == NULL) {
2388 			PF_RULES_WUNLOCK();
2389 			error = EBUSY;
2390 			break;
2391 		}
2392 
2393 		pf_krule_to_rule(rule, &pr->rule);
2394 
2395 		if (pf_kanchor_copyout(ruleset, rule, pr)) {
2396 			PF_RULES_WUNLOCK();
2397 			error = EBUSY;
2398 			break;
2399 		}
2400 		pf_addr_copyout(&pr->rule.src.addr);
2401 		pf_addr_copyout(&pr->rule.dst.addr);
2402 
2403 		if (pr->action == PF_GET_CLR_CNTR) {
2404 			counter_u64_zero(rule->evaluations);
2405 			for (int i = 0; i < 2; i++) {
2406 				counter_u64_zero(rule->packets[i]);
2407 				counter_u64_zero(rule->bytes[i]);
2408 			}
2409 			counter_u64_zero(rule->states_tot);
2410 		}
2411 		PF_RULES_WUNLOCK();
2412 		break;
2413 	}
2414 
2415 	case DIOCGETRULENV: {
2416 		struct pfioc_nv		*nv = (struct pfioc_nv *)addr;
2417 		nvlist_t		*nvrule = NULL;
2418 		nvlist_t		*nvl = NULL;
2419 		struct pf_kruleset	*ruleset;
2420 		struct pf_krule		*rule;
2421 		void			*nvlpacked = NULL;
2422 		int			 rs_num, nr;
2423 		bool			 clear_counter = false;
2424 
2425 #define	ERROUT(x)	ERROUT_IOCTL(DIOCGETRULENV_error, x)
2426 
2427 		if (nv->len > pf_ioctl_maxcount)
2428 			ERROUT(ENOMEM);
2429 
2430 		/* Copy the request in */
2431 		nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
2432 		if (nvlpacked == NULL)
2433 			ERROUT(ENOMEM);
2434 
2435 		error = copyin(nv->data, nvlpacked, nv->len);
2436 		if (error)
2437 			ERROUT(error);
2438 
2439 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
2440 		if (nvl == NULL)
2441 			ERROUT(EBADMSG);
2442 
2443 		if (! nvlist_exists_string(nvl, "anchor"))
2444 			ERROUT(EBADMSG);
2445 		if (! nvlist_exists_number(nvl, "ruleset"))
2446 			ERROUT(EBADMSG);
2447 		if (! nvlist_exists_number(nvl, "ticket"))
2448 			ERROUT(EBADMSG);
2449 		if (! nvlist_exists_number(nvl, "nr"))
2450 			ERROUT(EBADMSG);
2451 
2452 		if (nvlist_exists_bool(nvl, "clear_counter"))
2453 			clear_counter = nvlist_get_bool(nvl, "clear_counter");
2454 
2455 		if (clear_counter && !(flags & FWRITE))
2456 			ERROUT(EACCES);
2457 
2458 		nr = nvlist_get_number(nvl, "nr");
2459 
2460 		PF_RULES_WLOCK();
2461 		ruleset = pf_find_kruleset(nvlist_get_string(nvl, "anchor"));
2462 		if (ruleset == NULL) {
2463 			PF_RULES_WUNLOCK();
2464 			ERROUT(ENOENT);
2465 		}
2466 
2467 		rs_num = pf_get_ruleset_number(nvlist_get_number(nvl, "ruleset"));
2468 		if (rs_num >= PF_RULESET_MAX) {
2469 			PF_RULES_WUNLOCK();
2470 			ERROUT(EINVAL);
2471 		}
2472 
2473 		if (nvlist_get_number(nvl, "ticket") !=
2474 		    ruleset->rules[rs_num].active.ticket) {
2475 			PF_RULES_WUNLOCK();
2476 			ERROUT(EBUSY);
2477 		}
2478 
2479 		if ((error = nvlist_error(nvl))) {
2480 			PF_RULES_WUNLOCK();
2481 			ERROUT(error);
2482 		}
2483 
2484 		rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
2485 		while ((rule != NULL) && (rule->nr != nr))
2486 			rule = TAILQ_NEXT(rule, entries);
2487 		if (rule == NULL) {
2488 			PF_RULES_WUNLOCK();
2489 			ERROUT(EBUSY);
2490 		}
2491 
2492 		nvrule = pf_krule_to_nvrule(rule);
2493 
2494 		nvlist_destroy(nvl);
2495 		nvl = nvlist_create(0);
2496 		if (nvl == NULL) {
2497 			PF_RULES_WUNLOCK();
2498 			ERROUT(ENOMEM);
2499 		}
2500 		nvlist_add_number(nvl, "nr", nr);
2501 		nvlist_add_nvlist(nvl, "rule", nvrule);
2502 		nvlist_destroy(nvrule);
2503 		nvrule = NULL;
2504 		if (pf_kanchor_nvcopyout(ruleset, rule, nvl)) {
2505 			PF_RULES_WUNLOCK();
2506 			ERROUT(EBUSY);
2507 		}
2508 
2509 		free(nvlpacked, M_NVLIST);
2510 		nvlpacked = nvlist_pack(nvl, &nv->len);
2511 		if (nvlpacked == NULL) {
2512 			PF_RULES_WUNLOCK();
2513 			ERROUT(ENOMEM);
2514 		}
2515 
2516 		if (nv->size == 0) {
2517 			PF_RULES_WUNLOCK();
2518 			ERROUT(0);
2519 		}
2520 		else if (nv->size < nv->len) {
2521 			PF_RULES_WUNLOCK();
2522 			ERROUT(ENOSPC);
2523 		}
2524 
2525 		if (clear_counter) {
2526 			counter_u64_zero(rule->evaluations);
2527 			for (int i = 0; i < 2; i++) {
2528 				counter_u64_zero(rule->packets[i]);
2529 				counter_u64_zero(rule->bytes[i]);
2530 			}
2531 			counter_u64_zero(rule->states_tot);
2532 		}
2533 		PF_RULES_WUNLOCK();
2534 
2535 		error = copyout(nvlpacked, nv->data, nv->len);
2536 
2537 #undef ERROUT
2538 DIOCGETRULENV_error:
2539 		free(nvlpacked, M_NVLIST);
2540 		nvlist_destroy(nvrule);
2541 		nvlist_destroy(nvl);
2542 
2543 		break;
2544 	}
2545 
2546 	case DIOCCHANGERULE: {
2547 		struct pfioc_rule	*pcr = (struct pfioc_rule *)addr;
2548 		struct pf_kruleset	*ruleset;
2549 		struct pf_krule		*oldrule = NULL, *newrule = NULL;
2550 		struct pfi_kkif		*kif = NULL;
2551 		struct pf_kpooladdr	*pa;
2552 		u_int32_t		 nr = 0;
2553 		int			 rs_num;
2554 
2555 		if (pcr->action < PF_CHANGE_ADD_HEAD ||
2556 		    pcr->action > PF_CHANGE_GET_TICKET) {
2557 			error = EINVAL;
2558 			break;
2559 		}
2560 		if (pcr->rule.return_icmp >> 8 > ICMP_MAXTYPE) {
2561 			error = EINVAL;
2562 			break;
2563 		}
2564 
2565 		if (pcr->action != PF_CHANGE_REMOVE) {
2566 			newrule = malloc(sizeof(*newrule), M_PFRULE, M_WAITOK);
2567 			error = pf_rule_to_krule(&pcr->rule, newrule);
2568 			if (error != 0) {
2569 				free(newrule, M_PFRULE);
2570 				break;
2571 			}
2572 
2573 			if (newrule->ifname[0])
2574 				kif = pf_kkif_create(M_WAITOK);
2575 			newrule->evaluations = counter_u64_alloc(M_WAITOK);
2576 			for (int i = 0; i < 2; i++) {
2577 				newrule->packets[i] =
2578 				    counter_u64_alloc(M_WAITOK);
2579 				newrule->bytes[i] =
2580 				    counter_u64_alloc(M_WAITOK);
2581 			}
2582 			newrule->states_cur = counter_u64_alloc(M_WAITOK);
2583 			newrule->states_tot = counter_u64_alloc(M_WAITOK);
2584 			newrule->src_nodes = counter_u64_alloc(M_WAITOK);
2585 			newrule->cuid = td->td_ucred->cr_ruid;
2586 			newrule->cpid = td->td_proc ? td->td_proc->p_pid : 0;
2587 			TAILQ_INIT(&newrule->rpool.list);
2588 		}
2589 #define	ERROUT(x)	{ error = (x); goto DIOCCHANGERULE_error; }
2590 
2591 		PF_RULES_WLOCK();
2592 		if (!(pcr->action == PF_CHANGE_REMOVE ||
2593 		    pcr->action == PF_CHANGE_GET_TICKET) &&
2594 		    pcr->pool_ticket != V_ticket_pabuf)
2595 			ERROUT(EBUSY);
2596 
2597 		ruleset = pf_find_kruleset(pcr->anchor);
2598 		if (ruleset == NULL)
2599 			ERROUT(EINVAL);
2600 
2601 		rs_num = pf_get_ruleset_number(pcr->rule.action);
2602 		if (rs_num >= PF_RULESET_MAX)
2603 			ERROUT(EINVAL);
2604 
2605 		if (pcr->action == PF_CHANGE_GET_TICKET) {
2606 			pcr->ticket = ++ruleset->rules[rs_num].active.ticket;
2607 			ERROUT(0);
2608 		} else if (pcr->ticket !=
2609 			    ruleset->rules[rs_num].active.ticket)
2610 				ERROUT(EINVAL);
2611 
2612 		if (pcr->action != PF_CHANGE_REMOVE) {
2613 			if (newrule->ifname[0]) {
2614 				newrule->kif = pfi_kkif_attach(kif,
2615 				    newrule->ifname);
2616 				kif = NULL;
2617 				pfi_kkif_ref(newrule->kif);
2618 			} else
2619 				newrule->kif = NULL;
2620 
2621 			if (newrule->rtableid > 0 &&
2622 			    newrule->rtableid >= rt_numfibs)
2623 				error = EBUSY;
2624 
2625 #ifdef ALTQ
2626 			/* set queue IDs */
2627 			if (newrule->qname[0] != 0) {
2628 				if ((newrule->qid =
2629 				    pf_qname2qid(newrule->qname)) == 0)
2630 					error = EBUSY;
2631 				else if (newrule->pqname[0] != 0) {
2632 					if ((newrule->pqid =
2633 					    pf_qname2qid(newrule->pqname)) == 0)
2634 						error = EBUSY;
2635 				} else
2636 					newrule->pqid = newrule->qid;
2637 			}
2638 #endif /* ALTQ */
2639 			if (newrule->tagname[0])
2640 				if ((newrule->tag =
2641 				    pf_tagname2tag(newrule->tagname)) == 0)
2642 					error = EBUSY;
2643 			if (newrule->match_tagname[0])
2644 				if ((newrule->match_tag = pf_tagname2tag(
2645 				    newrule->match_tagname)) == 0)
2646 					error = EBUSY;
2647 			if (newrule->rt && !newrule->direction)
2648 				error = EINVAL;
2649 			if (!newrule->log)
2650 				newrule->logif = 0;
2651 			if (newrule->logif >= PFLOGIFS_MAX)
2652 				error = EINVAL;
2653 			if (pf_addr_setup(ruleset, &newrule->src.addr, newrule->af))
2654 				error = ENOMEM;
2655 			if (pf_addr_setup(ruleset, &newrule->dst.addr, newrule->af))
2656 				error = ENOMEM;
2657 			if (pf_kanchor_setup(newrule, ruleset, pcr->anchor_call))
2658 				error = EINVAL;
2659 			TAILQ_FOREACH(pa, &V_pf_pabuf, entries)
2660 				if (pa->addr.type == PF_ADDR_TABLE) {
2661 					pa->addr.p.tbl =
2662 					    pfr_attach_table(ruleset,
2663 					    pa->addr.v.tblname);
2664 					if (pa->addr.p.tbl == NULL)
2665 						error = ENOMEM;
2666 				}
2667 
2668 			newrule->overload_tbl = NULL;
2669 			if (newrule->overload_tblname[0]) {
2670 				if ((newrule->overload_tbl = pfr_attach_table(
2671 				    ruleset, newrule->overload_tblname)) ==
2672 				    NULL)
2673 					error = EINVAL;
2674 				else
2675 					newrule->overload_tbl->pfrkt_flags |=
2676 					    PFR_TFLAG_ACTIVE;
2677 			}
2678 
2679 			pf_mv_kpool(&V_pf_pabuf, &newrule->rpool.list);
2680 			if (((((newrule->action == PF_NAT) ||
2681 			    (newrule->action == PF_RDR) ||
2682 			    (newrule->action == PF_BINAT) ||
2683 			    (newrule->rt > PF_NOPFROUTE)) &&
2684 			    !newrule->anchor)) &&
2685 			    (TAILQ_FIRST(&newrule->rpool.list) == NULL))
2686 				error = EINVAL;
2687 
2688 			if (error) {
2689 				pf_free_rule(newrule);
2690 				PF_RULES_WUNLOCK();
2691 				break;
2692 			}
2693 
2694 			newrule->rpool.cur = TAILQ_FIRST(&newrule->rpool.list);
2695 		}
2696 		pf_empty_kpool(&V_pf_pabuf);
2697 
2698 		if (pcr->action == PF_CHANGE_ADD_HEAD)
2699 			oldrule = TAILQ_FIRST(
2700 			    ruleset->rules[rs_num].active.ptr);
2701 		else if (pcr->action == PF_CHANGE_ADD_TAIL)
2702 			oldrule = TAILQ_LAST(
2703 			    ruleset->rules[rs_num].active.ptr, pf_krulequeue);
2704 		else {
2705 			oldrule = TAILQ_FIRST(
2706 			    ruleset->rules[rs_num].active.ptr);
2707 			while ((oldrule != NULL) && (oldrule->nr != pcr->nr))
2708 				oldrule = TAILQ_NEXT(oldrule, entries);
2709 			if (oldrule == NULL) {
2710 				if (newrule != NULL)
2711 					pf_free_rule(newrule);
2712 				PF_RULES_WUNLOCK();
2713 				error = EINVAL;
2714 				break;
2715 			}
2716 		}
2717 
2718 		if (pcr->action == PF_CHANGE_REMOVE) {
2719 			pf_unlink_rule(ruleset->rules[rs_num].active.ptr,
2720 			    oldrule);
2721 			ruleset->rules[rs_num].active.rcount--;
2722 		} else {
2723 			if (oldrule == NULL)
2724 				TAILQ_INSERT_TAIL(
2725 				    ruleset->rules[rs_num].active.ptr,
2726 				    newrule, entries);
2727 			else if (pcr->action == PF_CHANGE_ADD_HEAD ||
2728 			    pcr->action == PF_CHANGE_ADD_BEFORE)
2729 				TAILQ_INSERT_BEFORE(oldrule, newrule, entries);
2730 			else
2731 				TAILQ_INSERT_AFTER(
2732 				    ruleset->rules[rs_num].active.ptr,
2733 				    oldrule, newrule, entries);
2734 			ruleset->rules[rs_num].active.rcount++;
2735 		}
2736 
2737 		nr = 0;
2738 		TAILQ_FOREACH(oldrule,
2739 		    ruleset->rules[rs_num].active.ptr, entries)
2740 			oldrule->nr = nr++;
2741 
2742 		ruleset->rules[rs_num].active.ticket++;
2743 
2744 		pf_calc_skip_steps(ruleset->rules[rs_num].active.ptr);
2745 		pf_remove_if_empty_kruleset(ruleset);
2746 
2747 		PF_RULES_WUNLOCK();
2748 		break;
2749 
2750 #undef ERROUT
2751 DIOCCHANGERULE_error:
2752 		PF_RULES_WUNLOCK();
2753 		pf_krule_free(newrule);
2754 		pf_kkif_free(kif);
2755 		break;
2756 	}
2757 
2758 	case DIOCCLRSTATES: {
2759 		struct pfioc_state_kill *psk = (struct pfioc_state_kill *)addr;
2760 		struct pf_kstate_kill	 kill;
2761 
2762 		error = pf_state_kill_to_kstate_kill(psk, &kill);
2763 		if (error)
2764 			break;
2765 
2766 		psk->psk_killed = pf_clear_states(&kill);
2767 		break;
2768 	}
2769 
2770 	case DIOCCLRSTATESNV: {
2771 		error = pf_clearstates_nv((struct pfioc_nv *)addr);
2772 		break;
2773 	}
2774 
2775 	case DIOCKILLSTATES: {
2776 		struct pfioc_state_kill	*psk = (struct pfioc_state_kill *)addr;
2777 		struct pf_kstate_kill	 kill;
2778 
2779 		error = pf_state_kill_to_kstate_kill(psk, &kill);
2780 		if (error)
2781 			break;
2782 
2783 		psk->psk_killed = 0;
2784 		pf_killstates(&kill, &psk->psk_killed);
2785 		break;
2786 	}
2787 
2788 	case DIOCKILLSTATESNV: {
2789 		error = pf_killstates_nv((struct pfioc_nv *)addr);
2790 		break;
2791 	}
2792 
2793 	case DIOCADDSTATE: {
2794 		struct pfioc_state	*ps = (struct pfioc_state *)addr;
2795 		struct pfsync_state	*sp = &ps->state;
2796 
2797 		if (sp->timeout >= PFTM_MAX) {
2798 			error = EINVAL;
2799 			break;
2800 		}
2801 		if (V_pfsync_state_import_ptr != NULL) {
2802 			PF_RULES_RLOCK();
2803 			error = V_pfsync_state_import_ptr(sp, PFSYNC_SI_IOCTL);
2804 			PF_RULES_RUNLOCK();
2805 		} else
2806 			error = EOPNOTSUPP;
2807 		break;
2808 	}
2809 
2810 	case DIOCGETSTATE: {
2811 		struct pfioc_state	*ps = (struct pfioc_state *)addr;
2812 		struct pf_kstate	*s;
2813 
2814 		s = pf_find_state_byid(ps->state.id, ps->state.creatorid);
2815 		if (s == NULL) {
2816 			error = ENOENT;
2817 			break;
2818 		}
2819 
2820 		pfsync_state_export(&ps->state, s);
2821 		PF_STATE_UNLOCK(s);
2822 		break;
2823 	}
2824 
2825 	case DIOCGETSTATENV: {
2826 		error = pf_getstate((struct pfioc_nv *)addr);
2827 		break;
2828 	}
2829 
2830 	case DIOCGETSTATES: {
2831 		struct pfioc_states	*ps = (struct pfioc_states *)addr;
2832 		struct pf_kstate	*s;
2833 		struct pfsync_state	*pstore, *p;
2834 		int i, nr;
2835 
2836 		if (ps->ps_len <= 0) {
2837 			nr = uma_zone_get_cur(V_pf_state_z);
2838 			ps->ps_len = sizeof(struct pfsync_state) * nr;
2839 			break;
2840 		}
2841 
2842 		p = pstore = malloc(ps->ps_len, M_TEMP, M_WAITOK | M_ZERO);
2843 		nr = 0;
2844 
2845 		for (i = 0; i <= pf_hashmask; i++) {
2846 			struct pf_idhash *ih = &V_pf_idhash[i];
2847 
2848 			PF_HASHROW_LOCK(ih);
2849 			LIST_FOREACH(s, &ih->states, entry) {
2850 				if (s->timeout == PFTM_UNLINKED)
2851 					continue;
2852 
2853 				if ((nr+1) * sizeof(*p) > ps->ps_len) {
2854 					PF_HASHROW_UNLOCK(ih);
2855 					goto DIOCGETSTATES_full;
2856 				}
2857 				pfsync_state_export(p, s);
2858 				p++;
2859 				nr++;
2860 			}
2861 			PF_HASHROW_UNLOCK(ih);
2862 		}
2863 DIOCGETSTATES_full:
2864 		error = copyout(pstore, ps->ps_states,
2865 		    sizeof(struct pfsync_state) * nr);
2866 		if (error) {
2867 			free(pstore, M_TEMP);
2868 			break;
2869 		}
2870 		ps->ps_len = sizeof(struct pfsync_state) * nr;
2871 		free(pstore, M_TEMP);
2872 
2873 		break;
2874 	}
2875 
2876 	case DIOCGETSTATESV2: {
2877 		struct pfioc_states_v2	*ps = (struct pfioc_states_v2 *)addr;
2878 		struct pf_kstate	*s;
2879 		struct pf_state_export	*pstore, *p;
2880 		int i, nr;
2881 		size_t slice_count = 16, count;
2882 		void *out;
2883 
2884 		if (ps->ps_req_version > PF_STATE_VERSION) {
2885 			error = ENOTSUP;
2886 			break;
2887 		}
2888 
2889 		if (ps->ps_len <= 0) {
2890 			nr = uma_zone_get_cur(V_pf_state_z);
2891 			ps->ps_len = sizeof(struct pf_state_export) * nr;
2892 			break;
2893 		}
2894 
2895 		out = ps->ps_states;
2896 		pstore = mallocarray(slice_count,
2897 		    sizeof(struct pf_state_export), M_TEMP, M_WAITOK | M_ZERO);
2898 		nr = 0;
2899 
2900 		for (i = 0; i <= pf_hashmask; i++) {
2901 			struct pf_idhash *ih = &V_pf_idhash[i];
2902 
2903 DIOCGETSTATESV2_retry:
2904 			p = pstore;
2905 
2906 			if (LIST_EMPTY(&ih->states))
2907 				continue;
2908 
2909 			PF_HASHROW_LOCK(ih);
2910 			count = 0;
2911 			LIST_FOREACH(s, &ih->states, entry) {
2912 				if (s->timeout == PFTM_UNLINKED)
2913 					continue;
2914 				count++;
2915 			}
2916 
2917 			if (count > slice_count) {
2918 				PF_HASHROW_UNLOCK(ih);
2919 				free(pstore, M_TEMP);
2920 				slice_count = count * 2;
2921 				pstore = mallocarray(slice_count,
2922 				    sizeof(struct pf_state_export), M_TEMP,
2923 				    M_WAITOK | M_ZERO);
2924 				goto DIOCGETSTATESV2_retry;
2925 			}
2926 
2927 			if ((nr+count) * sizeof(*p) > ps->ps_len) {
2928 				PF_HASHROW_UNLOCK(ih);
2929 				goto DIOCGETSTATESV2_full;
2930 			}
2931 
2932 			LIST_FOREACH(s, &ih->states, entry) {
2933 				if (s->timeout == PFTM_UNLINKED)
2934 					continue;
2935 
2936 				pf_state_export(p, s);
2937 				p++;
2938 				nr++;
2939 			}
2940 			PF_HASHROW_UNLOCK(ih);
2941 			error = copyout(pstore, out,
2942 			    sizeof(struct pf_state_export) * count);
2943 			if (error)
2944 				break;
2945 			out = ps->ps_states + nr;
2946 		}
2947 DIOCGETSTATESV2_full:
2948 		ps->ps_len = nr * sizeof(struct pf_state_export);
2949 		free(pstore, M_TEMP);
2950 
2951 		break;
2952 	}
2953 
2954 	case DIOCGETSTATESNV: {
2955 		error = pf_getstates((struct pfioc_nv *)addr);
2956 		break;
2957 	}
2958 
2959 	case DIOCGETSTATUS: {
2960 		struct pf_status *s = (struct pf_status *)addr;
2961 
2962 		PF_RULES_RLOCK();
2963 		s->running = V_pf_status.running;
2964 		s->since   = V_pf_status.since;
2965 		s->debug   = V_pf_status.debug;
2966 		s->hostid  = V_pf_status.hostid;
2967 		s->states  = V_pf_status.states;
2968 		s->src_nodes = V_pf_status.src_nodes;
2969 
2970 		for (int i = 0; i < PFRES_MAX; i++)
2971 			s->counters[i] =
2972 			    counter_u64_fetch(V_pf_status.counters[i]);
2973 		for (int i = 0; i < LCNT_MAX; i++)
2974 			s->lcounters[i] =
2975 			    counter_u64_fetch(V_pf_status.lcounters[i]);
2976 		for (int i = 0; i < FCNT_MAX; i++)
2977 			s->fcounters[i] =
2978 			    counter_u64_fetch(V_pf_status.fcounters[i]);
2979 		for (int i = 0; i < SCNT_MAX; i++)
2980 			s->scounters[i] =
2981 			    counter_u64_fetch(V_pf_status.scounters[i]);
2982 
2983 		bcopy(V_pf_status.ifname, s->ifname, IFNAMSIZ);
2984 		bcopy(V_pf_status.pf_chksum, s->pf_chksum,
2985 		    PF_MD5_DIGEST_LENGTH);
2986 
2987 		pfi_update_status(s->ifname, s);
2988 		PF_RULES_RUNLOCK();
2989 		break;
2990 	}
2991 
2992 	case DIOCSETSTATUSIF: {
2993 		struct pfioc_if	*pi = (struct pfioc_if *)addr;
2994 
2995 		if (pi->ifname[0] == 0) {
2996 			bzero(V_pf_status.ifname, IFNAMSIZ);
2997 			break;
2998 		}
2999 		PF_RULES_WLOCK();
3000 		strlcpy(V_pf_status.ifname, pi->ifname, IFNAMSIZ);
3001 		PF_RULES_WUNLOCK();
3002 		break;
3003 	}
3004 
3005 	case DIOCCLRSTATUS: {
3006 		PF_RULES_WLOCK();
3007 		for (int i = 0; i < PFRES_MAX; i++)
3008 			counter_u64_zero(V_pf_status.counters[i]);
3009 		for (int i = 0; i < FCNT_MAX; i++)
3010 			counter_u64_zero(V_pf_status.fcounters[i]);
3011 		for (int i = 0; i < SCNT_MAX; i++)
3012 			counter_u64_zero(V_pf_status.scounters[i]);
3013 		for (int i = 0; i < LCNT_MAX; i++)
3014 			counter_u64_zero(V_pf_status.lcounters[i]);
3015 		V_pf_status.since = time_second;
3016 		if (*V_pf_status.ifname)
3017 			pfi_update_status(V_pf_status.ifname, NULL);
3018 		PF_RULES_WUNLOCK();
3019 		break;
3020 	}
3021 
3022 	case DIOCNATLOOK: {
3023 		struct pfioc_natlook	*pnl = (struct pfioc_natlook *)addr;
3024 		struct pf_state_key	*sk;
3025 		struct pf_kstate	*state;
3026 		struct pf_state_key_cmp	 key;
3027 		int			 m = 0, direction = pnl->direction;
3028 		int			 sidx, didx;
3029 
3030 		/* NATLOOK src and dst are reversed, so reverse sidx/didx */
3031 		sidx = (direction == PF_IN) ? 1 : 0;
3032 		didx = (direction == PF_IN) ? 0 : 1;
3033 
3034 		if (!pnl->proto ||
3035 		    PF_AZERO(&pnl->saddr, pnl->af) ||
3036 		    PF_AZERO(&pnl->daddr, pnl->af) ||
3037 		    ((pnl->proto == IPPROTO_TCP ||
3038 		    pnl->proto == IPPROTO_UDP) &&
3039 		    (!pnl->dport || !pnl->sport)))
3040 			error = EINVAL;
3041 		else {
3042 			bzero(&key, sizeof(key));
3043 			key.af = pnl->af;
3044 			key.proto = pnl->proto;
3045 			PF_ACPY(&key.addr[sidx], &pnl->saddr, pnl->af);
3046 			key.port[sidx] = pnl->sport;
3047 			PF_ACPY(&key.addr[didx], &pnl->daddr, pnl->af);
3048 			key.port[didx] = pnl->dport;
3049 
3050 			state = pf_find_state_all(&key, direction, &m);
3051 
3052 			if (m > 1)
3053 				error = E2BIG;	/* more than one state */
3054 			else if (state != NULL) {
3055 				/* XXXGL: not locked read */
3056 				sk = state->key[sidx];
3057 				PF_ACPY(&pnl->rsaddr, &sk->addr[sidx], sk->af);
3058 				pnl->rsport = sk->port[sidx];
3059 				PF_ACPY(&pnl->rdaddr, &sk->addr[didx], sk->af);
3060 				pnl->rdport = sk->port[didx];
3061 			} else
3062 				error = ENOENT;
3063 		}
3064 		break;
3065 	}
3066 
3067 	case DIOCSETTIMEOUT: {
3068 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
3069 		int		 old;
3070 
3071 		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX ||
3072 		    pt->seconds < 0) {
3073 			error = EINVAL;
3074 			break;
3075 		}
3076 		PF_RULES_WLOCK();
3077 		old = V_pf_default_rule.timeout[pt->timeout];
3078 		if (pt->timeout == PFTM_INTERVAL && pt->seconds == 0)
3079 			pt->seconds = 1;
3080 		V_pf_default_rule.timeout[pt->timeout] = pt->seconds;
3081 		if (pt->timeout == PFTM_INTERVAL && pt->seconds < old)
3082 			wakeup(pf_purge_thread);
3083 		pt->seconds = old;
3084 		PF_RULES_WUNLOCK();
3085 		break;
3086 	}
3087 
3088 	case DIOCGETTIMEOUT: {
3089 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
3090 
3091 		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX) {
3092 			error = EINVAL;
3093 			break;
3094 		}
3095 		PF_RULES_RLOCK();
3096 		pt->seconds = V_pf_default_rule.timeout[pt->timeout];
3097 		PF_RULES_RUNLOCK();
3098 		break;
3099 	}
3100 
3101 	case DIOCGETLIMIT: {
3102 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
3103 
3104 		if (pl->index < 0 || pl->index >= PF_LIMIT_MAX) {
3105 			error = EINVAL;
3106 			break;
3107 		}
3108 		PF_RULES_RLOCK();
3109 		pl->limit = V_pf_limits[pl->index].limit;
3110 		PF_RULES_RUNLOCK();
3111 		break;
3112 	}
3113 
3114 	case DIOCSETLIMIT: {
3115 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
3116 		int			 old_limit;
3117 
3118 		PF_RULES_WLOCK();
3119 		if (pl->index < 0 || pl->index >= PF_LIMIT_MAX ||
3120 		    V_pf_limits[pl->index].zone == NULL) {
3121 			PF_RULES_WUNLOCK();
3122 			error = EINVAL;
3123 			break;
3124 		}
3125 		uma_zone_set_max(V_pf_limits[pl->index].zone, pl->limit);
3126 		old_limit = V_pf_limits[pl->index].limit;
3127 		V_pf_limits[pl->index].limit = pl->limit;
3128 		pl->limit = old_limit;
3129 		PF_RULES_WUNLOCK();
3130 		break;
3131 	}
3132 
3133 	case DIOCSETDEBUG: {
3134 		u_int32_t	*level = (u_int32_t *)addr;
3135 
3136 		PF_RULES_WLOCK();
3137 		V_pf_status.debug = *level;
3138 		PF_RULES_WUNLOCK();
3139 		break;
3140 	}
3141 
3142 	case DIOCCLRRULECTRS: {
3143 		/* obsoleted by DIOCGETRULE with action=PF_GET_CLR_CNTR */
3144 		struct pf_kruleset	*ruleset = &pf_main_ruleset;
3145 		struct pf_krule		*rule;
3146 
3147 		PF_RULES_WLOCK();
3148 		TAILQ_FOREACH(rule,
3149 		    ruleset->rules[PF_RULESET_FILTER].active.ptr, entries) {
3150 			counter_u64_zero(rule->evaluations);
3151 			for (int i = 0; i < 2; i++) {
3152 				counter_u64_zero(rule->packets[i]);
3153 				counter_u64_zero(rule->bytes[i]);
3154 			}
3155 		}
3156 		PF_RULES_WUNLOCK();
3157 		break;
3158 	}
3159 
3160 	case DIOCGIFSPEEDV0:
3161 	case DIOCGIFSPEEDV1: {
3162 		struct pf_ifspeed_v1	*psp = (struct pf_ifspeed_v1 *)addr;
3163 		struct pf_ifspeed_v1	ps;
3164 		struct ifnet		*ifp;
3165 
3166 		if (psp->ifname[0] != 0) {
3167 			/* Can we completely trust user-land? */
3168 			strlcpy(ps.ifname, psp->ifname, IFNAMSIZ);
3169 			ifp = ifunit(ps.ifname);
3170 			if (ifp != NULL) {
3171 				psp->baudrate32 =
3172 				    (u_int32_t)uqmin(ifp->if_baudrate, UINT_MAX);
3173 				if (cmd == DIOCGIFSPEEDV1)
3174 					psp->baudrate = ifp->if_baudrate;
3175 			} else
3176 				error = EINVAL;
3177 		} else
3178 			error = EINVAL;
3179 		break;
3180 	}
3181 
3182 #ifdef ALTQ
3183 	case DIOCSTARTALTQ: {
3184 		struct pf_altq		*altq;
3185 
3186 		PF_RULES_WLOCK();
3187 		/* enable all altq interfaces on active list */
3188 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries) {
3189 			if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
3190 				error = pf_enable_altq(altq);
3191 				if (error != 0)
3192 					break;
3193 			}
3194 		}
3195 		if (error == 0)
3196 			V_pf_altq_running = 1;
3197 		PF_RULES_WUNLOCK();
3198 		DPFPRINTF(PF_DEBUG_MISC, ("altq: started\n"));
3199 		break;
3200 	}
3201 
3202 	case DIOCSTOPALTQ: {
3203 		struct pf_altq		*altq;
3204 
3205 		PF_RULES_WLOCK();
3206 		/* disable all altq interfaces on active list */
3207 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries) {
3208 			if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
3209 				error = pf_disable_altq(altq);
3210 				if (error != 0)
3211 					break;
3212 			}
3213 		}
3214 		if (error == 0)
3215 			V_pf_altq_running = 0;
3216 		PF_RULES_WUNLOCK();
3217 		DPFPRINTF(PF_DEBUG_MISC, ("altq: stopped\n"));
3218 		break;
3219 	}
3220 
3221 	case DIOCADDALTQV0:
3222 	case DIOCADDALTQV1: {
3223 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
3224 		struct pf_altq		*altq, *a;
3225 		struct ifnet		*ifp;
3226 
3227 		altq = malloc(sizeof(*altq), M_PFALTQ, M_WAITOK | M_ZERO);
3228 		error = pf_import_kaltq(pa, altq, IOCPARM_LEN(cmd));
3229 		if (error)
3230 			break;
3231 		altq->local_flags = 0;
3232 
3233 		PF_RULES_WLOCK();
3234 		if (pa->ticket != V_ticket_altqs_inactive) {
3235 			PF_RULES_WUNLOCK();
3236 			free(altq, M_PFALTQ);
3237 			error = EBUSY;
3238 			break;
3239 		}
3240 
3241 		/*
3242 		 * if this is for a queue, find the discipline and
3243 		 * copy the necessary fields
3244 		 */
3245 		if (altq->qname[0] != 0) {
3246 			if ((altq->qid = pf_qname2qid(altq->qname)) == 0) {
3247 				PF_RULES_WUNLOCK();
3248 				error = EBUSY;
3249 				free(altq, M_PFALTQ);
3250 				break;
3251 			}
3252 			altq->altq_disc = NULL;
3253 			TAILQ_FOREACH(a, V_pf_altq_ifs_inactive, entries) {
3254 				if (strncmp(a->ifname, altq->ifname,
3255 				    IFNAMSIZ) == 0) {
3256 					altq->altq_disc = a->altq_disc;
3257 					break;
3258 				}
3259 			}
3260 		}
3261 
3262 		if ((ifp = ifunit(altq->ifname)) == NULL)
3263 			altq->local_flags |= PFALTQ_FLAG_IF_REMOVED;
3264 		else
3265 			error = altq_add(ifp, altq);
3266 
3267 		if (error) {
3268 			PF_RULES_WUNLOCK();
3269 			free(altq, M_PFALTQ);
3270 			break;
3271 		}
3272 
3273 		if (altq->qname[0] != 0)
3274 			TAILQ_INSERT_TAIL(V_pf_altqs_inactive, altq, entries);
3275 		else
3276 			TAILQ_INSERT_TAIL(V_pf_altq_ifs_inactive, altq, entries);
3277 		/* version error check done on import above */
3278 		pf_export_kaltq(altq, pa, IOCPARM_LEN(cmd));
3279 		PF_RULES_WUNLOCK();
3280 		break;
3281 	}
3282 
3283 	case DIOCGETALTQSV0:
3284 	case DIOCGETALTQSV1: {
3285 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
3286 		struct pf_altq		*altq;
3287 
3288 		PF_RULES_RLOCK();
3289 		pa->nr = 0;
3290 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries)
3291 			pa->nr++;
3292 		TAILQ_FOREACH(altq, V_pf_altqs_active, entries)
3293 			pa->nr++;
3294 		pa->ticket = V_ticket_altqs_active;
3295 		PF_RULES_RUNLOCK();
3296 		break;
3297 	}
3298 
3299 	case DIOCGETALTQV0:
3300 	case DIOCGETALTQV1: {
3301 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
3302 		struct pf_altq		*altq;
3303 
3304 		PF_RULES_RLOCK();
3305 		if (pa->ticket != V_ticket_altqs_active) {
3306 			PF_RULES_RUNLOCK();
3307 			error = EBUSY;
3308 			break;
3309 		}
3310 		altq = pf_altq_get_nth_active(pa->nr);
3311 		if (altq == NULL) {
3312 			PF_RULES_RUNLOCK();
3313 			error = EBUSY;
3314 			break;
3315 		}
3316 		pf_export_kaltq(altq, pa, IOCPARM_LEN(cmd));
3317 		PF_RULES_RUNLOCK();
3318 		break;
3319 	}
3320 
3321 	case DIOCCHANGEALTQV0:
3322 	case DIOCCHANGEALTQV1:
3323 		/* CHANGEALTQ not supported yet! */
3324 		error = ENODEV;
3325 		break;
3326 
3327 	case DIOCGETQSTATSV0:
3328 	case DIOCGETQSTATSV1: {
3329 		struct pfioc_qstats_v1	*pq = (struct pfioc_qstats_v1 *)addr;
3330 		struct pf_altq		*altq;
3331 		int			 nbytes;
3332 		u_int32_t		 version;
3333 
3334 		PF_RULES_RLOCK();
3335 		if (pq->ticket != V_ticket_altqs_active) {
3336 			PF_RULES_RUNLOCK();
3337 			error = EBUSY;
3338 			break;
3339 		}
3340 		nbytes = pq->nbytes;
3341 		altq = pf_altq_get_nth_active(pq->nr);
3342 		if (altq == NULL) {
3343 			PF_RULES_RUNLOCK();
3344 			error = EBUSY;
3345 			break;
3346 		}
3347 
3348 		if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) != 0) {
3349 			PF_RULES_RUNLOCK();
3350 			error = ENXIO;
3351 			break;
3352 		}
3353 		PF_RULES_RUNLOCK();
3354 		if (cmd == DIOCGETQSTATSV0)
3355 			version = 0;  /* DIOCGETQSTATSV0 means stats struct v0 */
3356 		else
3357 			version = pq->version;
3358 		error = altq_getqstats(altq, pq->buf, &nbytes, version);
3359 		if (error == 0) {
3360 			pq->scheduler = altq->scheduler;
3361 			pq->nbytes = nbytes;
3362 		}
3363 		break;
3364 	}
3365 #endif /* ALTQ */
3366 
3367 	case DIOCBEGINADDRS: {
3368 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
3369 
3370 		PF_RULES_WLOCK();
3371 		pf_empty_kpool(&V_pf_pabuf);
3372 		pp->ticket = ++V_ticket_pabuf;
3373 		PF_RULES_WUNLOCK();
3374 		break;
3375 	}
3376 
3377 	case DIOCADDADDR: {
3378 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
3379 		struct pf_kpooladdr	*pa;
3380 		struct pfi_kkif		*kif = NULL;
3381 
3382 #ifndef INET
3383 		if (pp->af == AF_INET) {
3384 			error = EAFNOSUPPORT;
3385 			break;
3386 		}
3387 #endif /* INET */
3388 #ifndef INET6
3389 		if (pp->af == AF_INET6) {
3390 			error = EAFNOSUPPORT;
3391 			break;
3392 		}
3393 #endif /* INET6 */
3394 		if (pp->addr.addr.type != PF_ADDR_ADDRMASK &&
3395 		    pp->addr.addr.type != PF_ADDR_DYNIFTL &&
3396 		    pp->addr.addr.type != PF_ADDR_TABLE) {
3397 			error = EINVAL;
3398 			break;
3399 		}
3400 		if (pp->addr.addr.p.dyn != NULL) {
3401 			error = EINVAL;
3402 			break;
3403 		}
3404 		pa = malloc(sizeof(*pa), M_PFRULE, M_WAITOK);
3405 		pf_pooladdr_to_kpooladdr(&pp->addr, pa);
3406 		if (pa->ifname[0])
3407 			kif = pf_kkif_create(M_WAITOK);
3408 		PF_RULES_WLOCK();
3409 		if (pp->ticket != V_ticket_pabuf) {
3410 			PF_RULES_WUNLOCK();
3411 			if (pa->ifname[0])
3412 				pf_kkif_free(kif);
3413 			free(pa, M_PFRULE);
3414 			error = EBUSY;
3415 			break;
3416 		}
3417 		if (pa->ifname[0]) {
3418 			pa->kif = pfi_kkif_attach(kif, pa->ifname);
3419 			kif = NULL;
3420 			pfi_kkif_ref(pa->kif);
3421 		} else
3422 			pa->kif = NULL;
3423 		if (pa->addr.type == PF_ADDR_DYNIFTL && ((error =
3424 		    pfi_dynaddr_setup(&pa->addr, pp->af)) != 0)) {
3425 			if (pa->ifname[0])
3426 				pfi_kkif_unref(pa->kif);
3427 			PF_RULES_WUNLOCK();
3428 			free(pa, M_PFRULE);
3429 			break;
3430 		}
3431 		TAILQ_INSERT_TAIL(&V_pf_pabuf, pa, entries);
3432 		PF_RULES_WUNLOCK();
3433 		break;
3434 	}
3435 
3436 	case DIOCGETADDRS: {
3437 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
3438 		struct pf_kpool		*pool;
3439 		struct pf_kpooladdr	*pa;
3440 
3441 		PF_RULES_RLOCK();
3442 		pp->nr = 0;
3443 		pool = pf_get_kpool(pp->anchor, pp->ticket, pp->r_action,
3444 		    pp->r_num, 0, 1, 0);
3445 		if (pool == NULL) {
3446 			PF_RULES_RUNLOCK();
3447 			error = EBUSY;
3448 			break;
3449 		}
3450 		TAILQ_FOREACH(pa, &pool->list, entries)
3451 			pp->nr++;
3452 		PF_RULES_RUNLOCK();
3453 		break;
3454 	}
3455 
3456 	case DIOCGETADDR: {
3457 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
3458 		struct pf_kpool		*pool;
3459 		struct pf_kpooladdr	*pa;
3460 		u_int32_t		 nr = 0;
3461 
3462 		PF_RULES_RLOCK();
3463 		pool = pf_get_kpool(pp->anchor, pp->ticket, pp->r_action,
3464 		    pp->r_num, 0, 1, 1);
3465 		if (pool == NULL) {
3466 			PF_RULES_RUNLOCK();
3467 			error = EBUSY;
3468 			break;
3469 		}
3470 		pa = TAILQ_FIRST(&pool->list);
3471 		while ((pa != NULL) && (nr < pp->nr)) {
3472 			pa = TAILQ_NEXT(pa, entries);
3473 			nr++;
3474 		}
3475 		if (pa == NULL) {
3476 			PF_RULES_RUNLOCK();
3477 			error = EBUSY;
3478 			break;
3479 		}
3480 		pf_kpooladdr_to_pooladdr(pa, &pp->addr);
3481 		pf_addr_copyout(&pp->addr.addr);
3482 		PF_RULES_RUNLOCK();
3483 		break;
3484 	}
3485 
3486 	case DIOCCHANGEADDR: {
3487 		struct pfioc_pooladdr	*pca = (struct pfioc_pooladdr *)addr;
3488 		struct pf_kpool		*pool;
3489 		struct pf_kpooladdr	*oldpa = NULL, *newpa = NULL;
3490 		struct pf_kruleset	*ruleset;
3491 		struct pfi_kkif		*kif = NULL;
3492 
3493 		if (pca->action < PF_CHANGE_ADD_HEAD ||
3494 		    pca->action > PF_CHANGE_REMOVE) {
3495 			error = EINVAL;
3496 			break;
3497 		}
3498 		if (pca->addr.addr.type != PF_ADDR_ADDRMASK &&
3499 		    pca->addr.addr.type != PF_ADDR_DYNIFTL &&
3500 		    pca->addr.addr.type != PF_ADDR_TABLE) {
3501 			error = EINVAL;
3502 			break;
3503 		}
3504 		if (pca->addr.addr.p.dyn != NULL) {
3505 			error = EINVAL;
3506 			break;
3507 		}
3508 
3509 		if (pca->action != PF_CHANGE_REMOVE) {
3510 #ifndef INET
3511 			if (pca->af == AF_INET) {
3512 				error = EAFNOSUPPORT;
3513 				break;
3514 			}
3515 #endif /* INET */
3516 #ifndef INET6
3517 			if (pca->af == AF_INET6) {
3518 				error = EAFNOSUPPORT;
3519 				break;
3520 			}
3521 #endif /* INET6 */
3522 			newpa = malloc(sizeof(*newpa), M_PFRULE, M_WAITOK);
3523 			bcopy(&pca->addr, newpa, sizeof(struct pf_pooladdr));
3524 			if (newpa->ifname[0])
3525 				kif = pf_kkif_create(M_WAITOK);
3526 			newpa->kif = NULL;
3527 		}
3528 #define	ERROUT(x)	ERROUT_IOCTL(DIOCCHANGEADDR_error, x)
3529 		PF_RULES_WLOCK();
3530 		ruleset = pf_find_kruleset(pca->anchor);
3531 		if (ruleset == NULL)
3532 			ERROUT(EBUSY);
3533 
3534 		pool = pf_get_kpool(pca->anchor, pca->ticket, pca->r_action,
3535 		    pca->r_num, pca->r_last, 1, 1);
3536 		if (pool == NULL)
3537 			ERROUT(EBUSY);
3538 
3539 		if (pca->action != PF_CHANGE_REMOVE) {
3540 			if (newpa->ifname[0]) {
3541 				newpa->kif = pfi_kkif_attach(kif, newpa->ifname);
3542 				pfi_kkif_ref(newpa->kif);
3543 				kif = NULL;
3544 			}
3545 
3546 			switch (newpa->addr.type) {
3547 			case PF_ADDR_DYNIFTL:
3548 				error = pfi_dynaddr_setup(&newpa->addr,
3549 				    pca->af);
3550 				break;
3551 			case PF_ADDR_TABLE:
3552 				newpa->addr.p.tbl = pfr_attach_table(ruleset,
3553 				    newpa->addr.v.tblname);
3554 				if (newpa->addr.p.tbl == NULL)
3555 					error = ENOMEM;
3556 				break;
3557 			}
3558 			if (error)
3559 				goto DIOCCHANGEADDR_error;
3560 		}
3561 
3562 		switch (pca->action) {
3563 		case PF_CHANGE_ADD_HEAD:
3564 			oldpa = TAILQ_FIRST(&pool->list);
3565 			break;
3566 		case PF_CHANGE_ADD_TAIL:
3567 			oldpa = TAILQ_LAST(&pool->list, pf_kpalist);
3568 			break;
3569 		default:
3570 			oldpa = TAILQ_FIRST(&pool->list);
3571 			for (int i = 0; oldpa && i < pca->nr; i++)
3572 				oldpa = TAILQ_NEXT(oldpa, entries);
3573 
3574 			if (oldpa == NULL)
3575 				ERROUT(EINVAL);
3576 		}
3577 
3578 		if (pca->action == PF_CHANGE_REMOVE) {
3579 			TAILQ_REMOVE(&pool->list, oldpa, entries);
3580 			switch (oldpa->addr.type) {
3581 			case PF_ADDR_DYNIFTL:
3582 				pfi_dynaddr_remove(oldpa->addr.p.dyn);
3583 				break;
3584 			case PF_ADDR_TABLE:
3585 				pfr_detach_table(oldpa->addr.p.tbl);
3586 				break;
3587 			}
3588 			if (oldpa->kif)
3589 				pfi_kkif_unref(oldpa->kif);
3590 			free(oldpa, M_PFRULE);
3591 		} else {
3592 			if (oldpa == NULL)
3593 				TAILQ_INSERT_TAIL(&pool->list, newpa, entries);
3594 			else if (pca->action == PF_CHANGE_ADD_HEAD ||
3595 			    pca->action == PF_CHANGE_ADD_BEFORE)
3596 				TAILQ_INSERT_BEFORE(oldpa, newpa, entries);
3597 			else
3598 				TAILQ_INSERT_AFTER(&pool->list, oldpa,
3599 				    newpa, entries);
3600 		}
3601 
3602 		pool->cur = TAILQ_FIRST(&pool->list);
3603 		PF_ACPY(&pool->counter, &pool->cur->addr.v.a.addr, pca->af);
3604 		PF_RULES_WUNLOCK();
3605 		break;
3606 
3607 #undef ERROUT
3608 DIOCCHANGEADDR_error:
3609 		if (newpa != NULL) {
3610 			if (newpa->kif)
3611 				pfi_kkif_unref(newpa->kif);
3612 			free(newpa, M_PFRULE);
3613 		}
3614 		PF_RULES_WUNLOCK();
3615 		pf_kkif_free(kif);
3616 		break;
3617 	}
3618 
3619 	case DIOCGETRULESETS: {
3620 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
3621 		struct pf_kruleset	*ruleset;
3622 		struct pf_kanchor	*anchor;
3623 
3624 		PF_RULES_RLOCK();
3625 		pr->path[sizeof(pr->path) - 1] = 0;
3626 		if ((ruleset = pf_find_kruleset(pr->path)) == NULL) {
3627 			PF_RULES_RUNLOCK();
3628 			error = ENOENT;
3629 			break;
3630 		}
3631 		pr->nr = 0;
3632 		if (ruleset->anchor == NULL) {
3633 			/* XXX kludge for pf_main_ruleset */
3634 			RB_FOREACH(anchor, pf_kanchor_global, &V_pf_anchors)
3635 				if (anchor->parent == NULL)
3636 					pr->nr++;
3637 		} else {
3638 			RB_FOREACH(anchor, pf_kanchor_node,
3639 			    &ruleset->anchor->children)
3640 				pr->nr++;
3641 		}
3642 		PF_RULES_RUNLOCK();
3643 		break;
3644 	}
3645 
3646 	case DIOCGETRULESET: {
3647 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
3648 		struct pf_kruleset	*ruleset;
3649 		struct pf_kanchor	*anchor;
3650 		u_int32_t		 nr = 0;
3651 
3652 		PF_RULES_RLOCK();
3653 		pr->path[sizeof(pr->path) - 1] = 0;
3654 		if ((ruleset = pf_find_kruleset(pr->path)) == NULL) {
3655 			PF_RULES_RUNLOCK();
3656 			error = ENOENT;
3657 			break;
3658 		}
3659 		pr->name[0] = 0;
3660 		if (ruleset->anchor == NULL) {
3661 			/* XXX kludge for pf_main_ruleset */
3662 			RB_FOREACH(anchor, pf_kanchor_global, &V_pf_anchors)
3663 				if (anchor->parent == NULL && nr++ == pr->nr) {
3664 					strlcpy(pr->name, anchor->name,
3665 					    sizeof(pr->name));
3666 					break;
3667 				}
3668 		} else {
3669 			RB_FOREACH(anchor, pf_kanchor_node,
3670 			    &ruleset->anchor->children)
3671 				if (nr++ == pr->nr) {
3672 					strlcpy(pr->name, anchor->name,
3673 					    sizeof(pr->name));
3674 					break;
3675 				}
3676 		}
3677 		if (!pr->name[0])
3678 			error = EBUSY;
3679 		PF_RULES_RUNLOCK();
3680 		break;
3681 	}
3682 
3683 	case DIOCRCLRTABLES: {
3684 		struct pfioc_table *io = (struct pfioc_table *)addr;
3685 
3686 		if (io->pfrio_esize != 0) {
3687 			error = ENODEV;
3688 			break;
3689 		}
3690 		PF_RULES_WLOCK();
3691 		error = pfr_clr_tables(&io->pfrio_table, &io->pfrio_ndel,
3692 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
3693 		PF_RULES_WUNLOCK();
3694 		break;
3695 	}
3696 
3697 	case DIOCRADDTABLES: {
3698 		struct pfioc_table *io = (struct pfioc_table *)addr;
3699 		struct pfr_table *pfrts;
3700 		size_t totlen;
3701 
3702 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3703 			error = ENODEV;
3704 			break;
3705 		}
3706 
3707 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
3708 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
3709 			error = ENOMEM;
3710 			break;
3711 		}
3712 
3713 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3714 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3715 		    M_TEMP, M_WAITOK);
3716 		error = copyin(io->pfrio_buffer, pfrts, totlen);
3717 		if (error) {
3718 			free(pfrts, M_TEMP);
3719 			break;
3720 		}
3721 		PF_RULES_WLOCK();
3722 		error = pfr_add_tables(pfrts, io->pfrio_size,
3723 		    &io->pfrio_nadd, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3724 		PF_RULES_WUNLOCK();
3725 		free(pfrts, M_TEMP);
3726 		break;
3727 	}
3728 
3729 	case DIOCRDELTABLES: {
3730 		struct pfioc_table *io = (struct pfioc_table *)addr;
3731 		struct pfr_table *pfrts;
3732 		size_t totlen;
3733 
3734 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3735 			error = ENODEV;
3736 			break;
3737 		}
3738 
3739 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
3740 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
3741 			error = ENOMEM;
3742 			break;
3743 		}
3744 
3745 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3746 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3747 		    M_TEMP, M_WAITOK);
3748 		error = copyin(io->pfrio_buffer, pfrts, totlen);
3749 		if (error) {
3750 			free(pfrts, M_TEMP);
3751 			break;
3752 		}
3753 		PF_RULES_WLOCK();
3754 		error = pfr_del_tables(pfrts, io->pfrio_size,
3755 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3756 		PF_RULES_WUNLOCK();
3757 		free(pfrts, M_TEMP);
3758 		break;
3759 	}
3760 
3761 	case DIOCRGETTABLES: {
3762 		struct pfioc_table *io = (struct pfioc_table *)addr;
3763 		struct pfr_table *pfrts;
3764 		size_t totlen;
3765 		int n;
3766 
3767 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3768 			error = ENODEV;
3769 			break;
3770 		}
3771 		PF_RULES_RLOCK();
3772 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
3773 		if (n < 0) {
3774 			PF_RULES_RUNLOCK();
3775 			error = EINVAL;
3776 			break;
3777 		}
3778 		io->pfrio_size = min(io->pfrio_size, n);
3779 
3780 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3781 
3782 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3783 		    M_TEMP, M_NOWAIT);
3784 		if (pfrts == NULL) {
3785 			error = ENOMEM;
3786 			PF_RULES_RUNLOCK();
3787 			break;
3788 		}
3789 		error = pfr_get_tables(&io->pfrio_table, pfrts,
3790 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3791 		PF_RULES_RUNLOCK();
3792 		if (error == 0)
3793 			error = copyout(pfrts, io->pfrio_buffer, totlen);
3794 		free(pfrts, M_TEMP);
3795 		break;
3796 	}
3797 
3798 	case DIOCRGETTSTATS: {
3799 		struct pfioc_table *io = (struct pfioc_table *)addr;
3800 		struct pfr_tstats *pfrtstats;
3801 		size_t totlen;
3802 		int n;
3803 
3804 		if (io->pfrio_esize != sizeof(struct pfr_tstats)) {
3805 			error = ENODEV;
3806 			break;
3807 		}
3808 		PF_TABLE_STATS_LOCK();
3809 		PF_RULES_RLOCK();
3810 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
3811 		if (n < 0) {
3812 			PF_RULES_RUNLOCK();
3813 			PF_TABLE_STATS_UNLOCK();
3814 			error = EINVAL;
3815 			break;
3816 		}
3817 		io->pfrio_size = min(io->pfrio_size, n);
3818 
3819 		totlen = io->pfrio_size * sizeof(struct pfr_tstats);
3820 		pfrtstats = mallocarray(io->pfrio_size,
3821 		    sizeof(struct pfr_tstats), M_TEMP, M_NOWAIT);
3822 		if (pfrtstats == NULL) {
3823 			error = ENOMEM;
3824 			PF_RULES_RUNLOCK();
3825 			PF_TABLE_STATS_UNLOCK();
3826 			break;
3827 		}
3828 		error = pfr_get_tstats(&io->pfrio_table, pfrtstats,
3829 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3830 		PF_RULES_RUNLOCK();
3831 		PF_TABLE_STATS_UNLOCK();
3832 		if (error == 0)
3833 			error = copyout(pfrtstats, io->pfrio_buffer, totlen);
3834 		free(pfrtstats, M_TEMP);
3835 		break;
3836 	}
3837 
3838 	case DIOCRCLRTSTATS: {
3839 		struct pfioc_table *io = (struct pfioc_table *)addr;
3840 		struct pfr_table *pfrts;
3841 		size_t totlen;
3842 
3843 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3844 			error = ENODEV;
3845 			break;
3846 		}
3847 
3848 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
3849 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
3850 			/* We used to count tables and use the minimum required
3851 			 * size, so we didn't fail on overly large requests.
3852 			 * Keep doing so. */
3853 			io->pfrio_size = pf_ioctl_maxcount;
3854 			break;
3855 		}
3856 
3857 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3858 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3859 		    M_TEMP, M_WAITOK);
3860 		error = copyin(io->pfrio_buffer, pfrts, totlen);
3861 		if (error) {
3862 			free(pfrts, M_TEMP);
3863 			break;
3864 		}
3865 
3866 		PF_TABLE_STATS_LOCK();
3867 		PF_RULES_RLOCK();
3868 		error = pfr_clr_tstats(pfrts, io->pfrio_size,
3869 		    &io->pfrio_nzero, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3870 		PF_RULES_RUNLOCK();
3871 		PF_TABLE_STATS_UNLOCK();
3872 		free(pfrts, M_TEMP);
3873 		break;
3874 	}
3875 
3876 	case DIOCRSETTFLAGS: {
3877 		struct pfioc_table *io = (struct pfioc_table *)addr;
3878 		struct pfr_table *pfrts;
3879 		size_t totlen;
3880 		int n;
3881 
3882 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3883 			error = ENODEV;
3884 			break;
3885 		}
3886 
3887 		PF_RULES_RLOCK();
3888 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
3889 		if (n < 0) {
3890 			PF_RULES_RUNLOCK();
3891 			error = EINVAL;
3892 			break;
3893 		}
3894 
3895 		io->pfrio_size = min(io->pfrio_size, n);
3896 		PF_RULES_RUNLOCK();
3897 
3898 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3899 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3900 		    M_TEMP, M_WAITOK);
3901 		error = copyin(io->pfrio_buffer, pfrts, totlen);
3902 		if (error) {
3903 			free(pfrts, M_TEMP);
3904 			break;
3905 		}
3906 		PF_RULES_WLOCK();
3907 		error = pfr_set_tflags(pfrts, io->pfrio_size,
3908 		    io->pfrio_setflag, io->pfrio_clrflag, &io->pfrio_nchange,
3909 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3910 		PF_RULES_WUNLOCK();
3911 		free(pfrts, M_TEMP);
3912 		break;
3913 	}
3914 
3915 	case DIOCRCLRADDRS: {
3916 		struct pfioc_table *io = (struct pfioc_table *)addr;
3917 
3918 		if (io->pfrio_esize != 0) {
3919 			error = ENODEV;
3920 			break;
3921 		}
3922 		PF_RULES_WLOCK();
3923 		error = pfr_clr_addrs(&io->pfrio_table, &io->pfrio_ndel,
3924 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
3925 		PF_RULES_WUNLOCK();
3926 		break;
3927 	}
3928 
3929 	case DIOCRADDADDRS: {
3930 		struct pfioc_table *io = (struct pfioc_table *)addr;
3931 		struct pfr_addr *pfras;
3932 		size_t totlen;
3933 
3934 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
3935 			error = ENODEV;
3936 			break;
3937 		}
3938 		if (io->pfrio_size < 0 ||
3939 		    io->pfrio_size > pf_ioctl_maxcount ||
3940 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
3941 			error = EINVAL;
3942 			break;
3943 		}
3944 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
3945 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
3946 		    M_TEMP, M_WAITOK);
3947 		error = copyin(io->pfrio_buffer, pfras, totlen);
3948 		if (error) {
3949 			free(pfras, M_TEMP);
3950 			break;
3951 		}
3952 		PF_RULES_WLOCK();
3953 		error = pfr_add_addrs(&io->pfrio_table, pfras,
3954 		    io->pfrio_size, &io->pfrio_nadd, io->pfrio_flags |
3955 		    PFR_FLAG_USERIOCTL);
3956 		PF_RULES_WUNLOCK();
3957 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
3958 			error = copyout(pfras, io->pfrio_buffer, totlen);
3959 		free(pfras, M_TEMP);
3960 		break;
3961 	}
3962 
3963 	case DIOCRDELADDRS: {
3964 		struct pfioc_table *io = (struct pfioc_table *)addr;
3965 		struct pfr_addr *pfras;
3966 		size_t totlen;
3967 
3968 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
3969 			error = ENODEV;
3970 			break;
3971 		}
3972 		if (io->pfrio_size < 0 ||
3973 		    io->pfrio_size > pf_ioctl_maxcount ||
3974 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
3975 			error = EINVAL;
3976 			break;
3977 		}
3978 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
3979 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
3980 		    M_TEMP, M_WAITOK);
3981 		error = copyin(io->pfrio_buffer, pfras, totlen);
3982 		if (error) {
3983 			free(pfras, M_TEMP);
3984 			break;
3985 		}
3986 		PF_RULES_WLOCK();
3987 		error = pfr_del_addrs(&io->pfrio_table, pfras,
3988 		    io->pfrio_size, &io->pfrio_ndel, io->pfrio_flags |
3989 		    PFR_FLAG_USERIOCTL);
3990 		PF_RULES_WUNLOCK();
3991 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
3992 			error = copyout(pfras, io->pfrio_buffer, totlen);
3993 		free(pfras, M_TEMP);
3994 		break;
3995 	}
3996 
3997 	case DIOCRSETADDRS: {
3998 		struct pfioc_table *io = (struct pfioc_table *)addr;
3999 		struct pfr_addr *pfras;
4000 		size_t totlen, count;
4001 
4002 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4003 			error = ENODEV;
4004 			break;
4005 		}
4006 		if (io->pfrio_size < 0 || io->pfrio_size2 < 0) {
4007 			error = EINVAL;
4008 			break;
4009 		}
4010 		count = max(io->pfrio_size, io->pfrio_size2);
4011 		if (count > pf_ioctl_maxcount ||
4012 		    WOULD_OVERFLOW(count, sizeof(struct pfr_addr))) {
4013 			error = EINVAL;
4014 			break;
4015 		}
4016 		totlen = count * sizeof(struct pfr_addr);
4017 		pfras = mallocarray(count, sizeof(struct pfr_addr), M_TEMP,
4018 		    M_WAITOK);
4019 		error = copyin(io->pfrio_buffer, pfras, totlen);
4020 		if (error) {
4021 			free(pfras, M_TEMP);
4022 			break;
4023 		}
4024 		PF_RULES_WLOCK();
4025 		error = pfr_set_addrs(&io->pfrio_table, pfras,
4026 		    io->pfrio_size, &io->pfrio_size2, &io->pfrio_nadd,
4027 		    &io->pfrio_ndel, &io->pfrio_nchange, io->pfrio_flags |
4028 		    PFR_FLAG_USERIOCTL, 0);
4029 		PF_RULES_WUNLOCK();
4030 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4031 			error = copyout(pfras, io->pfrio_buffer, totlen);
4032 		free(pfras, M_TEMP);
4033 		break;
4034 	}
4035 
4036 	case DIOCRGETADDRS: {
4037 		struct pfioc_table *io = (struct pfioc_table *)addr;
4038 		struct pfr_addr *pfras;
4039 		size_t totlen;
4040 
4041 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4042 			error = ENODEV;
4043 			break;
4044 		}
4045 		if (io->pfrio_size < 0 ||
4046 		    io->pfrio_size > pf_ioctl_maxcount ||
4047 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4048 			error = EINVAL;
4049 			break;
4050 		}
4051 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4052 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4053 		    M_TEMP, M_WAITOK);
4054 		PF_RULES_RLOCK();
4055 		error = pfr_get_addrs(&io->pfrio_table, pfras,
4056 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4057 		PF_RULES_RUNLOCK();
4058 		if (error == 0)
4059 			error = copyout(pfras, io->pfrio_buffer, totlen);
4060 		free(pfras, M_TEMP);
4061 		break;
4062 	}
4063 
4064 	case DIOCRGETASTATS: {
4065 		struct pfioc_table *io = (struct pfioc_table *)addr;
4066 		struct pfr_astats *pfrastats;
4067 		size_t totlen;
4068 
4069 		if (io->pfrio_esize != sizeof(struct pfr_astats)) {
4070 			error = ENODEV;
4071 			break;
4072 		}
4073 		if (io->pfrio_size < 0 ||
4074 		    io->pfrio_size > pf_ioctl_maxcount ||
4075 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_astats))) {
4076 			error = EINVAL;
4077 			break;
4078 		}
4079 		totlen = io->pfrio_size * sizeof(struct pfr_astats);
4080 		pfrastats = mallocarray(io->pfrio_size,
4081 		    sizeof(struct pfr_astats), M_TEMP, M_WAITOK);
4082 		PF_RULES_RLOCK();
4083 		error = pfr_get_astats(&io->pfrio_table, pfrastats,
4084 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4085 		PF_RULES_RUNLOCK();
4086 		if (error == 0)
4087 			error = copyout(pfrastats, io->pfrio_buffer, totlen);
4088 		free(pfrastats, M_TEMP);
4089 		break;
4090 	}
4091 
4092 	case DIOCRCLRASTATS: {
4093 		struct pfioc_table *io = (struct pfioc_table *)addr;
4094 		struct pfr_addr *pfras;
4095 		size_t totlen;
4096 
4097 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4098 			error = ENODEV;
4099 			break;
4100 		}
4101 		if (io->pfrio_size < 0 ||
4102 		    io->pfrio_size > pf_ioctl_maxcount ||
4103 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4104 			error = EINVAL;
4105 			break;
4106 		}
4107 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4108 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4109 		    M_TEMP, M_WAITOK);
4110 		error = copyin(io->pfrio_buffer, pfras, totlen);
4111 		if (error) {
4112 			free(pfras, M_TEMP);
4113 			break;
4114 		}
4115 		PF_RULES_WLOCK();
4116 		error = pfr_clr_astats(&io->pfrio_table, pfras,
4117 		    io->pfrio_size, &io->pfrio_nzero, io->pfrio_flags |
4118 		    PFR_FLAG_USERIOCTL);
4119 		PF_RULES_WUNLOCK();
4120 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4121 			error = copyout(pfras, io->pfrio_buffer, totlen);
4122 		free(pfras, M_TEMP);
4123 		break;
4124 	}
4125 
4126 	case DIOCRTSTADDRS: {
4127 		struct pfioc_table *io = (struct pfioc_table *)addr;
4128 		struct pfr_addr *pfras;
4129 		size_t totlen;
4130 
4131 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4132 			error = ENODEV;
4133 			break;
4134 		}
4135 		if (io->pfrio_size < 0 ||
4136 		    io->pfrio_size > pf_ioctl_maxcount ||
4137 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4138 			error = EINVAL;
4139 			break;
4140 		}
4141 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4142 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4143 		    M_TEMP, M_WAITOK);
4144 		error = copyin(io->pfrio_buffer, pfras, totlen);
4145 		if (error) {
4146 			free(pfras, M_TEMP);
4147 			break;
4148 		}
4149 		PF_RULES_RLOCK();
4150 		error = pfr_tst_addrs(&io->pfrio_table, pfras,
4151 		    io->pfrio_size, &io->pfrio_nmatch, io->pfrio_flags |
4152 		    PFR_FLAG_USERIOCTL);
4153 		PF_RULES_RUNLOCK();
4154 		if (error == 0)
4155 			error = copyout(pfras, io->pfrio_buffer, totlen);
4156 		free(pfras, M_TEMP);
4157 		break;
4158 	}
4159 
4160 	case DIOCRINADEFINE: {
4161 		struct pfioc_table *io = (struct pfioc_table *)addr;
4162 		struct pfr_addr *pfras;
4163 		size_t totlen;
4164 
4165 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4166 			error = ENODEV;
4167 			break;
4168 		}
4169 		if (io->pfrio_size < 0 ||
4170 		    io->pfrio_size > pf_ioctl_maxcount ||
4171 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4172 			error = EINVAL;
4173 			break;
4174 		}
4175 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4176 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4177 		    M_TEMP, M_WAITOK);
4178 		error = copyin(io->pfrio_buffer, pfras, totlen);
4179 		if (error) {
4180 			free(pfras, M_TEMP);
4181 			break;
4182 		}
4183 		PF_RULES_WLOCK();
4184 		error = pfr_ina_define(&io->pfrio_table, pfras,
4185 		    io->pfrio_size, &io->pfrio_nadd, &io->pfrio_naddr,
4186 		    io->pfrio_ticket, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4187 		PF_RULES_WUNLOCK();
4188 		free(pfras, M_TEMP);
4189 		break;
4190 	}
4191 
4192 	case DIOCOSFPADD: {
4193 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
4194 		PF_RULES_WLOCK();
4195 		error = pf_osfp_add(io);
4196 		PF_RULES_WUNLOCK();
4197 		break;
4198 	}
4199 
4200 	case DIOCOSFPGET: {
4201 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
4202 		PF_RULES_RLOCK();
4203 		error = pf_osfp_get(io);
4204 		PF_RULES_RUNLOCK();
4205 		break;
4206 	}
4207 
4208 	case DIOCXBEGIN: {
4209 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
4210 		struct pfioc_trans_e	*ioes, *ioe;
4211 		size_t			 totlen;
4212 		int			 i;
4213 
4214 		if (io->esize != sizeof(*ioe)) {
4215 			error = ENODEV;
4216 			break;
4217 		}
4218 		if (io->size < 0 ||
4219 		    io->size > pf_ioctl_maxcount ||
4220 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
4221 			error = EINVAL;
4222 			break;
4223 		}
4224 		totlen = sizeof(struct pfioc_trans_e) * io->size;
4225 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
4226 		    M_TEMP, M_WAITOK);
4227 		error = copyin(io->array, ioes, totlen);
4228 		if (error) {
4229 			free(ioes, M_TEMP);
4230 			break;
4231 		}
4232 		PF_RULES_WLOCK();
4233 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
4234 			switch (ioe->rs_num) {
4235 #ifdef ALTQ
4236 			case PF_RULESET_ALTQ:
4237 				if (ioe->anchor[0]) {
4238 					PF_RULES_WUNLOCK();
4239 					free(ioes, M_TEMP);
4240 					error = EINVAL;
4241 					goto fail;
4242 				}
4243 				if ((error = pf_begin_altq(&ioe->ticket))) {
4244 					PF_RULES_WUNLOCK();
4245 					free(ioes, M_TEMP);
4246 					goto fail;
4247 				}
4248 				break;
4249 #endif /* ALTQ */
4250 			case PF_RULESET_TABLE:
4251 			    {
4252 				struct pfr_table table;
4253 
4254 				bzero(&table, sizeof(table));
4255 				strlcpy(table.pfrt_anchor, ioe->anchor,
4256 				    sizeof(table.pfrt_anchor));
4257 				if ((error = pfr_ina_begin(&table,
4258 				    &ioe->ticket, NULL, 0))) {
4259 					PF_RULES_WUNLOCK();
4260 					free(ioes, M_TEMP);
4261 					goto fail;
4262 				}
4263 				break;
4264 			    }
4265 			default:
4266 				if ((error = pf_begin_rules(&ioe->ticket,
4267 				    ioe->rs_num, ioe->anchor))) {
4268 					PF_RULES_WUNLOCK();
4269 					free(ioes, M_TEMP);
4270 					goto fail;
4271 				}
4272 				break;
4273 			}
4274 		}
4275 		PF_RULES_WUNLOCK();
4276 		error = copyout(ioes, io->array, totlen);
4277 		free(ioes, M_TEMP);
4278 		break;
4279 	}
4280 
4281 	case DIOCXROLLBACK: {
4282 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
4283 		struct pfioc_trans_e	*ioe, *ioes;
4284 		size_t			 totlen;
4285 		int			 i;
4286 
4287 		if (io->esize != sizeof(*ioe)) {
4288 			error = ENODEV;
4289 			break;
4290 		}
4291 		if (io->size < 0 ||
4292 		    io->size > pf_ioctl_maxcount ||
4293 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
4294 			error = EINVAL;
4295 			break;
4296 		}
4297 		totlen = sizeof(struct pfioc_trans_e) * io->size;
4298 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
4299 		    M_TEMP, M_WAITOK);
4300 		error = copyin(io->array, ioes, totlen);
4301 		if (error) {
4302 			free(ioes, M_TEMP);
4303 			break;
4304 		}
4305 		PF_RULES_WLOCK();
4306 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
4307 			switch (ioe->rs_num) {
4308 #ifdef ALTQ
4309 			case PF_RULESET_ALTQ:
4310 				if (ioe->anchor[0]) {
4311 					PF_RULES_WUNLOCK();
4312 					free(ioes, M_TEMP);
4313 					error = EINVAL;
4314 					goto fail;
4315 				}
4316 				if ((error = pf_rollback_altq(ioe->ticket))) {
4317 					PF_RULES_WUNLOCK();
4318 					free(ioes, M_TEMP);
4319 					goto fail; /* really bad */
4320 				}
4321 				break;
4322 #endif /* ALTQ */
4323 			case PF_RULESET_TABLE:
4324 			    {
4325 				struct pfr_table table;
4326 
4327 				bzero(&table, sizeof(table));
4328 				strlcpy(table.pfrt_anchor, ioe->anchor,
4329 				    sizeof(table.pfrt_anchor));
4330 				if ((error = pfr_ina_rollback(&table,
4331 				    ioe->ticket, NULL, 0))) {
4332 					PF_RULES_WUNLOCK();
4333 					free(ioes, M_TEMP);
4334 					goto fail; /* really bad */
4335 				}
4336 				break;
4337 			    }
4338 			default:
4339 				if ((error = pf_rollback_rules(ioe->ticket,
4340 				    ioe->rs_num, ioe->anchor))) {
4341 					PF_RULES_WUNLOCK();
4342 					free(ioes, M_TEMP);
4343 					goto fail; /* really bad */
4344 				}
4345 				break;
4346 			}
4347 		}
4348 		PF_RULES_WUNLOCK();
4349 		free(ioes, M_TEMP);
4350 		break;
4351 	}
4352 
4353 	case DIOCXCOMMIT: {
4354 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
4355 		struct pfioc_trans_e	*ioe, *ioes;
4356 		struct pf_kruleset	*rs;
4357 		size_t			 totlen;
4358 		int			 i;
4359 
4360 		if (io->esize != sizeof(*ioe)) {
4361 			error = ENODEV;
4362 			break;
4363 		}
4364 
4365 		if (io->size < 0 ||
4366 		    io->size > pf_ioctl_maxcount ||
4367 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
4368 			error = EINVAL;
4369 			break;
4370 		}
4371 
4372 		totlen = sizeof(struct pfioc_trans_e) * io->size;
4373 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
4374 		    M_TEMP, M_WAITOK);
4375 		error = copyin(io->array, ioes, totlen);
4376 		if (error) {
4377 			free(ioes, M_TEMP);
4378 			break;
4379 		}
4380 		PF_RULES_WLOCK();
4381 		/* First makes sure everything will succeed. */
4382 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
4383 			switch (ioe->rs_num) {
4384 #ifdef ALTQ
4385 			case PF_RULESET_ALTQ:
4386 				if (ioe->anchor[0]) {
4387 					PF_RULES_WUNLOCK();
4388 					free(ioes, M_TEMP);
4389 					error = EINVAL;
4390 					goto fail;
4391 				}
4392 				if (!V_altqs_inactive_open || ioe->ticket !=
4393 				    V_ticket_altqs_inactive) {
4394 					PF_RULES_WUNLOCK();
4395 					free(ioes, M_TEMP);
4396 					error = EBUSY;
4397 					goto fail;
4398 				}
4399 				break;
4400 #endif /* ALTQ */
4401 			case PF_RULESET_TABLE:
4402 				rs = pf_find_kruleset(ioe->anchor);
4403 				if (rs == NULL || !rs->topen || ioe->ticket !=
4404 				    rs->tticket) {
4405 					PF_RULES_WUNLOCK();
4406 					free(ioes, M_TEMP);
4407 					error = EBUSY;
4408 					goto fail;
4409 				}
4410 				break;
4411 			default:
4412 				if (ioe->rs_num < 0 || ioe->rs_num >=
4413 				    PF_RULESET_MAX) {
4414 					PF_RULES_WUNLOCK();
4415 					free(ioes, M_TEMP);
4416 					error = EINVAL;
4417 					goto fail;
4418 				}
4419 				rs = pf_find_kruleset(ioe->anchor);
4420 				if (rs == NULL ||
4421 				    !rs->rules[ioe->rs_num].inactive.open ||
4422 				    rs->rules[ioe->rs_num].inactive.ticket !=
4423 				    ioe->ticket) {
4424 					PF_RULES_WUNLOCK();
4425 					free(ioes, M_TEMP);
4426 					error = EBUSY;
4427 					goto fail;
4428 				}
4429 				break;
4430 			}
4431 		}
4432 		/* Now do the commit - no errors should happen here. */
4433 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
4434 			switch (ioe->rs_num) {
4435 #ifdef ALTQ
4436 			case PF_RULESET_ALTQ:
4437 				if ((error = pf_commit_altq(ioe->ticket))) {
4438 					PF_RULES_WUNLOCK();
4439 					free(ioes, M_TEMP);
4440 					goto fail; /* really bad */
4441 				}
4442 				break;
4443 #endif /* ALTQ */
4444 			case PF_RULESET_TABLE:
4445 			    {
4446 				struct pfr_table table;
4447 
4448 				bzero(&table, sizeof(table));
4449 				strlcpy(table.pfrt_anchor, ioe->anchor,
4450 				    sizeof(table.pfrt_anchor));
4451 				if ((error = pfr_ina_commit(&table,
4452 				    ioe->ticket, NULL, NULL, 0))) {
4453 					PF_RULES_WUNLOCK();
4454 					free(ioes, M_TEMP);
4455 					goto fail; /* really bad */
4456 				}
4457 				break;
4458 			    }
4459 			default:
4460 				if ((error = pf_commit_rules(ioe->ticket,
4461 				    ioe->rs_num, ioe->anchor))) {
4462 					PF_RULES_WUNLOCK();
4463 					free(ioes, M_TEMP);
4464 					goto fail; /* really bad */
4465 				}
4466 				break;
4467 			}
4468 		}
4469 		PF_RULES_WUNLOCK();
4470 		free(ioes, M_TEMP);
4471 		break;
4472 	}
4473 
4474 	case DIOCGETSRCNODES: {
4475 		struct pfioc_src_nodes	*psn = (struct pfioc_src_nodes *)addr;
4476 		struct pf_srchash	*sh;
4477 		struct pf_ksrc_node	*n;
4478 		struct pf_src_node	*p, *pstore;
4479 		uint32_t		 i, nr = 0;
4480 
4481 		for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
4482 				i++, sh++) {
4483 			PF_HASHROW_LOCK(sh);
4484 			LIST_FOREACH(n, &sh->nodes, entry)
4485 				nr++;
4486 			PF_HASHROW_UNLOCK(sh);
4487 		}
4488 
4489 		psn->psn_len = min(psn->psn_len,
4490 		    sizeof(struct pf_src_node) * nr);
4491 
4492 		if (psn->psn_len == 0) {
4493 			psn->psn_len = sizeof(struct pf_src_node) * nr;
4494 			break;
4495 		}
4496 
4497 		nr = 0;
4498 
4499 		p = pstore = malloc(psn->psn_len, M_TEMP, M_WAITOK | M_ZERO);
4500 		for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
4501 		    i++, sh++) {
4502 		    PF_HASHROW_LOCK(sh);
4503 		    LIST_FOREACH(n, &sh->nodes, entry) {
4504 
4505 			if ((nr + 1) * sizeof(*p) > (unsigned)psn->psn_len)
4506 				break;
4507 
4508 			pf_src_node_copy(n, p);
4509 
4510 			p++;
4511 			nr++;
4512 		    }
4513 		    PF_HASHROW_UNLOCK(sh);
4514 		}
4515 		error = copyout(pstore, psn->psn_src_nodes,
4516 		    sizeof(struct pf_src_node) * nr);
4517 		if (error) {
4518 			free(pstore, M_TEMP);
4519 			break;
4520 		}
4521 		psn->psn_len = sizeof(struct pf_src_node) * nr;
4522 		free(pstore, M_TEMP);
4523 		break;
4524 	}
4525 
4526 	case DIOCCLRSRCNODES: {
4527 		pf_clear_srcnodes(NULL);
4528 		pf_purge_expired_src_nodes();
4529 		break;
4530 	}
4531 
4532 	case DIOCKILLSRCNODES:
4533 		pf_kill_srcnodes((struct pfioc_src_node_kill *)addr);
4534 		break;
4535 
4536 	case DIOCKEEPCOUNTERS:
4537 		error = pf_keepcounters((struct pfioc_nv *)addr);
4538 		break;
4539 
4540 	case DIOCSETHOSTID: {
4541 		u_int32_t	*hostid = (u_int32_t *)addr;
4542 
4543 		PF_RULES_WLOCK();
4544 		if (*hostid == 0)
4545 			V_pf_status.hostid = arc4random();
4546 		else
4547 			V_pf_status.hostid = *hostid;
4548 		PF_RULES_WUNLOCK();
4549 		break;
4550 	}
4551 
4552 	case DIOCOSFPFLUSH:
4553 		PF_RULES_WLOCK();
4554 		pf_osfp_flush();
4555 		PF_RULES_WUNLOCK();
4556 		break;
4557 
4558 	case DIOCIGETIFACES: {
4559 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
4560 		struct pfi_kif *ifstore;
4561 		size_t bufsiz;
4562 
4563 		if (io->pfiio_esize != sizeof(struct pfi_kif)) {
4564 			error = ENODEV;
4565 			break;
4566 		}
4567 
4568 		if (io->pfiio_size < 0 ||
4569 		    io->pfiio_size > pf_ioctl_maxcount ||
4570 		    WOULD_OVERFLOW(io->pfiio_size, sizeof(struct pfi_kif))) {
4571 			error = EINVAL;
4572 			break;
4573 		}
4574 
4575 		bufsiz = io->pfiio_size * sizeof(struct pfi_kif);
4576 		ifstore = mallocarray(io->pfiio_size, sizeof(struct pfi_kif),
4577 		    M_TEMP, M_WAITOK);
4578 
4579 		PF_RULES_RLOCK();
4580 		pfi_get_ifaces(io->pfiio_name, ifstore, &io->pfiio_size);
4581 		PF_RULES_RUNLOCK();
4582 		error = copyout(ifstore, io->pfiio_buffer, bufsiz);
4583 		free(ifstore, M_TEMP);
4584 		break;
4585 	}
4586 
4587 	case DIOCSETIFFLAG: {
4588 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
4589 
4590 		PF_RULES_WLOCK();
4591 		error = pfi_set_flags(io->pfiio_name, io->pfiio_flags);
4592 		PF_RULES_WUNLOCK();
4593 		break;
4594 	}
4595 
4596 	case DIOCCLRIFFLAG: {
4597 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
4598 
4599 		PF_RULES_WLOCK();
4600 		error = pfi_clear_flags(io->pfiio_name, io->pfiio_flags);
4601 		PF_RULES_WUNLOCK();
4602 		break;
4603 	}
4604 
4605 	default:
4606 		error = ENODEV;
4607 		break;
4608 	}
4609 fail:
4610 	if (sx_xlocked(&pf_ioctl_lock))
4611 		sx_xunlock(&pf_ioctl_lock);
4612 	CURVNET_RESTORE();
4613 
4614 #undef ERROUT_IOCTL
4615 
4616 	return (error);
4617 }
4618 
4619 void
4620 pfsync_state_export(struct pfsync_state *sp, struct pf_kstate *st)
4621 {
4622 	bzero(sp, sizeof(struct pfsync_state));
4623 
4624 	/* copy from state key */
4625 	sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
4626 	sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
4627 	sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
4628 	sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
4629 	sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
4630 	sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
4631 	sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
4632 	sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
4633 	sp->proto = st->key[PF_SK_WIRE]->proto;
4634 	sp->af = st->key[PF_SK_WIRE]->af;
4635 
4636 	/* copy from state */
4637 	strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
4638 	bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));
4639 	sp->creation = htonl(time_uptime - st->creation);
4640 	sp->expire = pf_state_expires(st);
4641 	if (sp->expire <= time_uptime)
4642 		sp->expire = htonl(0);
4643 	else
4644 		sp->expire = htonl(sp->expire - time_uptime);
4645 
4646 	sp->direction = st->direction;
4647 	sp->log = st->log;
4648 	sp->timeout = st->timeout;
4649 	sp->state_flags = st->state_flags;
4650 	if (st->src_node)
4651 		sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
4652 	if (st->nat_src_node)
4653 		sp->sync_flags |= PFSYNC_FLAG_NATSRCNODE;
4654 
4655 	sp->id = st->id;
4656 	sp->creatorid = st->creatorid;
4657 	pf_state_peer_hton(&st->src, &sp->src);
4658 	pf_state_peer_hton(&st->dst, &sp->dst);
4659 
4660 	if (st->rule.ptr == NULL)
4661 		sp->rule = htonl(-1);
4662 	else
4663 		sp->rule = htonl(st->rule.ptr->nr);
4664 	if (st->anchor.ptr == NULL)
4665 		sp->anchor = htonl(-1);
4666 	else
4667 		sp->anchor = htonl(st->anchor.ptr->nr);
4668 	if (st->nat_rule.ptr == NULL)
4669 		sp->nat_rule = htonl(-1);
4670 	else
4671 		sp->nat_rule = htonl(st->nat_rule.ptr->nr);
4672 
4673 	pf_state_counter_hton(st->packets[0], sp->packets[0]);
4674 	pf_state_counter_hton(st->packets[1], sp->packets[1]);
4675 	pf_state_counter_hton(st->bytes[0], sp->bytes[0]);
4676 	pf_state_counter_hton(st->bytes[1], sp->bytes[1]);
4677 }
4678 
4679 void
4680 pf_state_export(struct pf_state_export *sp, struct pf_kstate *st)
4681 {
4682 	bzero(sp, sizeof(*sp));
4683 
4684 	sp->version = PF_STATE_VERSION;
4685 
4686 	/* copy from state key */
4687 	sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
4688 	sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
4689 	sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
4690 	sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
4691 	sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
4692 	sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
4693 	sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
4694 	sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
4695 	sp->proto = st->key[PF_SK_WIRE]->proto;
4696 	sp->af = st->key[PF_SK_WIRE]->af;
4697 
4698 	/* copy from state */
4699 	strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
4700 	strlcpy(sp->orig_ifname, st->orig_kif->pfik_name,
4701 	    sizeof(sp->orig_ifname));
4702 	bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));
4703 	sp->creation = htonl(time_uptime - st->creation);
4704 	sp->expire = pf_state_expires(st);
4705 	if (sp->expire <= time_uptime)
4706 		sp->expire = htonl(0);
4707 	else
4708 		sp->expire = htonl(sp->expire - time_uptime);
4709 
4710 	sp->direction = st->direction;
4711 	sp->log = st->log;
4712 	sp->timeout = st->timeout;
4713 	sp->state_flags = st->state_flags;
4714 	if (st->src_node)
4715 		sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
4716 	if (st->nat_src_node)
4717 		sp->sync_flags |= PFSYNC_FLAG_NATSRCNODE;
4718 
4719 	sp->id = st->id;
4720 	sp->creatorid = st->creatorid;
4721 	pf_state_peer_hton(&st->src, &sp->src);
4722 	pf_state_peer_hton(&st->dst, &sp->dst);
4723 
4724 	if (st->rule.ptr == NULL)
4725 		sp->rule = htonl(-1);
4726 	else
4727 		sp->rule = htonl(st->rule.ptr->nr);
4728 	if (st->anchor.ptr == NULL)
4729 		sp->anchor = htonl(-1);
4730 	else
4731 		sp->anchor = htonl(st->anchor.ptr->nr);
4732 	if (st->nat_rule.ptr == NULL)
4733 		sp->nat_rule = htonl(-1);
4734 	else
4735 		sp->nat_rule = htonl(st->nat_rule.ptr->nr);
4736 
4737 	sp->packets[0] = st->packets[0];
4738 	sp->packets[1] = st->packets[1];
4739 	sp->bytes[0] = st->bytes[0];
4740 	sp->bytes[1] = st->bytes[1];
4741 }
4742 
4743 static void
4744 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
4745 {
4746 	struct pfr_ktable *kt;
4747 
4748 	KASSERT(aw->type == PF_ADDR_TABLE, ("%s: type %u", __func__, aw->type));
4749 
4750 	kt = aw->p.tbl;
4751 	if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
4752 		kt = kt->pfrkt_root;
4753 	aw->p.tbl = NULL;
4754 	aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
4755 		kt->pfrkt_cnt : -1;
4756 }
4757 
4758 /*
4759  * XXX - Check for version missmatch!!!
4760  */
4761 static void
4762 pf_clear_all_states(void)
4763 {
4764 	struct pf_kstate	*s;
4765 	u_int i;
4766 
4767 	for (i = 0; i <= pf_hashmask; i++) {
4768 		struct pf_idhash *ih = &V_pf_idhash[i];
4769 relock:
4770 		PF_HASHROW_LOCK(ih);
4771 		LIST_FOREACH(s, &ih->states, entry) {
4772 			s->timeout = PFTM_PURGE;
4773 			/* Don't send out individual delete messages. */
4774 			s->state_flags |= PFSTATE_NOSYNC;
4775 			pf_unlink_state(s, PF_ENTER_LOCKED);
4776 			goto relock;
4777 		}
4778 		PF_HASHROW_UNLOCK(ih);
4779 	}
4780 }
4781 
4782 static int
4783 pf_clear_tables(void)
4784 {
4785 	struct pfioc_table io;
4786 	int error;
4787 
4788 	bzero(&io, sizeof(io));
4789 
4790 	error = pfr_clr_tables(&io.pfrio_table, &io.pfrio_ndel,
4791 	    io.pfrio_flags);
4792 
4793 	return (error);
4794 }
4795 
4796 static void
4797 pf_clear_srcnodes(struct pf_ksrc_node *n)
4798 {
4799 	struct pf_kstate *s;
4800 	int i;
4801 
4802 	for (i = 0; i <= pf_hashmask; i++) {
4803 		struct pf_idhash *ih = &V_pf_idhash[i];
4804 
4805 		PF_HASHROW_LOCK(ih);
4806 		LIST_FOREACH(s, &ih->states, entry) {
4807 			if (n == NULL || n == s->src_node)
4808 				s->src_node = NULL;
4809 			if (n == NULL || n == s->nat_src_node)
4810 				s->nat_src_node = NULL;
4811 		}
4812 		PF_HASHROW_UNLOCK(ih);
4813 	}
4814 
4815 	if (n == NULL) {
4816 		struct pf_srchash *sh;
4817 
4818 		for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
4819 		    i++, sh++) {
4820 			PF_HASHROW_LOCK(sh);
4821 			LIST_FOREACH(n, &sh->nodes, entry) {
4822 				n->expire = 1;
4823 				n->states = 0;
4824 			}
4825 			PF_HASHROW_UNLOCK(sh);
4826 		}
4827 	} else {
4828 		/* XXX: hash slot should already be locked here. */
4829 		n->expire = 1;
4830 		n->states = 0;
4831 	}
4832 }
4833 
4834 static void
4835 pf_kill_srcnodes(struct pfioc_src_node_kill *psnk)
4836 {
4837 	struct pf_ksrc_node_list	 kill;
4838 
4839 	LIST_INIT(&kill);
4840 	for (int i = 0; i <= pf_srchashmask; i++) {
4841 		struct pf_srchash *sh = &V_pf_srchash[i];
4842 		struct pf_ksrc_node *sn, *tmp;
4843 
4844 		PF_HASHROW_LOCK(sh);
4845 		LIST_FOREACH_SAFE(sn, &sh->nodes, entry, tmp)
4846 			if (PF_MATCHA(psnk->psnk_src.neg,
4847 			      &psnk->psnk_src.addr.v.a.addr,
4848 			      &psnk->psnk_src.addr.v.a.mask,
4849 			      &sn->addr, sn->af) &&
4850 			    PF_MATCHA(psnk->psnk_dst.neg,
4851 			      &psnk->psnk_dst.addr.v.a.addr,
4852 			      &psnk->psnk_dst.addr.v.a.mask,
4853 			      &sn->raddr, sn->af)) {
4854 				pf_unlink_src_node(sn);
4855 				LIST_INSERT_HEAD(&kill, sn, entry);
4856 				sn->expire = 1;
4857 			}
4858 		PF_HASHROW_UNLOCK(sh);
4859 	}
4860 
4861 	for (int i = 0; i <= pf_hashmask; i++) {
4862 		struct pf_idhash *ih = &V_pf_idhash[i];
4863 		struct pf_kstate *s;
4864 
4865 		PF_HASHROW_LOCK(ih);
4866 		LIST_FOREACH(s, &ih->states, entry) {
4867 			if (s->src_node && s->src_node->expire == 1)
4868 				s->src_node = NULL;
4869 			if (s->nat_src_node && s->nat_src_node->expire == 1)
4870 				s->nat_src_node = NULL;
4871 		}
4872 		PF_HASHROW_UNLOCK(ih);
4873 	}
4874 
4875 	psnk->psnk_killed = pf_free_src_nodes(&kill);
4876 }
4877 
4878 static int
4879 pf_keepcounters(struct pfioc_nv *nv)
4880 {
4881 	nvlist_t	*nvl = NULL;
4882 	void		*nvlpacked = NULL;
4883 	int		 error = 0;
4884 
4885 #define	ERROUT(x)	ERROUT_FUNCTION(on_error, x)
4886 
4887 	if (nv->len > pf_ioctl_maxcount)
4888 		ERROUT(ENOMEM);
4889 
4890 	nvlpacked = malloc(nv->len, M_TEMP, M_WAITOK);
4891 	if (nvlpacked == NULL)
4892 		ERROUT(ENOMEM);
4893 
4894 	error = copyin(nv->data, nvlpacked, nv->len);
4895 	if (error)
4896 		ERROUT(error);
4897 
4898 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
4899 	if (nvl == NULL)
4900 		ERROUT(EBADMSG);
4901 
4902 	if (! nvlist_exists_bool(nvl, "keep_counters"))
4903 		ERROUT(EBADMSG);
4904 
4905 	V_pf_status.keep_counters = nvlist_get_bool(nvl, "keep_counters");
4906 
4907 on_error:
4908 	nvlist_destroy(nvl);
4909 	free(nvlpacked, M_TEMP);
4910 	return (error);
4911 }
4912 
4913 static unsigned int
4914 pf_clear_states(const struct pf_kstate_kill *kill)
4915 {
4916 	struct pf_state_key_cmp	 match_key;
4917 	struct pf_kstate	*s;
4918 	struct pfi_kkif	*kif;
4919 	int		 idx;
4920 	unsigned int	 killed = 0, dir;
4921 
4922 	for (unsigned int i = 0; i <= pf_hashmask; i++) {
4923 		struct pf_idhash *ih = &V_pf_idhash[i];
4924 
4925 relock_DIOCCLRSTATES:
4926 		PF_HASHROW_LOCK(ih);
4927 		LIST_FOREACH(s, &ih->states, entry) {
4928 			/* For floating states look at the original kif. */
4929 			kif = s->kif == V_pfi_all ? s->orig_kif : s->kif;
4930 
4931 			if (kill->psk_ifname[0] &&
4932 			    strcmp(kill->psk_ifname,
4933 			    kif->pfik_name))
4934 				continue;
4935 
4936 			if (kill->psk_kill_match) {
4937 				bzero(&match_key, sizeof(match_key));
4938 
4939 				if (s->direction == PF_OUT) {
4940 					dir = PF_IN;
4941 					idx = PF_SK_STACK;
4942 				} else {
4943 					dir = PF_OUT;
4944 					idx = PF_SK_WIRE;
4945 				}
4946 
4947 				match_key.af = s->key[idx]->af;
4948 				match_key.proto = s->key[idx]->proto;
4949 				PF_ACPY(&match_key.addr[0],
4950 				    &s->key[idx]->addr[1], match_key.af);
4951 				match_key.port[0] = s->key[idx]->port[1];
4952 				PF_ACPY(&match_key.addr[1],
4953 				    &s->key[idx]->addr[0], match_key.af);
4954 				match_key.port[1] = s->key[idx]->port[0];
4955 			}
4956 
4957 			/*
4958 			 * Don't send out individual
4959 			 * delete messages.
4960 			 */
4961 			s->state_flags |= PFSTATE_NOSYNC;
4962 			pf_unlink_state(s, PF_ENTER_LOCKED);
4963 			killed++;
4964 
4965 			if (kill->psk_kill_match)
4966 				killed += pf_kill_matching_state(&match_key,
4967 				    dir);
4968 
4969 			goto relock_DIOCCLRSTATES;
4970 		}
4971 		PF_HASHROW_UNLOCK(ih);
4972 	}
4973 
4974 	if (V_pfsync_clear_states_ptr != NULL)
4975 		V_pfsync_clear_states_ptr(V_pf_status.hostid, kill->psk_ifname);
4976 
4977 	return (killed);
4978 }
4979 
4980 static void
4981 pf_killstates(struct pf_kstate_kill *kill, unsigned int *killed)
4982 {
4983 	struct pf_kstate	*s;
4984 
4985 	if (kill->psk_pfcmp.id) {
4986 		if (kill->psk_pfcmp.creatorid == 0)
4987 			kill->psk_pfcmp.creatorid = V_pf_status.hostid;
4988 		if ((s = pf_find_state_byid(kill->psk_pfcmp.id,
4989 		    kill->psk_pfcmp.creatorid))) {
4990 			pf_unlink_state(s, PF_ENTER_LOCKED);
4991 			*killed = 1;
4992 		}
4993 		return;
4994 	}
4995 
4996 	for (unsigned int i = 0; i <= pf_hashmask; i++)
4997 		*killed += pf_killstates_row(kill, &V_pf_idhash[i]);
4998 
4999 	return;
5000 }
5001 
5002 static int
5003 pf_killstates_nv(struct pfioc_nv *nv)
5004 {
5005 	struct pf_kstate_kill	 kill;
5006 	nvlist_t		*nvl = NULL;
5007 	void			*nvlpacked = NULL;
5008 	int			 error = 0;
5009 	unsigned int		 killed = 0;
5010 
5011 #define ERROUT(x)	ERROUT_FUNCTION(on_error, x)
5012 
5013 	if (nv->len > pf_ioctl_maxcount)
5014 		ERROUT(ENOMEM);
5015 
5016 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
5017 	if (nvlpacked == NULL)
5018 		ERROUT(ENOMEM);
5019 
5020 	error = copyin(nv->data, nvlpacked, nv->len);
5021 	if (error)
5022 		ERROUT(error);
5023 
5024 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
5025 	if (nvl == NULL)
5026 		ERROUT(EBADMSG);
5027 
5028 	error = pf_nvstate_kill_to_kstate_kill(nvl, &kill);
5029 	if (error)
5030 		ERROUT(error);
5031 
5032 	pf_killstates(&kill, &killed);
5033 
5034 	free(nvlpacked, M_NVLIST);
5035 	nvlpacked = NULL;
5036 	nvlist_destroy(nvl);
5037 	nvl = nvlist_create(0);
5038 	if (nvl == NULL)
5039 		ERROUT(ENOMEM);
5040 
5041 	nvlist_add_number(nvl, "killed", killed);
5042 
5043 	nvlpacked = nvlist_pack(nvl, &nv->len);
5044 	if (nvlpacked == NULL)
5045 		ERROUT(ENOMEM);
5046 
5047 	if (nv->size == 0)
5048 		ERROUT(0);
5049 	else if (nv->size < nv->len)
5050 		ERROUT(ENOSPC);
5051 
5052 	error = copyout(nvlpacked, nv->data, nv->len);
5053 
5054 on_error:
5055 	nvlist_destroy(nvl);
5056 	free(nvlpacked, M_NVLIST);
5057 	return (error);
5058 }
5059 
5060 static int
5061 pf_clearstates_nv(struct pfioc_nv *nv)
5062 {
5063 	struct pf_kstate_kill	 kill;
5064 	nvlist_t		*nvl = NULL;
5065 	void			*nvlpacked = NULL;
5066 	int			 error = 0;
5067 	unsigned int		 killed;
5068 
5069 #define ERROUT(x)	ERROUT_FUNCTION(on_error, x)
5070 
5071 	if (nv->len > pf_ioctl_maxcount)
5072 		ERROUT(ENOMEM);
5073 
5074 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
5075 	if (nvlpacked == NULL)
5076 		ERROUT(ENOMEM);
5077 
5078 	error = copyin(nv->data, nvlpacked, nv->len);
5079 	if (error)
5080 		ERROUT(error);
5081 
5082 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
5083 	if (nvl == NULL)
5084 		ERROUT(EBADMSG);
5085 
5086 	error = pf_nvstate_kill_to_kstate_kill(nvl, &kill);
5087 	if (error)
5088 		ERROUT(error);
5089 
5090 	killed = pf_clear_states(&kill);
5091 
5092 	free(nvlpacked, M_NVLIST);
5093 	nvlpacked = NULL;
5094 	nvlist_destroy(nvl);
5095 	nvl = nvlist_create(0);
5096 	if (nvl == NULL)
5097 		ERROUT(ENOMEM);
5098 
5099 	nvlist_add_number(nvl, "killed", killed);
5100 
5101 	nvlpacked = nvlist_pack(nvl, &nv->len);
5102 	if (nvlpacked == NULL)
5103 		ERROUT(ENOMEM);
5104 
5105 	if (nv->size == 0)
5106 		ERROUT(0);
5107 	else if (nv->size < nv->len)
5108 		ERROUT(ENOSPC);
5109 
5110 	error = copyout(nvlpacked, nv->data, nv->len);
5111 
5112 #undef ERROUT
5113 on_error:
5114 	nvlist_destroy(nvl);
5115 	free(nvlpacked, M_NVLIST);
5116 	return (error);
5117 }
5118 
5119 static int
5120 pf_getstate(struct pfioc_nv *nv)
5121 {
5122 	nvlist_t		*nvl = NULL, *nvls;
5123 	void			*nvlpacked = NULL;
5124 	struct pf_kstate	*s = NULL;
5125 	int			 error = 0;
5126 	uint64_t		 id, creatorid;
5127 
5128 #define ERROUT(x)	ERROUT_FUNCTION(errout, x)
5129 
5130 	if (nv->len > pf_ioctl_maxcount)
5131 		ERROUT(ENOMEM);
5132 
5133 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
5134 	if (nvlpacked == NULL)
5135 		ERROUT(ENOMEM);
5136 
5137 	error = copyin(nv->data, nvlpacked, nv->len);
5138 	if (error)
5139 		ERROUT(error);
5140 
5141 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
5142 	if (nvl == NULL)
5143 		ERROUT(EBADMSG);
5144 
5145 	PFNV_CHK(pf_nvuint64(nvl, "id", &id));
5146 	PFNV_CHK(pf_nvuint64(nvl, "creatorid", &creatorid));
5147 
5148 	s = pf_find_state_byid(id, creatorid);
5149 	if (s == NULL)
5150 		ERROUT(ENOENT);
5151 
5152 	free(nvlpacked, M_NVLIST);
5153 	nvlpacked = NULL;
5154 	nvlist_destroy(nvl);
5155 	nvl = nvlist_create(0);
5156 	if (nvl == NULL)
5157 		ERROUT(ENOMEM);
5158 
5159 	nvls = pf_state_to_nvstate(s);
5160 	if (nvls == NULL)
5161 		ERROUT(ENOMEM);
5162 
5163 	nvlist_add_nvlist(nvl, "state", nvls);
5164 	nvlist_destroy(nvls);
5165 
5166 	nvlpacked = nvlist_pack(nvl, &nv->len);
5167 	if (nvlpacked == NULL)
5168 		ERROUT(ENOMEM);
5169 
5170 	if (nv->size == 0)
5171 		ERROUT(0);
5172 	else if (nv->size < nv->len)
5173 		ERROUT(ENOSPC);
5174 
5175 	error = copyout(nvlpacked, nv->data, nv->len);
5176 
5177 #undef ERROUT
5178 errout:
5179 	if (s != NULL)
5180 		PF_STATE_UNLOCK(s);
5181 	free(nvlpacked, M_NVLIST);
5182 	nvlist_destroy(nvl);
5183 	return (error);
5184 }
5185 
5186 static int
5187 pf_getstates(struct pfioc_nv *nv)
5188 {
5189 	nvlist_t		*nvl = NULL, *nvls;
5190 	void			*nvlpacked = NULL;
5191 	struct pf_kstate	*s = NULL;
5192 	int			 error = 0;
5193 	uint64_t		 count = 0;
5194 
5195 #define ERROUT(x)	ERROUT_FUNCTION(errout, x)
5196 
5197 	nvl = nvlist_create(0);
5198 	if (nvl == NULL)
5199 		ERROUT(ENOMEM);
5200 
5201 	nvlist_add_number(nvl, "count", uma_zone_get_cur(V_pf_state_z));
5202 
5203 	for (int i = 0; i < pf_hashmask; i++) {
5204 		struct pf_idhash *ih = &V_pf_idhash[i];
5205 
5206 		/* Avoid taking the lock if there are no states in the row. */
5207 		if (LIST_EMPTY(&ih->states))
5208 			continue;
5209 
5210 		PF_HASHROW_LOCK(ih);
5211 		LIST_FOREACH(s, &ih->states, entry) {
5212 			if (s->timeout == PFTM_UNLINKED)
5213 				continue;
5214 
5215 			if (SIGPENDING(curthread)) {
5216 				PF_HASHROW_UNLOCK(ih);
5217 				ERROUT(EINTR);
5218 			}
5219 
5220 			nvls = pf_state_to_nvstate(s);
5221 			if (nvls == NULL) {
5222 				PF_HASHROW_UNLOCK(ih);
5223 				ERROUT(ENOMEM);
5224 			}
5225 			if ((nvlist_size(nvl) + nvlist_size(nvls)) > nv->size) {
5226 				/* We've run out of room for more states. */
5227 				nvlist_destroy(nvls);
5228 				PF_HASHROW_UNLOCK(ih);
5229 				goto DIOCGETSTATESNV_full;
5230 			}
5231 			nvlist_append_nvlist_array(nvl, "states", nvls);
5232 			nvlist_destroy(nvls);
5233 			count++;
5234 		}
5235 		PF_HASHROW_UNLOCK(ih);
5236 	}
5237 
5238 	/* We've managed to put them all the available space. Let's make sure
5239 	 * 'count' matches our array (that's racy, because we don't hold a lock
5240 	 * over all states, only over each row individually. */
5241 	(void)nvlist_take_number(nvl, "count");
5242 	nvlist_add_number(nvl, "count", count);
5243 
5244 DIOCGETSTATESNV_full:
5245 
5246 	nvlpacked = nvlist_pack(nvl, &nv->len);
5247 	if (nvlpacked == NULL)
5248 		ERROUT(ENOMEM);
5249 
5250 	if (nv->size == 0)
5251 		ERROUT(0);
5252 	else if (nv->size < nv->len)
5253 		ERROUT(ENOSPC);
5254 
5255 	error = copyout(nvlpacked, nv->data, nv->len);
5256 
5257 #undef ERROUT
5258 errout:
5259 	free(nvlpacked, M_NVLIST);
5260 	nvlist_destroy(nvl);
5261 	return (error);
5262 }
5263 
5264 /*
5265  * XXX - Check for version missmatch!!!
5266  */
5267 
5268 /*
5269  * Duplicate pfctl -Fa operation to get rid of as much as we can.
5270  */
5271 static int
5272 shutdown_pf(void)
5273 {
5274 	int error = 0;
5275 	u_int32_t t[5];
5276 	char nn = '\0';
5277 
5278 	do {
5279 		if ((error = pf_begin_rules(&t[0], PF_RULESET_SCRUB, &nn))
5280 		    != 0) {
5281 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: SCRUB\n"));
5282 			break;
5283 		}
5284 		if ((error = pf_begin_rules(&t[1], PF_RULESET_FILTER, &nn))
5285 		    != 0) {
5286 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: FILTER\n"));
5287 			break;		/* XXX: rollback? */
5288 		}
5289 		if ((error = pf_begin_rules(&t[2], PF_RULESET_NAT, &nn))
5290 		    != 0) {
5291 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: NAT\n"));
5292 			break;		/* XXX: rollback? */
5293 		}
5294 		if ((error = pf_begin_rules(&t[3], PF_RULESET_BINAT, &nn))
5295 		    != 0) {
5296 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: BINAT\n"));
5297 			break;		/* XXX: rollback? */
5298 		}
5299 		if ((error = pf_begin_rules(&t[4], PF_RULESET_RDR, &nn))
5300 		    != 0) {
5301 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: RDR\n"));
5302 			break;		/* XXX: rollback? */
5303 		}
5304 
5305 		/* XXX: these should always succeed here */
5306 		pf_commit_rules(t[0], PF_RULESET_SCRUB, &nn);
5307 		pf_commit_rules(t[1], PF_RULESET_FILTER, &nn);
5308 		pf_commit_rules(t[2], PF_RULESET_NAT, &nn);
5309 		pf_commit_rules(t[3], PF_RULESET_BINAT, &nn);
5310 		pf_commit_rules(t[4], PF_RULESET_RDR, &nn);
5311 
5312 		if ((error = pf_clear_tables()) != 0)
5313 			break;
5314 
5315 #ifdef ALTQ
5316 		if ((error = pf_begin_altq(&t[0])) != 0) {
5317 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: ALTQ\n"));
5318 			break;
5319 		}
5320 		pf_commit_altq(t[0]);
5321 #endif
5322 
5323 		pf_clear_all_states();
5324 
5325 		pf_clear_srcnodes(NULL);
5326 
5327 		/* status does not use malloced mem so no need to cleanup */
5328 		/* fingerprints and interfaces have their own cleanup code */
5329 	} while(0);
5330 
5331 	return (error);
5332 }
5333 
5334 static pfil_return_t
5335 pf_check_return(int chk, struct mbuf **m)
5336 {
5337 
5338 	switch (chk) {
5339 	case PF_PASS:
5340 		if (*m == NULL)
5341 			return (PFIL_CONSUMED);
5342 		else
5343 			return (PFIL_PASS);
5344 		break;
5345 	default:
5346 		if (*m != NULL) {
5347 			m_freem(*m);
5348 			*m = NULL;
5349 		}
5350 		return (PFIL_DROPPED);
5351 	}
5352 }
5353 
5354 #ifdef INET
5355 static pfil_return_t
5356 pf_check_in(struct mbuf **m, struct ifnet *ifp, int flags,
5357     void *ruleset __unused, struct inpcb *inp)
5358 {
5359 	int chk;
5360 
5361 	chk = pf_test(PF_IN, flags, ifp, m, inp);
5362 
5363 	return (pf_check_return(chk, m));
5364 }
5365 
5366 static pfil_return_t
5367 pf_check_out(struct mbuf **m, struct ifnet *ifp, int flags,
5368     void *ruleset __unused,  struct inpcb *inp)
5369 {
5370 	int chk;
5371 
5372 	chk = pf_test(PF_OUT, flags, ifp, m, inp);
5373 
5374 	return (pf_check_return(chk, m));
5375 }
5376 #endif
5377 
5378 #ifdef INET6
5379 static pfil_return_t
5380 pf_check6_in(struct mbuf **m, struct ifnet *ifp, int flags,
5381     void *ruleset __unused,  struct inpcb *inp)
5382 {
5383 	int chk;
5384 
5385 	/*
5386 	 * In case of loopback traffic IPv6 uses the real interface in
5387 	 * order to support scoped addresses. In order to support stateful
5388 	 * filtering we have change this to lo0 as it is the case in IPv4.
5389 	 */
5390 	CURVNET_SET(ifp->if_vnet);
5391 	chk = pf_test6(PF_IN, flags, (*m)->m_flags & M_LOOP ? V_loif : ifp, m, inp);
5392 	CURVNET_RESTORE();
5393 
5394 	return (pf_check_return(chk, m));
5395 }
5396 
5397 static pfil_return_t
5398 pf_check6_out(struct mbuf **m, struct ifnet *ifp, int flags,
5399     void *ruleset __unused,  struct inpcb *inp)
5400 {
5401 	int chk;
5402 
5403 	CURVNET_SET(ifp->if_vnet);
5404 	chk = pf_test6(PF_OUT, flags, ifp, m, inp);
5405 	CURVNET_RESTORE();
5406 
5407 	return (pf_check_return(chk, m));
5408 }
5409 #endif /* INET6 */
5410 
5411 #ifdef INET
5412 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip4_in_hook);
5413 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip4_out_hook);
5414 #define	V_pf_ip4_in_hook	VNET(pf_ip4_in_hook)
5415 #define	V_pf_ip4_out_hook	VNET(pf_ip4_out_hook)
5416 #endif
5417 #ifdef INET6
5418 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip6_in_hook);
5419 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip6_out_hook);
5420 #define	V_pf_ip6_in_hook	VNET(pf_ip6_in_hook)
5421 #define	V_pf_ip6_out_hook	VNET(pf_ip6_out_hook)
5422 #endif
5423 
5424 static void
5425 hook_pf(void)
5426 {
5427 	struct pfil_hook_args pha;
5428 	struct pfil_link_args pla;
5429 	int ret;
5430 
5431 	if (V_pf_pfil_hooked)
5432 		return;
5433 
5434 	pha.pa_version = PFIL_VERSION;
5435 	pha.pa_modname = "pf";
5436 	pha.pa_ruleset = NULL;
5437 
5438 	pla.pa_version = PFIL_VERSION;
5439 
5440 #ifdef INET
5441 	pha.pa_type = PFIL_TYPE_IP4;
5442 	pha.pa_func = pf_check_in;
5443 	pha.pa_flags = PFIL_IN;
5444 	pha.pa_rulname = "default-in";
5445 	V_pf_ip4_in_hook = pfil_add_hook(&pha);
5446 	pla.pa_flags = PFIL_IN | PFIL_HEADPTR | PFIL_HOOKPTR;
5447 	pla.pa_head = V_inet_pfil_head;
5448 	pla.pa_hook = V_pf_ip4_in_hook;
5449 	ret = pfil_link(&pla);
5450 	MPASS(ret == 0);
5451 	pha.pa_func = pf_check_out;
5452 	pha.pa_flags = PFIL_OUT;
5453 	pha.pa_rulname = "default-out";
5454 	V_pf_ip4_out_hook = pfil_add_hook(&pha);
5455 	pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
5456 	pla.pa_head = V_inet_pfil_head;
5457 	pla.pa_hook = V_pf_ip4_out_hook;
5458 	ret = pfil_link(&pla);
5459 	MPASS(ret == 0);
5460 #endif
5461 #ifdef INET6
5462 	pha.pa_type = PFIL_TYPE_IP6;
5463 	pha.pa_func = pf_check6_in;
5464 	pha.pa_flags = PFIL_IN;
5465 	pha.pa_rulname = "default-in6";
5466 	V_pf_ip6_in_hook = pfil_add_hook(&pha);
5467 	pla.pa_flags = PFIL_IN | PFIL_HEADPTR | PFIL_HOOKPTR;
5468 	pla.pa_head = V_inet6_pfil_head;
5469 	pla.pa_hook = V_pf_ip6_in_hook;
5470 	ret = pfil_link(&pla);
5471 	MPASS(ret == 0);
5472 	pha.pa_func = pf_check6_out;
5473 	pha.pa_rulname = "default-out6";
5474 	pha.pa_flags = PFIL_OUT;
5475 	V_pf_ip6_out_hook = pfil_add_hook(&pha);
5476 	pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
5477 	pla.pa_head = V_inet6_pfil_head;
5478 	pla.pa_hook = V_pf_ip6_out_hook;
5479 	ret = pfil_link(&pla);
5480 	MPASS(ret == 0);
5481 #endif
5482 
5483 	V_pf_pfil_hooked = 1;
5484 }
5485 
5486 static void
5487 dehook_pf(void)
5488 {
5489 
5490 	if (V_pf_pfil_hooked == 0)
5491 		return;
5492 
5493 #ifdef INET
5494 	pfil_remove_hook(V_pf_ip4_in_hook);
5495 	pfil_remove_hook(V_pf_ip4_out_hook);
5496 #endif
5497 #ifdef INET6
5498 	pfil_remove_hook(V_pf_ip6_in_hook);
5499 	pfil_remove_hook(V_pf_ip6_out_hook);
5500 #endif
5501 
5502 	V_pf_pfil_hooked = 0;
5503 }
5504 
5505 static void
5506 pf_load_vnet(void)
5507 {
5508 	V_pf_tag_z = uma_zcreate("pf tags", sizeof(struct pf_tagname),
5509 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
5510 
5511 	pf_init_tagset(&V_pf_tags, &pf_rule_tag_hashsize,
5512 	    PF_RULE_TAG_HASH_SIZE_DEFAULT);
5513 #ifdef ALTQ
5514 	pf_init_tagset(&V_pf_qids, &pf_queue_tag_hashsize,
5515 	    PF_QUEUE_TAG_HASH_SIZE_DEFAULT);
5516 #endif
5517 
5518 	pfattach_vnet();
5519 	V_pf_vnet_active = 1;
5520 }
5521 
5522 static int
5523 pf_load(void)
5524 {
5525 	int error;
5526 
5527 	rm_init(&pf_rules_lock, "pf rulesets");
5528 	sx_init(&pf_ioctl_lock, "pf ioctl");
5529 	sx_init(&pf_end_lock, "pf end thread");
5530 
5531 	pf_mtag_initialize();
5532 
5533 	pf_dev = make_dev(&pf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, PF_NAME);
5534 	if (pf_dev == NULL)
5535 		return (ENOMEM);
5536 
5537 	pf_end_threads = 0;
5538 	error = kproc_create(pf_purge_thread, NULL, &pf_purge_proc, 0, 0, "pf purge");
5539 	if (error != 0)
5540 		return (error);
5541 
5542 	pfi_initialize();
5543 
5544 	return (0);
5545 }
5546 
5547 static void
5548 pf_unload_vnet(void)
5549 {
5550 	int ret;
5551 
5552 	V_pf_vnet_active = 0;
5553 	V_pf_status.running = 0;
5554 	dehook_pf();
5555 
5556 	PF_RULES_WLOCK();
5557 	shutdown_pf();
5558 	PF_RULES_WUNLOCK();
5559 
5560 	ret = swi_remove(V_pf_swi_cookie);
5561 	MPASS(ret == 0);
5562 	ret = intr_event_destroy(V_pf_swi_ie);
5563 	MPASS(ret == 0);
5564 
5565 	pf_unload_vnet_purge();
5566 
5567 	pf_normalize_cleanup();
5568 	PF_RULES_WLOCK();
5569 	pfi_cleanup_vnet();
5570 	PF_RULES_WUNLOCK();
5571 	pfr_cleanup();
5572 	pf_osfp_flush();
5573 	pf_cleanup();
5574 	if (IS_DEFAULT_VNET(curvnet))
5575 		pf_mtag_cleanup();
5576 
5577 	pf_cleanup_tagset(&V_pf_tags);
5578 #ifdef ALTQ
5579 	pf_cleanup_tagset(&V_pf_qids);
5580 #endif
5581 	uma_zdestroy(V_pf_tag_z);
5582 
5583 	/* Free counters last as we updated them during shutdown. */
5584 	counter_u64_free(V_pf_default_rule.evaluations);
5585 	for (int i = 0; i < 2; i++) {
5586 		counter_u64_free(V_pf_default_rule.packets[i]);
5587 		counter_u64_free(V_pf_default_rule.bytes[i]);
5588 	}
5589 	counter_u64_free(V_pf_default_rule.states_cur);
5590 	counter_u64_free(V_pf_default_rule.states_tot);
5591 	counter_u64_free(V_pf_default_rule.src_nodes);
5592 
5593 	for (int i = 0; i < PFRES_MAX; i++)
5594 		counter_u64_free(V_pf_status.counters[i]);
5595 	for (int i = 0; i < LCNT_MAX; i++)
5596 		counter_u64_free(V_pf_status.lcounters[i]);
5597 	for (int i = 0; i < FCNT_MAX; i++)
5598 		counter_u64_free(V_pf_status.fcounters[i]);
5599 	for (int i = 0; i < SCNT_MAX; i++)
5600 		counter_u64_free(V_pf_status.scounters[i]);
5601 }
5602 
5603 static void
5604 pf_unload(void)
5605 {
5606 
5607 	sx_xlock(&pf_end_lock);
5608 	pf_end_threads = 1;
5609 	while (pf_end_threads < 2) {
5610 		wakeup_one(pf_purge_thread);
5611 		sx_sleep(pf_purge_proc, &pf_end_lock, 0, "pftmo", 0);
5612 	}
5613 	sx_xunlock(&pf_end_lock);
5614 
5615 	if (pf_dev != NULL)
5616 		destroy_dev(pf_dev);
5617 
5618 	pfi_cleanup();
5619 
5620 	rm_destroy(&pf_rules_lock);
5621 	sx_destroy(&pf_ioctl_lock);
5622 	sx_destroy(&pf_end_lock);
5623 }
5624 
5625 static void
5626 vnet_pf_init(void *unused __unused)
5627 {
5628 
5629 	pf_load_vnet();
5630 }
5631 VNET_SYSINIT(vnet_pf_init, SI_SUB_PROTO_FIREWALL, SI_ORDER_THIRD,
5632     vnet_pf_init, NULL);
5633 
5634 static void
5635 vnet_pf_uninit(const void *unused __unused)
5636 {
5637 
5638 	pf_unload_vnet();
5639 }
5640 SYSUNINIT(pf_unload, SI_SUB_PROTO_FIREWALL, SI_ORDER_SECOND, pf_unload, NULL);
5641 VNET_SYSUNINIT(vnet_pf_uninit, SI_SUB_PROTO_FIREWALL, SI_ORDER_THIRD,
5642     vnet_pf_uninit, NULL);
5643 
5644 static int
5645 pf_modevent(module_t mod, int type, void *data)
5646 {
5647 	int error = 0;
5648 
5649 	switch(type) {
5650 	case MOD_LOAD:
5651 		error = pf_load();
5652 		break;
5653 	case MOD_UNLOAD:
5654 		/* Handled in SYSUNINIT(pf_unload) to ensure it's done after
5655 		 * the vnet_pf_uninit()s */
5656 		break;
5657 	default:
5658 		error = EINVAL;
5659 		break;
5660 	}
5661 
5662 	return (error);
5663 }
5664 
5665 static moduledata_t pf_mod = {
5666 	"pf",
5667 	pf_modevent,
5668 	0
5669 };
5670 
5671 DECLARE_MODULE(pf, pf_mod, SI_SUB_PROTO_FIREWALL, SI_ORDER_SECOND);
5672 MODULE_VERSION(pf, PF_MODVER);
5673