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