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