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