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