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