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