xref: /freebsd/sys/netpfil/pf/pf_ioctl.c (revision d59a76183470685bdf0b88013d2baad1f04f030f)
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 		error = copyin(nv->data, packed, nv->len);
2827 		if (error)
2828 			ERROUT(error);
2829 
2830 		nvl = nvlist_unpack(packed, nv->len, 0);
2831 		if (nvl == NULL)
2832 			ERROUT(EBADMSG);
2833 
2834 		if (! nvlist_exists_string(nvl, "anchor"))
2835 			ERROUT(EBADMSG);
2836 
2837 		anchor = nvlist_get_string(nvl, "anchor");
2838 
2839 		rs = pf_find_keth_ruleset(anchor);
2840 
2841 		nvlist_destroy(nvl);
2842 		nvl = NULL;
2843 		free(packed, M_NVLIST);
2844 		packed = NULL;
2845 
2846 		if (rs == NULL)
2847 			ERROUT(ENOENT);
2848 
2849 		/* Reply */
2850 		nvl = nvlist_create(0);
2851 		if (nvl == NULL)
2852 			ERROUT(ENOMEM);
2853 
2854 		PF_RULES_RLOCK();
2855 
2856 		ticket = rs->active.ticket;
2857 		tail = TAILQ_LAST(rs->active.rules, pf_keth_ruleq);
2858 		if (tail)
2859 			nr = tail->nr + 1;
2860 		else
2861 			nr = 0;
2862 
2863 		PF_RULES_RUNLOCK();
2864 
2865 		nvlist_add_number(nvl, "ticket", ticket);
2866 		nvlist_add_number(nvl, "nr", nr);
2867 
2868 		packed = nvlist_pack(nvl, &nv->len);
2869 		if (packed == NULL)
2870 			ERROUT(ENOMEM);
2871 
2872 		if (nv->size == 0)
2873 			ERROUT(0);
2874 		else if (nv->size < nv->len)
2875 			ERROUT(ENOSPC);
2876 
2877 		error = copyout(packed, nv->data, nv->len);
2878 
2879 #undef ERROUT
2880 DIOCGETETHRULES_error:
2881 		free(packed, M_NVLIST);
2882 		nvlist_destroy(nvl);
2883 		break;
2884 	}
2885 
2886 	case DIOCGETETHRULE: {
2887 		struct epoch_tracker	 et;
2888 		struct pfioc_nv		*nv = (struct pfioc_nv *)addr;
2889 		nvlist_t		*nvl = NULL;
2890 		void			*nvlpacked = NULL;
2891 		struct pf_keth_rule	*rule = NULL;
2892 		struct pf_keth_ruleset	*rs;
2893 		u_int32_t		 ticket, nr;
2894 		bool			 clear = false;
2895 		const char		*anchor;
2896 
2897 #define ERROUT(x)	ERROUT_IOCTL(DIOCGETETHRULE_error, x)
2898 
2899 		if (nv->len > pf_ioctl_maxcount)
2900 			ERROUT(ENOMEM);
2901 
2902 		nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
2903 		error = copyin(nv->data, nvlpacked, nv->len);
2904 		if (error)
2905 			ERROUT(error);
2906 
2907 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
2908 		if (nvl == NULL)
2909 			ERROUT(EBADMSG);
2910 		if (! nvlist_exists_number(nvl, "ticket"))
2911 			ERROUT(EBADMSG);
2912 		ticket = nvlist_get_number(nvl, "ticket");
2913 		if (! nvlist_exists_string(nvl, "anchor"))
2914 			ERROUT(EBADMSG);
2915 		anchor = nvlist_get_string(nvl, "anchor");
2916 
2917 		if (nvlist_exists_bool(nvl, "clear"))
2918 			clear = nvlist_get_bool(nvl, "clear");
2919 
2920 		if (clear && !(flags & FWRITE))
2921 			ERROUT(EACCES);
2922 
2923 		if (! nvlist_exists_number(nvl, "nr"))
2924 			ERROUT(EBADMSG);
2925 		nr = nvlist_get_number(nvl, "nr");
2926 
2927 		PF_RULES_RLOCK();
2928 		rs = pf_find_keth_ruleset(anchor);
2929 		if (rs == NULL) {
2930 			PF_RULES_RUNLOCK();
2931 			ERROUT(ENOENT);
2932 		}
2933 		if (ticket != rs->active.ticket) {
2934 			PF_RULES_RUNLOCK();
2935 			ERROUT(EBUSY);
2936 		}
2937 
2938 		nvlist_destroy(nvl);
2939 		nvl = NULL;
2940 		free(nvlpacked, M_NVLIST);
2941 		nvlpacked = NULL;
2942 
2943 		rule = TAILQ_FIRST(rs->active.rules);
2944 		while ((rule != NULL) && (rule->nr != nr))
2945 			rule = TAILQ_NEXT(rule, entries);
2946 		if (rule == NULL) {
2947 			PF_RULES_RUNLOCK();
2948 			ERROUT(ENOENT);
2949 		}
2950 		/* Make sure rule can't go away. */
2951 		NET_EPOCH_ENTER(et);
2952 		PF_RULES_RUNLOCK();
2953 		nvl = pf_keth_rule_to_nveth_rule(rule);
2954 		if (pf_keth_anchor_nvcopyout(rs, rule, nvl))
2955 			ERROUT(EBUSY);
2956 		NET_EPOCH_EXIT(et);
2957 		if (nvl == NULL)
2958 			ERROUT(ENOMEM);
2959 
2960 		nvlpacked = nvlist_pack(nvl, &nv->len);
2961 		if (nvlpacked == NULL)
2962 			ERROUT(ENOMEM);
2963 
2964 		if (nv->size == 0)
2965 			ERROUT(0);
2966 		else if (nv->size < nv->len)
2967 			ERROUT(ENOSPC);
2968 
2969 		error = copyout(nvlpacked, nv->data, nv->len);
2970 		if (error == 0 && clear) {
2971 			counter_u64_zero(rule->evaluations);
2972 			for (int i = 0; i < 2; i++) {
2973 				counter_u64_zero(rule->packets[i]);
2974 				counter_u64_zero(rule->bytes[i]);
2975 			}
2976 		}
2977 
2978 #undef ERROUT
2979 DIOCGETETHRULE_error:
2980 		free(nvlpacked, M_NVLIST);
2981 		nvlist_destroy(nvl);
2982 		break;
2983 	}
2984 
2985 	case DIOCADDETHRULE: {
2986 		struct pfioc_nv		*nv = (struct pfioc_nv *)addr;
2987 		nvlist_t		*nvl = NULL;
2988 		void			*nvlpacked = NULL;
2989 		struct pf_keth_rule	*rule = NULL, *tail = NULL;
2990 		struct pf_keth_ruleset	*ruleset = NULL;
2991 		struct pfi_kkif		*kif = NULL, *bridge_to_kif = NULL;
2992 		const char		*anchor = "", *anchor_call = "";
2993 
2994 #define ERROUT(x)	ERROUT_IOCTL(DIOCADDETHRULE_error, x)
2995 
2996 		if (nv->len > pf_ioctl_maxcount)
2997 			ERROUT(ENOMEM);
2998 
2999 		nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
3000 		error = copyin(nv->data, nvlpacked, nv->len);
3001 		if (error)
3002 			ERROUT(error);
3003 
3004 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
3005 		if (nvl == NULL)
3006 			ERROUT(EBADMSG);
3007 
3008 		if (! nvlist_exists_number(nvl, "ticket"))
3009 			ERROUT(EBADMSG);
3010 
3011 		if (nvlist_exists_string(nvl, "anchor"))
3012 			anchor = nvlist_get_string(nvl, "anchor");
3013 		if (nvlist_exists_string(nvl, "anchor_call"))
3014 			anchor_call = nvlist_get_string(nvl, "anchor_call");
3015 
3016 		ruleset = pf_find_keth_ruleset(anchor);
3017 		if (ruleset == NULL)
3018 			ERROUT(EINVAL);
3019 
3020 		if (nvlist_get_number(nvl, "ticket") !=
3021 		    ruleset->inactive.ticket) {
3022 			DPFPRINTF(PF_DEBUG_MISC,
3023 			    ("ticket: %d != %d\n",
3024 			    (u_int32_t)nvlist_get_number(nvl, "ticket"),
3025 			    ruleset->inactive.ticket));
3026 			ERROUT(EBUSY);
3027 		}
3028 
3029 		rule = malloc(sizeof(*rule), M_PFRULE, M_WAITOK);
3030 		rule->timestamp = NULL;
3031 
3032 		error = pf_nveth_rule_to_keth_rule(nvl, rule);
3033 		if (error != 0)
3034 			ERROUT(error);
3035 
3036 		if (rule->ifname[0])
3037 			kif = pf_kkif_create(M_WAITOK);
3038 		if (rule->bridge_to_name[0])
3039 			bridge_to_kif = pf_kkif_create(M_WAITOK);
3040 		rule->evaluations = counter_u64_alloc(M_WAITOK);
3041 		for (int i = 0; i < 2; i++) {
3042 			rule->packets[i] = counter_u64_alloc(M_WAITOK);
3043 			rule->bytes[i] = counter_u64_alloc(M_WAITOK);
3044 		}
3045 		rule->timestamp = uma_zalloc_pcpu(pf_timestamp_pcpu_zone,
3046 		    M_WAITOK | M_ZERO);
3047 
3048 		PF_RULES_WLOCK();
3049 
3050 		if (rule->ifname[0]) {
3051 			rule->kif = pfi_kkif_attach(kif, rule->ifname);
3052 			pfi_kkif_ref(rule->kif);
3053 		} else
3054 			rule->kif = NULL;
3055 		if (rule->bridge_to_name[0]) {
3056 			rule->bridge_to = pfi_kkif_attach(bridge_to_kif,
3057 			    rule->bridge_to_name);
3058 			pfi_kkif_ref(rule->bridge_to);
3059 		} else
3060 			rule->bridge_to = NULL;
3061 
3062 #ifdef ALTQ
3063 		/* set queue IDs */
3064 		if (rule->qname[0] != 0) {
3065 			if ((rule->qid = pf_qname2qid(rule->qname)) == 0)
3066 				error = EBUSY;
3067 			else
3068 				rule->qid = rule->qid;
3069 		}
3070 #endif
3071 		if (rule->tagname[0])
3072 			if ((rule->tag = pf_tagname2tag(rule->tagname)) == 0)
3073 				error = EBUSY;
3074 		if (rule->match_tagname[0])
3075 			if ((rule->match_tag = pf_tagname2tag(
3076 			    rule->match_tagname)) == 0)
3077 				error = EBUSY;
3078 
3079 		if (error == 0 && rule->ipdst.addr.type == PF_ADDR_TABLE)
3080 			error = pf_eth_addr_setup(ruleset, &rule->ipdst.addr);
3081 		if (error == 0 && rule->ipsrc.addr.type == PF_ADDR_TABLE)
3082 			error = pf_eth_addr_setup(ruleset, &rule->ipsrc.addr);
3083 
3084 		if (error) {
3085 			pf_free_eth_rule(rule);
3086 			PF_RULES_WUNLOCK();
3087 			ERROUT(error);
3088 		}
3089 
3090 		if (pf_keth_anchor_setup(rule, ruleset, anchor_call)) {
3091 			pf_free_eth_rule(rule);
3092 			PF_RULES_WUNLOCK();
3093 			ERROUT(EINVAL);
3094 		}
3095 
3096 		tail = TAILQ_LAST(ruleset->inactive.rules, pf_keth_ruleq);
3097 		if (tail)
3098 			rule->nr = tail->nr + 1;
3099 		else
3100 			rule->nr = 0;
3101 
3102 		TAILQ_INSERT_TAIL(ruleset->inactive.rules, rule, entries);
3103 
3104 		PF_RULES_WUNLOCK();
3105 
3106 #undef ERROUT
3107 DIOCADDETHRULE_error:
3108 		nvlist_destroy(nvl);
3109 		free(nvlpacked, M_NVLIST);
3110 		break;
3111 	}
3112 
3113 	case DIOCGETETHRULESETS: {
3114 		struct epoch_tracker	 et;
3115 		struct pfioc_nv		*nv = (struct pfioc_nv *)addr;
3116 		nvlist_t		*nvl = NULL;
3117 		void			*nvlpacked = NULL;
3118 		struct pf_keth_ruleset	*ruleset;
3119 		struct pf_keth_anchor	*anchor;
3120 		int			 nr = 0;
3121 
3122 #define ERROUT(x)	ERROUT_IOCTL(DIOCGETETHRULESETS_error, x)
3123 
3124 		if (nv->len > pf_ioctl_maxcount)
3125 			ERROUT(ENOMEM);
3126 
3127 		nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
3128 		error = copyin(nv->data, nvlpacked, nv->len);
3129 		if (error)
3130 			ERROUT(error);
3131 
3132 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
3133 		if (nvl == NULL)
3134 			ERROUT(EBADMSG);
3135 		if (! nvlist_exists_string(nvl, "path"))
3136 			ERROUT(EBADMSG);
3137 
3138 		NET_EPOCH_ENTER(et);
3139 
3140 		if ((ruleset = pf_find_keth_ruleset(
3141 		    nvlist_get_string(nvl, "path"))) == NULL) {
3142 			NET_EPOCH_EXIT(et);
3143 			ERROUT(ENOENT);
3144 		}
3145 
3146 		if (ruleset->anchor == NULL) {
3147 			RB_FOREACH(anchor, pf_keth_anchor_global, &V_pf_keth_anchors)
3148 				if (anchor->parent == NULL)
3149 					nr++;
3150 		} else {
3151 			RB_FOREACH(anchor, pf_keth_anchor_node,
3152 			    &ruleset->anchor->children)
3153 				nr++;
3154 		}
3155 
3156 		NET_EPOCH_EXIT(et);
3157 
3158 		nvlist_destroy(nvl);
3159 		nvl = NULL;
3160 		free(nvlpacked, M_NVLIST);
3161 		nvlpacked = NULL;
3162 
3163 		nvl = nvlist_create(0);
3164 		if (nvl == NULL)
3165 			ERROUT(ENOMEM);
3166 
3167 		nvlist_add_number(nvl, "nr", nr);
3168 
3169 		nvlpacked = nvlist_pack(nvl, &nv->len);
3170 		if (nvlpacked == NULL)
3171 			ERROUT(ENOMEM);
3172 
3173 		if (nv->size == 0)
3174 			ERROUT(0);
3175 		else if (nv->size < nv->len)
3176 			ERROUT(ENOSPC);
3177 
3178 		error = copyout(nvlpacked, nv->data, nv->len);
3179 
3180 #undef ERROUT
3181 DIOCGETETHRULESETS_error:
3182 		free(nvlpacked, M_NVLIST);
3183 		nvlist_destroy(nvl);
3184 		break;
3185 	}
3186 
3187 	case DIOCGETETHRULESET: {
3188 		struct epoch_tracker	 et;
3189 		struct pfioc_nv		*nv = (struct pfioc_nv *)addr;
3190 		nvlist_t		*nvl = NULL;
3191 		void			*nvlpacked = NULL;
3192 		struct pf_keth_ruleset	*ruleset;
3193 		struct pf_keth_anchor	*anchor;
3194 		int			 nr = 0, req_nr = 0;
3195 		bool			 found = false;
3196 
3197 #define ERROUT(x)	ERROUT_IOCTL(DIOCGETETHRULESET_error, x)
3198 
3199 		if (nv->len > pf_ioctl_maxcount)
3200 			ERROUT(ENOMEM);
3201 
3202 		nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
3203 		error = copyin(nv->data, nvlpacked, nv->len);
3204 		if (error)
3205 			ERROUT(error);
3206 
3207 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
3208 		if (nvl == NULL)
3209 			ERROUT(EBADMSG);
3210 		if (! nvlist_exists_string(nvl, "path"))
3211 			ERROUT(EBADMSG);
3212 		if (! nvlist_exists_number(nvl, "nr"))
3213 			ERROUT(EBADMSG);
3214 
3215 		req_nr = nvlist_get_number(nvl, "nr");
3216 
3217 		NET_EPOCH_ENTER(et);
3218 
3219 		if ((ruleset = pf_find_keth_ruleset(
3220 		    nvlist_get_string(nvl, "path"))) == NULL) {
3221 			NET_EPOCH_EXIT(et);
3222 			ERROUT(ENOENT);
3223 		}
3224 
3225 		nvlist_destroy(nvl);
3226 		nvl = NULL;
3227 		free(nvlpacked, M_NVLIST);
3228 		nvlpacked = NULL;
3229 
3230 		nvl = nvlist_create(0);
3231 		if (nvl == NULL) {
3232 			NET_EPOCH_EXIT(et);
3233 			ERROUT(ENOMEM);
3234 		}
3235 
3236 		if (ruleset->anchor == NULL) {
3237 			RB_FOREACH(anchor, pf_keth_anchor_global,
3238 			    &V_pf_keth_anchors) {
3239 				if (anchor->parent == NULL && nr++ == req_nr) {
3240 					found = true;
3241 					break;
3242 				}
3243 			}
3244 		} else {
3245 			RB_FOREACH(anchor, pf_keth_anchor_node,
3246 			     &ruleset->anchor->children) {
3247 				if (nr++ == req_nr) {
3248 					found = true;
3249 					break;
3250 				}
3251 			}
3252 		}
3253 
3254 		NET_EPOCH_EXIT(et);
3255 		if (found) {
3256 			nvlist_add_number(nvl, "nr", nr);
3257 			nvlist_add_string(nvl, "name", anchor->name);
3258 			if (ruleset->anchor)
3259 				nvlist_add_string(nvl, "path",
3260 				    ruleset->anchor->path);
3261 			else
3262 				nvlist_add_string(nvl, "path", "");
3263 		} else {
3264 			ERROUT(EBUSY);
3265 		}
3266 
3267 		nvlpacked = nvlist_pack(nvl, &nv->len);
3268 		if (nvlpacked == NULL)
3269 			ERROUT(ENOMEM);
3270 
3271 		if (nv->size == 0)
3272 			ERROUT(0);
3273 		else if (nv->size < nv->len)
3274 			ERROUT(ENOSPC);
3275 
3276 		error = copyout(nvlpacked, nv->data, nv->len);
3277 
3278 #undef ERROUT
3279 DIOCGETETHRULESET_error:
3280 		free(nvlpacked, M_NVLIST);
3281 		nvlist_destroy(nvl);
3282 		break;
3283 	}
3284 
3285 	case DIOCADDRULENV: {
3286 		struct pfioc_nv	*nv = (struct pfioc_nv *)addr;
3287 		nvlist_t	*nvl = NULL;
3288 		void		*nvlpacked = NULL;
3289 		struct pf_krule	*rule = NULL;
3290 		const char	*anchor = "", *anchor_call = "";
3291 		uint32_t	 ticket = 0, pool_ticket = 0;
3292 
3293 #define	ERROUT(x)	ERROUT_IOCTL(DIOCADDRULENV_error, x)
3294 
3295 		if (nv->len > pf_ioctl_maxcount)
3296 			ERROUT(ENOMEM);
3297 
3298 		nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
3299 		error = copyin(nv->data, nvlpacked, nv->len);
3300 		if (error)
3301 			ERROUT(error);
3302 
3303 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
3304 		if (nvl == NULL)
3305 			ERROUT(EBADMSG);
3306 
3307 		if (! nvlist_exists_number(nvl, "ticket"))
3308 			ERROUT(EINVAL);
3309 		ticket = nvlist_get_number(nvl, "ticket");
3310 
3311 		if (! nvlist_exists_number(nvl, "pool_ticket"))
3312 			ERROUT(EINVAL);
3313 		pool_ticket = nvlist_get_number(nvl, "pool_ticket");
3314 
3315 		if (! nvlist_exists_nvlist(nvl, "rule"))
3316 			ERROUT(EINVAL);
3317 
3318 		rule = pf_krule_alloc();
3319 		error = pf_nvrule_to_krule(nvlist_get_nvlist(nvl, "rule"),
3320 		    rule);
3321 		if (error)
3322 			ERROUT(error);
3323 
3324 		if (nvlist_exists_string(nvl, "anchor"))
3325 			anchor = nvlist_get_string(nvl, "anchor");
3326 		if (nvlist_exists_string(nvl, "anchor_call"))
3327 			anchor_call = nvlist_get_string(nvl, "anchor_call");
3328 
3329 		if ((error = nvlist_error(nvl)))
3330 			ERROUT(error);
3331 
3332 		/* Frees rule on error */
3333 		error = pf_ioctl_addrule(rule, ticket, pool_ticket, anchor,
3334 		    anchor_call, td->td_ucred->cr_ruid,
3335 		    td->td_proc ? td->td_proc->p_pid : 0);
3336 
3337 		nvlist_destroy(nvl);
3338 		free(nvlpacked, M_NVLIST);
3339 		break;
3340 #undef ERROUT
3341 DIOCADDRULENV_error:
3342 		pf_krule_free(rule);
3343 		nvlist_destroy(nvl);
3344 		free(nvlpacked, M_NVLIST);
3345 
3346 		break;
3347 	}
3348 	case DIOCADDRULE: {
3349 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
3350 		struct pf_krule		*rule;
3351 
3352 		rule = pf_krule_alloc();
3353 		error = pf_rule_to_krule(&pr->rule, rule);
3354 		if (error != 0) {
3355 			pf_krule_free(rule);
3356 			break;
3357 		}
3358 
3359 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
3360 
3361 		/* Frees rule on error */
3362 		error = pf_ioctl_addrule(rule, pr->ticket, pr->pool_ticket,
3363 		    pr->anchor, pr->anchor_call, td->td_ucred->cr_ruid,
3364 		    td->td_proc ? td->td_proc->p_pid : 0);
3365 		break;
3366 	}
3367 
3368 	case DIOCGETRULES: {
3369 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
3370 
3371 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
3372 
3373 		error = pf_ioctl_getrules(pr);
3374 
3375 		break;
3376 	}
3377 
3378 	case DIOCGETRULENV: {
3379 		struct pfioc_nv		*nv = (struct pfioc_nv *)addr;
3380 		nvlist_t		*nvrule = NULL;
3381 		nvlist_t		*nvl = NULL;
3382 		struct pf_kruleset	*ruleset;
3383 		struct pf_krule		*rule;
3384 		void			*nvlpacked = NULL;
3385 		int			 rs_num, nr;
3386 		bool			 clear_counter = false;
3387 
3388 #define	ERROUT(x)	ERROUT_IOCTL(DIOCGETRULENV_error, x)
3389 
3390 		if (nv->len > pf_ioctl_maxcount)
3391 			ERROUT(ENOMEM);
3392 
3393 		/* Copy the request in */
3394 		nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
3395 		error = copyin(nv->data, nvlpacked, nv->len);
3396 		if (error)
3397 			ERROUT(error);
3398 
3399 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
3400 		if (nvl == NULL)
3401 			ERROUT(EBADMSG);
3402 
3403 		if (! nvlist_exists_string(nvl, "anchor"))
3404 			ERROUT(EBADMSG);
3405 		if (! nvlist_exists_number(nvl, "ruleset"))
3406 			ERROUT(EBADMSG);
3407 		if (! nvlist_exists_number(nvl, "ticket"))
3408 			ERROUT(EBADMSG);
3409 		if (! nvlist_exists_number(nvl, "nr"))
3410 			ERROUT(EBADMSG);
3411 
3412 		if (nvlist_exists_bool(nvl, "clear_counter"))
3413 			clear_counter = nvlist_get_bool(nvl, "clear_counter");
3414 
3415 		if (clear_counter && !(flags & FWRITE))
3416 			ERROUT(EACCES);
3417 
3418 		nr = nvlist_get_number(nvl, "nr");
3419 
3420 		PF_RULES_WLOCK();
3421 		ruleset = pf_find_kruleset(nvlist_get_string(nvl, "anchor"));
3422 		if (ruleset == NULL) {
3423 			PF_RULES_WUNLOCK();
3424 			ERROUT(ENOENT);
3425 		}
3426 
3427 		rs_num = pf_get_ruleset_number(nvlist_get_number(nvl, "ruleset"));
3428 		if (rs_num >= PF_RULESET_MAX) {
3429 			PF_RULES_WUNLOCK();
3430 			ERROUT(EINVAL);
3431 		}
3432 
3433 		if (nvlist_get_number(nvl, "ticket") !=
3434 		    ruleset->rules[rs_num].active.ticket) {
3435 			PF_RULES_WUNLOCK();
3436 			ERROUT(EBUSY);
3437 		}
3438 
3439 		if ((error = nvlist_error(nvl))) {
3440 			PF_RULES_WUNLOCK();
3441 			ERROUT(error);
3442 		}
3443 
3444 		rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
3445 		while ((rule != NULL) && (rule->nr != nr))
3446 			rule = TAILQ_NEXT(rule, entries);
3447 		if (rule == NULL) {
3448 			PF_RULES_WUNLOCK();
3449 			ERROUT(EBUSY);
3450 		}
3451 
3452 		nvrule = pf_krule_to_nvrule(rule);
3453 
3454 		nvlist_destroy(nvl);
3455 		nvl = nvlist_create(0);
3456 		if (nvl == NULL) {
3457 			PF_RULES_WUNLOCK();
3458 			ERROUT(ENOMEM);
3459 		}
3460 		nvlist_add_number(nvl, "nr", nr);
3461 		nvlist_add_nvlist(nvl, "rule", nvrule);
3462 		nvlist_destroy(nvrule);
3463 		nvrule = NULL;
3464 		if (pf_kanchor_nvcopyout(ruleset, rule, nvl)) {
3465 			PF_RULES_WUNLOCK();
3466 			ERROUT(EBUSY);
3467 		}
3468 
3469 		free(nvlpacked, M_NVLIST);
3470 		nvlpacked = nvlist_pack(nvl, &nv->len);
3471 		if (nvlpacked == NULL) {
3472 			PF_RULES_WUNLOCK();
3473 			ERROUT(ENOMEM);
3474 		}
3475 
3476 		if (nv->size == 0) {
3477 			PF_RULES_WUNLOCK();
3478 			ERROUT(0);
3479 		}
3480 		else if (nv->size < nv->len) {
3481 			PF_RULES_WUNLOCK();
3482 			ERROUT(ENOSPC);
3483 		}
3484 
3485 		if (clear_counter)
3486 			pf_krule_clear_counters(rule);
3487 
3488 		PF_RULES_WUNLOCK();
3489 
3490 		error = copyout(nvlpacked, nv->data, nv->len);
3491 
3492 #undef ERROUT
3493 DIOCGETRULENV_error:
3494 		free(nvlpacked, M_NVLIST);
3495 		nvlist_destroy(nvrule);
3496 		nvlist_destroy(nvl);
3497 
3498 		break;
3499 	}
3500 
3501 	case DIOCCHANGERULE: {
3502 		struct pfioc_rule	*pcr = (struct pfioc_rule *)addr;
3503 		struct pf_kruleset	*ruleset;
3504 		struct pf_krule		*oldrule = NULL, *newrule = NULL;
3505 		struct pfi_kkif		*kif = NULL;
3506 		struct pf_kpooladdr	*pa;
3507 		u_int32_t		 nr = 0;
3508 		int			 rs_num;
3509 
3510 		pcr->anchor[sizeof(pcr->anchor) - 1] = 0;
3511 
3512 		if (pcr->action < PF_CHANGE_ADD_HEAD ||
3513 		    pcr->action > PF_CHANGE_GET_TICKET) {
3514 			error = EINVAL;
3515 			break;
3516 		}
3517 		if (pcr->rule.return_icmp >> 8 > ICMP_MAXTYPE) {
3518 			error = EINVAL;
3519 			break;
3520 		}
3521 
3522 		if (pcr->action != PF_CHANGE_REMOVE) {
3523 			newrule = pf_krule_alloc();
3524 			error = pf_rule_to_krule(&pcr->rule, newrule);
3525 			if (error != 0) {
3526 				pf_krule_free(newrule);
3527 				break;
3528 			}
3529 
3530 			if (newrule->ifname[0])
3531 				kif = pf_kkif_create(M_WAITOK);
3532 			pf_counter_u64_init(&newrule->evaluations, M_WAITOK);
3533 			for (int i = 0; i < 2; i++) {
3534 				pf_counter_u64_init(&newrule->packets[i], M_WAITOK);
3535 				pf_counter_u64_init(&newrule->bytes[i], M_WAITOK);
3536 			}
3537 			newrule->states_cur = counter_u64_alloc(M_WAITOK);
3538 			newrule->states_tot = counter_u64_alloc(M_WAITOK);
3539 			newrule->src_nodes = counter_u64_alloc(M_WAITOK);
3540 			newrule->cuid = td->td_ucred->cr_ruid;
3541 			newrule->cpid = td->td_proc ? td->td_proc->p_pid : 0;
3542 			TAILQ_INIT(&newrule->rpool.list);
3543 		}
3544 #define	ERROUT(x)	ERROUT_IOCTL(DIOCCHANGERULE_error, x)
3545 
3546 		PF_CONFIG_LOCK();
3547 		PF_RULES_WLOCK();
3548 #ifdef PF_WANT_32_TO_64_COUNTER
3549 		if (newrule != NULL) {
3550 			LIST_INSERT_HEAD(&V_pf_allrulelist, newrule, allrulelist);
3551 			newrule->allrulelinked = true;
3552 			V_pf_allrulecount++;
3553 		}
3554 #endif
3555 
3556 		if (!(pcr->action == PF_CHANGE_REMOVE ||
3557 		    pcr->action == PF_CHANGE_GET_TICKET) &&
3558 		    pcr->pool_ticket != V_ticket_pabuf)
3559 			ERROUT(EBUSY);
3560 
3561 		ruleset = pf_find_kruleset(pcr->anchor);
3562 		if (ruleset == NULL)
3563 			ERROUT(EINVAL);
3564 
3565 		rs_num = pf_get_ruleset_number(pcr->rule.action);
3566 		if (rs_num >= PF_RULESET_MAX)
3567 			ERROUT(EINVAL);
3568 
3569 		/*
3570 		 * XXXMJG: there is no guarantee that the ruleset was
3571 		 * created by the usual route of calling DIOCXBEGIN.
3572 		 * As a result it is possible the rule tree will not
3573 		 * be allocated yet. Hack around it by doing it here.
3574 		 * Note it is fine to let the tree persist in case of
3575 		 * error as it will be freed down the road on future
3576 		 * updates (if need be).
3577 		 */
3578 		if (ruleset->rules[rs_num].active.tree == NULL) {
3579 			ruleset->rules[rs_num].active.tree = pf_rule_tree_alloc(M_NOWAIT);
3580 			if (ruleset->rules[rs_num].active.tree == NULL) {
3581 				ERROUT(ENOMEM);
3582 			}
3583 		}
3584 
3585 		if (pcr->action == PF_CHANGE_GET_TICKET) {
3586 			pcr->ticket = ++ruleset->rules[rs_num].active.ticket;
3587 			ERROUT(0);
3588 		} else if (pcr->ticket !=
3589 			    ruleset->rules[rs_num].active.ticket)
3590 				ERROUT(EINVAL);
3591 
3592 		if (pcr->action != PF_CHANGE_REMOVE) {
3593 			if (newrule->ifname[0]) {
3594 				newrule->kif = pfi_kkif_attach(kif,
3595 				    newrule->ifname);
3596 				kif = NULL;
3597 				pfi_kkif_ref(newrule->kif);
3598 			} else
3599 				newrule->kif = NULL;
3600 
3601 			if (newrule->rtableid > 0 &&
3602 			    newrule->rtableid >= rt_numfibs)
3603 				error = EBUSY;
3604 
3605 #ifdef ALTQ
3606 			/* set queue IDs */
3607 			if (newrule->qname[0] != 0) {
3608 				if ((newrule->qid =
3609 				    pf_qname2qid(newrule->qname)) == 0)
3610 					error = EBUSY;
3611 				else if (newrule->pqname[0] != 0) {
3612 					if ((newrule->pqid =
3613 					    pf_qname2qid(newrule->pqname)) == 0)
3614 						error = EBUSY;
3615 				} else
3616 					newrule->pqid = newrule->qid;
3617 			}
3618 #endif /* ALTQ */
3619 			if (newrule->tagname[0])
3620 				if ((newrule->tag =
3621 				    pf_tagname2tag(newrule->tagname)) == 0)
3622 					error = EBUSY;
3623 			if (newrule->match_tagname[0])
3624 				if ((newrule->match_tag = pf_tagname2tag(
3625 				    newrule->match_tagname)) == 0)
3626 					error = EBUSY;
3627 			if (newrule->rt && !newrule->direction)
3628 				error = EINVAL;
3629 			if (!newrule->log)
3630 				newrule->logif = 0;
3631 			if (newrule->logif >= PFLOGIFS_MAX)
3632 				error = EINVAL;
3633 			if (pf_addr_setup(ruleset, &newrule->src.addr, newrule->af))
3634 				error = ENOMEM;
3635 			if (pf_addr_setup(ruleset, &newrule->dst.addr, newrule->af))
3636 				error = ENOMEM;
3637 			if (pf_kanchor_setup(newrule, ruleset, pcr->anchor_call))
3638 				error = EINVAL;
3639 			TAILQ_FOREACH(pa, &V_pf_pabuf, entries)
3640 				if (pa->addr.type == PF_ADDR_TABLE) {
3641 					pa->addr.p.tbl =
3642 					    pfr_attach_table(ruleset,
3643 					    pa->addr.v.tblname);
3644 					if (pa->addr.p.tbl == NULL)
3645 						error = ENOMEM;
3646 				}
3647 
3648 			newrule->overload_tbl = NULL;
3649 			if (newrule->overload_tblname[0]) {
3650 				if ((newrule->overload_tbl = pfr_attach_table(
3651 				    ruleset, newrule->overload_tblname)) ==
3652 				    NULL)
3653 					error = EINVAL;
3654 				else
3655 					newrule->overload_tbl->pfrkt_flags |=
3656 					    PFR_TFLAG_ACTIVE;
3657 			}
3658 
3659 			pf_mv_kpool(&V_pf_pabuf, &newrule->rpool.list);
3660 			if (((((newrule->action == PF_NAT) ||
3661 			    (newrule->action == PF_RDR) ||
3662 			    (newrule->action == PF_BINAT) ||
3663 			    (newrule->rt > PF_NOPFROUTE)) &&
3664 			    !newrule->anchor)) &&
3665 			    (TAILQ_FIRST(&newrule->rpool.list) == NULL))
3666 				error = EINVAL;
3667 
3668 			if (error) {
3669 				pf_free_rule(newrule);
3670 				PF_RULES_WUNLOCK();
3671 				PF_CONFIG_UNLOCK();
3672 				break;
3673 			}
3674 
3675 			newrule->rpool.cur = TAILQ_FIRST(&newrule->rpool.list);
3676 		}
3677 		pf_empty_kpool(&V_pf_pabuf);
3678 
3679 		if (pcr->action == PF_CHANGE_ADD_HEAD)
3680 			oldrule = TAILQ_FIRST(
3681 			    ruleset->rules[rs_num].active.ptr);
3682 		else if (pcr->action == PF_CHANGE_ADD_TAIL)
3683 			oldrule = TAILQ_LAST(
3684 			    ruleset->rules[rs_num].active.ptr, pf_krulequeue);
3685 		else {
3686 			oldrule = TAILQ_FIRST(
3687 			    ruleset->rules[rs_num].active.ptr);
3688 			while ((oldrule != NULL) && (oldrule->nr != pcr->nr))
3689 				oldrule = TAILQ_NEXT(oldrule, entries);
3690 			if (oldrule == NULL) {
3691 				if (newrule != NULL)
3692 					pf_free_rule(newrule);
3693 				PF_RULES_WUNLOCK();
3694 				PF_CONFIG_UNLOCK();
3695 				error = EINVAL;
3696 				break;
3697 			}
3698 		}
3699 
3700 		if (pcr->action == PF_CHANGE_REMOVE) {
3701 			pf_unlink_rule(ruleset->rules[rs_num].active.ptr,
3702 			    oldrule);
3703 			RB_REMOVE(pf_krule_global,
3704 			    ruleset->rules[rs_num].active.tree, oldrule);
3705 			ruleset->rules[rs_num].active.rcount--;
3706 		} else {
3707 			pf_hash_rule(newrule);
3708 			if (RB_INSERT(pf_krule_global,
3709 			    ruleset->rules[rs_num].active.tree, newrule) != NULL) {
3710 				pf_free_rule(newrule);
3711 				PF_RULES_WUNLOCK();
3712 				PF_CONFIG_UNLOCK();
3713 				error = EEXIST;
3714 				break;
3715 			}
3716 
3717 			if (oldrule == NULL)
3718 				TAILQ_INSERT_TAIL(
3719 				    ruleset->rules[rs_num].active.ptr,
3720 				    newrule, entries);
3721 			else if (pcr->action == PF_CHANGE_ADD_HEAD ||
3722 			    pcr->action == PF_CHANGE_ADD_BEFORE)
3723 				TAILQ_INSERT_BEFORE(oldrule, newrule, entries);
3724 			else
3725 				TAILQ_INSERT_AFTER(
3726 				    ruleset->rules[rs_num].active.ptr,
3727 				    oldrule, newrule, entries);
3728 			ruleset->rules[rs_num].active.rcount++;
3729 		}
3730 
3731 		nr = 0;
3732 		TAILQ_FOREACH(oldrule,
3733 		    ruleset->rules[rs_num].active.ptr, entries)
3734 			oldrule->nr = nr++;
3735 
3736 		ruleset->rules[rs_num].active.ticket++;
3737 
3738 		pf_calc_skip_steps(ruleset->rules[rs_num].active.ptr);
3739 		pf_remove_if_empty_kruleset(ruleset);
3740 
3741 		PF_RULES_WUNLOCK();
3742 		PF_CONFIG_UNLOCK();
3743 		break;
3744 
3745 #undef ERROUT
3746 DIOCCHANGERULE_error:
3747 		PF_RULES_WUNLOCK();
3748 		PF_CONFIG_UNLOCK();
3749 		pf_krule_free(newrule);
3750 		pf_kkif_free(kif);
3751 		break;
3752 	}
3753 
3754 	case DIOCCLRSTATESNV: {
3755 		error = pf_clearstates_nv((struct pfioc_nv *)addr);
3756 		break;
3757 	}
3758 
3759 	case DIOCKILLSTATESNV: {
3760 		error = pf_killstates_nv((struct pfioc_nv *)addr);
3761 		break;
3762 	}
3763 
3764 	case DIOCADDSTATE: {
3765 		struct pfioc_state		*ps = (struct pfioc_state *)addr;
3766 		struct pfsync_state_1301	*sp = &ps->state;
3767 
3768 		if (sp->timeout >= PFTM_MAX) {
3769 			error = EINVAL;
3770 			break;
3771 		}
3772 		if (V_pfsync_state_import_ptr != NULL) {
3773 			PF_RULES_RLOCK();
3774 			error = V_pfsync_state_import_ptr(
3775 			    (union pfsync_state_union *)sp, PFSYNC_SI_IOCTL,
3776 			    PFSYNC_MSG_VERSION_1301);
3777 			PF_RULES_RUNLOCK();
3778 		} else
3779 			error = EOPNOTSUPP;
3780 		break;
3781 	}
3782 
3783 	case DIOCGETSTATE: {
3784 		struct pfioc_state	*ps = (struct pfioc_state *)addr;
3785 		struct pf_kstate	*s;
3786 
3787 		s = pf_find_state_byid(ps->state.id, ps->state.creatorid);
3788 		if (s == NULL) {
3789 			error = ENOENT;
3790 			break;
3791 		}
3792 
3793 		pfsync_state_export((union pfsync_state_union*)&ps->state,
3794 		    s, PFSYNC_MSG_VERSION_1301);
3795 		PF_STATE_UNLOCK(s);
3796 		break;
3797 	}
3798 
3799 	case DIOCGETSTATENV: {
3800 		error = pf_getstate((struct pfioc_nv *)addr);
3801 		break;
3802 	}
3803 
3804 #ifdef COMPAT_FREEBSD14
3805 	case DIOCGETSTATES: {
3806 		struct pfioc_states	*ps = (struct pfioc_states *)addr;
3807 		struct pf_kstate	*s;
3808 		struct pfsync_state_1301	*pstore, *p;
3809 		int			 i, nr;
3810 		size_t			 slice_count = 16, count;
3811 		void			*out;
3812 
3813 		if (ps->ps_len <= 0) {
3814 			nr = uma_zone_get_cur(V_pf_state_z);
3815 			ps->ps_len = sizeof(struct pfsync_state_1301) * nr;
3816 			break;
3817 		}
3818 
3819 		out = ps->ps_states;
3820 		pstore = mallocarray(slice_count,
3821 		    sizeof(struct pfsync_state_1301), M_TEMP, M_WAITOK | M_ZERO);
3822 		nr = 0;
3823 
3824 		for (i = 0; i <= V_pf_hashmask; i++) {
3825 			struct pf_idhash *ih = &V_pf_idhash[i];
3826 
3827 DIOCGETSTATES_retry:
3828 			p = pstore;
3829 
3830 			if (LIST_EMPTY(&ih->states))
3831 				continue;
3832 
3833 			PF_HASHROW_LOCK(ih);
3834 			count = 0;
3835 			LIST_FOREACH(s, &ih->states, entry) {
3836 				if (s->timeout == PFTM_UNLINKED)
3837 					continue;
3838 				count++;
3839 			}
3840 
3841 			if (count > slice_count) {
3842 				PF_HASHROW_UNLOCK(ih);
3843 				free(pstore, M_TEMP);
3844 				slice_count = count * 2;
3845 				pstore = mallocarray(slice_count,
3846 				    sizeof(struct pfsync_state_1301), M_TEMP,
3847 				    M_WAITOK | M_ZERO);
3848 				goto DIOCGETSTATES_retry;
3849 			}
3850 
3851 			if ((nr+count) * sizeof(*p) > ps->ps_len) {
3852 				PF_HASHROW_UNLOCK(ih);
3853 				goto DIOCGETSTATES_full;
3854 			}
3855 
3856 			LIST_FOREACH(s, &ih->states, entry) {
3857 				if (s->timeout == PFTM_UNLINKED)
3858 					continue;
3859 
3860 				pfsync_state_export((union pfsync_state_union*)p,
3861 				    s, PFSYNC_MSG_VERSION_1301);
3862 				p++;
3863 				nr++;
3864 			}
3865 			PF_HASHROW_UNLOCK(ih);
3866 			error = copyout(pstore, out,
3867 			    sizeof(struct pfsync_state_1301) * count);
3868 			if (error)
3869 				break;
3870 			out = ps->ps_states + nr;
3871 		}
3872 DIOCGETSTATES_full:
3873 		ps->ps_len = sizeof(struct pfsync_state_1301) * nr;
3874 		free(pstore, M_TEMP);
3875 
3876 		break;
3877 	}
3878 
3879 	case DIOCGETSTATESV2: {
3880 		struct pfioc_states_v2	*ps = (struct pfioc_states_v2 *)addr;
3881 		struct pf_kstate	*s;
3882 		struct pf_state_export	*pstore, *p;
3883 		int i, nr;
3884 		size_t slice_count = 16, count;
3885 		void *out;
3886 
3887 		if (ps->ps_req_version > PF_STATE_VERSION) {
3888 			error = ENOTSUP;
3889 			break;
3890 		}
3891 
3892 		if (ps->ps_len <= 0) {
3893 			nr = uma_zone_get_cur(V_pf_state_z);
3894 			ps->ps_len = sizeof(struct pf_state_export) * nr;
3895 			break;
3896 		}
3897 
3898 		out = ps->ps_states;
3899 		pstore = mallocarray(slice_count,
3900 		    sizeof(struct pf_state_export), M_TEMP, M_WAITOK | M_ZERO);
3901 		nr = 0;
3902 
3903 		for (i = 0; i <= V_pf_hashmask; i++) {
3904 			struct pf_idhash *ih = &V_pf_idhash[i];
3905 
3906 DIOCGETSTATESV2_retry:
3907 			p = pstore;
3908 
3909 			if (LIST_EMPTY(&ih->states))
3910 				continue;
3911 
3912 			PF_HASHROW_LOCK(ih);
3913 			count = 0;
3914 			LIST_FOREACH(s, &ih->states, entry) {
3915 				if (s->timeout == PFTM_UNLINKED)
3916 					continue;
3917 				count++;
3918 			}
3919 
3920 			if (count > slice_count) {
3921 				PF_HASHROW_UNLOCK(ih);
3922 				free(pstore, M_TEMP);
3923 				slice_count = count * 2;
3924 				pstore = mallocarray(slice_count,
3925 				    sizeof(struct pf_state_export), M_TEMP,
3926 				    M_WAITOK | M_ZERO);
3927 				goto DIOCGETSTATESV2_retry;
3928 			}
3929 
3930 			if ((nr+count) * sizeof(*p) > ps->ps_len) {
3931 				PF_HASHROW_UNLOCK(ih);
3932 				goto DIOCGETSTATESV2_full;
3933 			}
3934 
3935 			LIST_FOREACH(s, &ih->states, entry) {
3936 				if (s->timeout == PFTM_UNLINKED)
3937 					continue;
3938 
3939 				pf_state_export(p, s);
3940 				p++;
3941 				nr++;
3942 			}
3943 			PF_HASHROW_UNLOCK(ih);
3944 			error = copyout(pstore, out,
3945 			    sizeof(struct pf_state_export) * count);
3946 			if (error)
3947 				break;
3948 			out = ps->ps_states + nr;
3949 		}
3950 DIOCGETSTATESV2_full:
3951 		ps->ps_len = nr * sizeof(struct pf_state_export);
3952 		free(pstore, M_TEMP);
3953 
3954 		break;
3955 	}
3956 #endif
3957 	case DIOCGETSTATUSNV: {
3958 		error = pf_getstatus((struct pfioc_nv *)addr);
3959 		break;
3960 	}
3961 
3962 	case DIOCSETSTATUSIF: {
3963 		struct pfioc_if	*pi = (struct pfioc_if *)addr;
3964 
3965 		if (pi->ifname[0] == 0) {
3966 			bzero(V_pf_status.ifname, IFNAMSIZ);
3967 			break;
3968 		}
3969 		PF_RULES_WLOCK();
3970 		error = pf_user_strcpy(V_pf_status.ifname, pi->ifname, IFNAMSIZ);
3971 		PF_RULES_WUNLOCK();
3972 		break;
3973 	}
3974 
3975 	case DIOCCLRSTATUS: {
3976 		pf_ioctl_clear_status();
3977 		break;
3978 	}
3979 
3980 	case DIOCNATLOOK: {
3981 		struct pfioc_natlook	*pnl = (struct pfioc_natlook *)addr;
3982 		struct pf_state_key	*sk;
3983 		struct pf_kstate	*state;
3984 		struct pf_state_key_cmp	 key;
3985 		int			 m = 0, direction = pnl->direction;
3986 		int			 sidx, didx;
3987 
3988 		/* NATLOOK src and dst are reversed, so reverse sidx/didx */
3989 		sidx = (direction == PF_IN) ? 1 : 0;
3990 		didx = (direction == PF_IN) ? 0 : 1;
3991 
3992 		if (!pnl->proto ||
3993 		    PF_AZERO(&pnl->saddr, pnl->af) ||
3994 		    PF_AZERO(&pnl->daddr, pnl->af) ||
3995 		    ((pnl->proto == IPPROTO_TCP ||
3996 		    pnl->proto == IPPROTO_UDP) &&
3997 		    (!pnl->dport || !pnl->sport)))
3998 			error = EINVAL;
3999 		else {
4000 			bzero(&key, sizeof(key));
4001 			key.af = pnl->af;
4002 			key.proto = pnl->proto;
4003 			PF_ACPY(&key.addr[sidx], &pnl->saddr, pnl->af);
4004 			key.port[sidx] = pnl->sport;
4005 			PF_ACPY(&key.addr[didx], &pnl->daddr, pnl->af);
4006 			key.port[didx] = pnl->dport;
4007 
4008 			state = pf_find_state_all(&key, direction, &m);
4009 			if (state == NULL) {
4010 				error = ENOENT;
4011 			} else {
4012 				if (m > 1) {
4013 					PF_STATE_UNLOCK(state);
4014 					error = E2BIG;	/* more than one state */
4015 				} else {
4016 					sk = state->key[sidx];
4017 					PF_ACPY(&pnl->rsaddr, &sk->addr[sidx], sk->af);
4018 					pnl->rsport = sk->port[sidx];
4019 					PF_ACPY(&pnl->rdaddr, &sk->addr[didx], sk->af);
4020 					pnl->rdport = sk->port[didx];
4021 					PF_STATE_UNLOCK(state);
4022 				}
4023 			}
4024 		}
4025 		break;
4026 	}
4027 
4028 	case DIOCSETTIMEOUT: {
4029 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
4030 
4031 		error = pf_ioctl_set_timeout(pt->timeout, pt->seconds,
4032 		    &pt->seconds);
4033 		break;
4034 	}
4035 
4036 	case DIOCGETTIMEOUT: {
4037 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
4038 
4039 		error = pf_ioctl_get_timeout(pt->timeout, &pt->seconds);
4040 		break;
4041 	}
4042 
4043 	case DIOCGETLIMIT: {
4044 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
4045 
4046 		error = pf_ioctl_get_limit(pl->index, &pl->limit);
4047 		break;
4048 	}
4049 
4050 	case DIOCSETLIMIT: {
4051 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
4052 		unsigned int old_limit;
4053 
4054 		error = pf_ioctl_set_limit(pl->index, pl->limit, &old_limit);
4055 		pl->limit = old_limit;
4056 		break;
4057 	}
4058 
4059 	case DIOCSETDEBUG: {
4060 		u_int32_t	*level = (u_int32_t *)addr;
4061 
4062 		PF_RULES_WLOCK();
4063 		V_pf_status.debug = *level;
4064 		PF_RULES_WUNLOCK();
4065 		break;
4066 	}
4067 
4068 	case DIOCCLRRULECTRS: {
4069 		/* obsoleted by DIOCGETRULE with action=PF_GET_CLR_CNTR */
4070 		struct pf_kruleset	*ruleset = &pf_main_ruleset;
4071 		struct pf_krule		*rule;
4072 
4073 		PF_RULES_WLOCK();
4074 		TAILQ_FOREACH(rule,
4075 		    ruleset->rules[PF_RULESET_FILTER].active.ptr, entries) {
4076 			pf_counter_u64_zero(&rule->evaluations);
4077 			for (int i = 0; i < 2; i++) {
4078 				pf_counter_u64_zero(&rule->packets[i]);
4079 				pf_counter_u64_zero(&rule->bytes[i]);
4080 			}
4081 		}
4082 		PF_RULES_WUNLOCK();
4083 		break;
4084 	}
4085 
4086 	case DIOCGIFSPEEDV0:
4087 	case DIOCGIFSPEEDV1: {
4088 		struct pf_ifspeed_v1	*psp = (struct pf_ifspeed_v1 *)addr;
4089 		struct pf_ifspeed_v1	ps;
4090 		struct ifnet		*ifp;
4091 
4092 		if (psp->ifname[0] == '\0') {
4093 			error = EINVAL;
4094 			break;
4095 		}
4096 
4097 		error = pf_user_strcpy(ps.ifname, psp->ifname, IFNAMSIZ);
4098 		if (error != 0)
4099 			break;
4100 		ifp = ifunit(ps.ifname);
4101 		if (ifp != NULL) {
4102 			psp->baudrate32 =
4103 			    (u_int32_t)uqmin(ifp->if_baudrate, UINT_MAX);
4104 			if (cmd == DIOCGIFSPEEDV1)
4105 				psp->baudrate = ifp->if_baudrate;
4106 		} else {
4107 			error = EINVAL;
4108 		}
4109 		break;
4110 	}
4111 
4112 #ifdef ALTQ
4113 	case DIOCSTARTALTQ: {
4114 		struct pf_altq		*altq;
4115 
4116 		PF_RULES_WLOCK();
4117 		/* enable all altq interfaces on active list */
4118 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries) {
4119 			if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
4120 				error = pf_enable_altq(altq);
4121 				if (error != 0)
4122 					break;
4123 			}
4124 		}
4125 		if (error == 0)
4126 			V_pf_altq_running = 1;
4127 		PF_RULES_WUNLOCK();
4128 		DPFPRINTF(PF_DEBUG_MISC, ("altq: started\n"));
4129 		break;
4130 	}
4131 
4132 	case DIOCSTOPALTQ: {
4133 		struct pf_altq		*altq;
4134 
4135 		PF_RULES_WLOCK();
4136 		/* disable all altq interfaces on active list */
4137 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries) {
4138 			if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
4139 				error = pf_disable_altq(altq);
4140 				if (error != 0)
4141 					break;
4142 			}
4143 		}
4144 		if (error == 0)
4145 			V_pf_altq_running = 0;
4146 		PF_RULES_WUNLOCK();
4147 		DPFPRINTF(PF_DEBUG_MISC, ("altq: stopped\n"));
4148 		break;
4149 	}
4150 
4151 	case DIOCADDALTQV0:
4152 	case DIOCADDALTQV1: {
4153 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
4154 		struct pf_altq		*altq, *a;
4155 		struct ifnet		*ifp;
4156 
4157 		altq = malloc(sizeof(*altq), M_PFALTQ, M_WAITOK | M_ZERO);
4158 		error = pf_import_kaltq(pa, altq, IOCPARM_LEN(cmd));
4159 		if (error)
4160 			break;
4161 		altq->local_flags = 0;
4162 
4163 		PF_RULES_WLOCK();
4164 		if (pa->ticket != V_ticket_altqs_inactive) {
4165 			PF_RULES_WUNLOCK();
4166 			free(altq, M_PFALTQ);
4167 			error = EBUSY;
4168 			break;
4169 		}
4170 
4171 		/*
4172 		 * if this is for a queue, find the discipline and
4173 		 * copy the necessary fields
4174 		 */
4175 		if (altq->qname[0] != 0) {
4176 			if ((altq->qid = pf_qname2qid(altq->qname)) == 0) {
4177 				PF_RULES_WUNLOCK();
4178 				error = EBUSY;
4179 				free(altq, M_PFALTQ);
4180 				break;
4181 			}
4182 			altq->altq_disc = NULL;
4183 			TAILQ_FOREACH(a, V_pf_altq_ifs_inactive, entries) {
4184 				if (strncmp(a->ifname, altq->ifname,
4185 				    IFNAMSIZ) == 0) {
4186 					altq->altq_disc = a->altq_disc;
4187 					break;
4188 				}
4189 			}
4190 		}
4191 
4192 		if ((ifp = ifunit(altq->ifname)) == NULL)
4193 			altq->local_flags |= PFALTQ_FLAG_IF_REMOVED;
4194 		else
4195 			error = altq_add(ifp, altq);
4196 
4197 		if (error) {
4198 			PF_RULES_WUNLOCK();
4199 			free(altq, M_PFALTQ);
4200 			break;
4201 		}
4202 
4203 		if (altq->qname[0] != 0)
4204 			TAILQ_INSERT_TAIL(V_pf_altqs_inactive, altq, entries);
4205 		else
4206 			TAILQ_INSERT_TAIL(V_pf_altq_ifs_inactive, altq, entries);
4207 		/* version error check done on import above */
4208 		pf_export_kaltq(altq, pa, IOCPARM_LEN(cmd));
4209 		PF_RULES_WUNLOCK();
4210 		break;
4211 	}
4212 
4213 	case DIOCGETALTQSV0:
4214 	case DIOCGETALTQSV1: {
4215 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
4216 		struct pf_altq		*altq;
4217 
4218 		PF_RULES_RLOCK();
4219 		pa->nr = 0;
4220 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries)
4221 			pa->nr++;
4222 		TAILQ_FOREACH(altq, V_pf_altqs_active, entries)
4223 			pa->nr++;
4224 		pa->ticket = V_ticket_altqs_active;
4225 		PF_RULES_RUNLOCK();
4226 		break;
4227 	}
4228 
4229 	case DIOCGETALTQV0:
4230 	case DIOCGETALTQV1: {
4231 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
4232 		struct pf_altq		*altq;
4233 
4234 		PF_RULES_RLOCK();
4235 		if (pa->ticket != V_ticket_altqs_active) {
4236 			PF_RULES_RUNLOCK();
4237 			error = EBUSY;
4238 			break;
4239 		}
4240 		altq = pf_altq_get_nth_active(pa->nr);
4241 		if (altq == NULL) {
4242 			PF_RULES_RUNLOCK();
4243 			error = EBUSY;
4244 			break;
4245 		}
4246 		pf_export_kaltq(altq, pa, IOCPARM_LEN(cmd));
4247 		PF_RULES_RUNLOCK();
4248 		break;
4249 	}
4250 
4251 	case DIOCCHANGEALTQV0:
4252 	case DIOCCHANGEALTQV1:
4253 		/* CHANGEALTQ not supported yet! */
4254 		error = ENODEV;
4255 		break;
4256 
4257 	case DIOCGETQSTATSV0:
4258 	case DIOCGETQSTATSV1: {
4259 		struct pfioc_qstats_v1	*pq = (struct pfioc_qstats_v1 *)addr;
4260 		struct pf_altq		*altq;
4261 		int			 nbytes;
4262 		u_int32_t		 version;
4263 
4264 		PF_RULES_RLOCK();
4265 		if (pq->ticket != V_ticket_altqs_active) {
4266 			PF_RULES_RUNLOCK();
4267 			error = EBUSY;
4268 			break;
4269 		}
4270 		nbytes = pq->nbytes;
4271 		altq = pf_altq_get_nth_active(pq->nr);
4272 		if (altq == NULL) {
4273 			PF_RULES_RUNLOCK();
4274 			error = EBUSY;
4275 			break;
4276 		}
4277 
4278 		if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) != 0) {
4279 			PF_RULES_RUNLOCK();
4280 			error = ENXIO;
4281 			break;
4282 		}
4283 		PF_RULES_RUNLOCK();
4284 		if (cmd == DIOCGETQSTATSV0)
4285 			version = 0;  /* DIOCGETQSTATSV0 means stats struct v0 */
4286 		else
4287 			version = pq->version;
4288 		error = altq_getqstats(altq, pq->buf, &nbytes, version);
4289 		if (error == 0) {
4290 			pq->scheduler = altq->scheduler;
4291 			pq->nbytes = nbytes;
4292 		}
4293 		break;
4294 	}
4295 #endif /* ALTQ */
4296 
4297 	case DIOCBEGINADDRS: {
4298 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
4299 
4300 		error = pf_ioctl_begin_addrs(&pp->ticket);
4301 		break;
4302 	}
4303 
4304 	case DIOCADDADDR: {
4305 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
4306 
4307 		error = pf_ioctl_add_addr(pp);
4308 		break;
4309 	}
4310 
4311 	case DIOCGETADDRS: {
4312 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
4313 
4314 		error = pf_ioctl_get_addrs(pp);
4315 		break;
4316 	}
4317 
4318 	case DIOCGETADDR: {
4319 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
4320 
4321 		error = pf_ioctl_get_addr(pp);
4322 		break;
4323 	}
4324 
4325 	case DIOCCHANGEADDR: {
4326 		struct pfioc_pooladdr	*pca = (struct pfioc_pooladdr *)addr;
4327 		struct pf_kpool		*pool;
4328 		struct pf_kpooladdr	*oldpa = NULL, *newpa = NULL;
4329 		struct pf_kruleset	*ruleset;
4330 		struct pfi_kkif		*kif = NULL;
4331 
4332 		pca->anchor[sizeof(pca->anchor) - 1] = 0;
4333 
4334 		if (pca->action < PF_CHANGE_ADD_HEAD ||
4335 		    pca->action > PF_CHANGE_REMOVE) {
4336 			error = EINVAL;
4337 			break;
4338 		}
4339 		if (pca->addr.addr.type != PF_ADDR_ADDRMASK &&
4340 		    pca->addr.addr.type != PF_ADDR_DYNIFTL &&
4341 		    pca->addr.addr.type != PF_ADDR_TABLE) {
4342 			error = EINVAL;
4343 			break;
4344 		}
4345 		if (pca->addr.addr.p.dyn != NULL) {
4346 			error = EINVAL;
4347 			break;
4348 		}
4349 
4350 		if (pca->action != PF_CHANGE_REMOVE) {
4351 #ifndef INET
4352 			if (pca->af == AF_INET) {
4353 				error = EAFNOSUPPORT;
4354 				break;
4355 			}
4356 #endif /* INET */
4357 #ifndef INET6
4358 			if (pca->af == AF_INET6) {
4359 				error = EAFNOSUPPORT;
4360 				break;
4361 			}
4362 #endif /* INET6 */
4363 			newpa = malloc(sizeof(*newpa), M_PFRULE, M_WAITOK);
4364 			bcopy(&pca->addr, newpa, sizeof(struct pf_pooladdr));
4365 			if (newpa->ifname[0])
4366 				kif = pf_kkif_create(M_WAITOK);
4367 			newpa->kif = NULL;
4368 		}
4369 #define	ERROUT(x)	ERROUT_IOCTL(DIOCCHANGEADDR_error, x)
4370 		PF_RULES_WLOCK();
4371 		ruleset = pf_find_kruleset(pca->anchor);
4372 		if (ruleset == NULL)
4373 			ERROUT(EBUSY);
4374 
4375 		pool = pf_get_kpool(pca->anchor, pca->ticket, pca->r_action,
4376 		    pca->r_num, pca->r_last, 1, 1);
4377 		if (pool == NULL)
4378 			ERROUT(EBUSY);
4379 
4380 		if (pca->action != PF_CHANGE_REMOVE) {
4381 			if (newpa->ifname[0]) {
4382 				newpa->kif = pfi_kkif_attach(kif, newpa->ifname);
4383 				pfi_kkif_ref(newpa->kif);
4384 				kif = NULL;
4385 			}
4386 
4387 			switch (newpa->addr.type) {
4388 			case PF_ADDR_DYNIFTL:
4389 				error = pfi_dynaddr_setup(&newpa->addr,
4390 				    pca->af);
4391 				break;
4392 			case PF_ADDR_TABLE:
4393 				newpa->addr.p.tbl = pfr_attach_table(ruleset,
4394 				    newpa->addr.v.tblname);
4395 				if (newpa->addr.p.tbl == NULL)
4396 					error = ENOMEM;
4397 				break;
4398 			}
4399 			if (error)
4400 				goto DIOCCHANGEADDR_error;
4401 		}
4402 
4403 		switch (pca->action) {
4404 		case PF_CHANGE_ADD_HEAD:
4405 			oldpa = TAILQ_FIRST(&pool->list);
4406 			break;
4407 		case PF_CHANGE_ADD_TAIL:
4408 			oldpa = TAILQ_LAST(&pool->list, pf_kpalist);
4409 			break;
4410 		default:
4411 			oldpa = TAILQ_FIRST(&pool->list);
4412 			for (int i = 0; oldpa && i < pca->nr; i++)
4413 				oldpa = TAILQ_NEXT(oldpa, entries);
4414 
4415 			if (oldpa == NULL)
4416 				ERROUT(EINVAL);
4417 		}
4418 
4419 		if (pca->action == PF_CHANGE_REMOVE) {
4420 			TAILQ_REMOVE(&pool->list, oldpa, entries);
4421 			switch (oldpa->addr.type) {
4422 			case PF_ADDR_DYNIFTL:
4423 				pfi_dynaddr_remove(oldpa->addr.p.dyn);
4424 				break;
4425 			case PF_ADDR_TABLE:
4426 				pfr_detach_table(oldpa->addr.p.tbl);
4427 				break;
4428 			}
4429 			if (oldpa->kif)
4430 				pfi_kkif_unref(oldpa->kif);
4431 			free(oldpa, M_PFRULE);
4432 		} else {
4433 			if (oldpa == NULL)
4434 				TAILQ_INSERT_TAIL(&pool->list, newpa, entries);
4435 			else if (pca->action == PF_CHANGE_ADD_HEAD ||
4436 			    pca->action == PF_CHANGE_ADD_BEFORE)
4437 				TAILQ_INSERT_BEFORE(oldpa, newpa, entries);
4438 			else
4439 				TAILQ_INSERT_AFTER(&pool->list, oldpa,
4440 				    newpa, entries);
4441 		}
4442 
4443 		pool->cur = TAILQ_FIRST(&pool->list);
4444 		PF_ACPY(&pool->counter, &pool->cur->addr.v.a.addr, pca->af);
4445 		PF_RULES_WUNLOCK();
4446 		break;
4447 
4448 #undef ERROUT
4449 DIOCCHANGEADDR_error:
4450 		if (newpa != NULL) {
4451 			if (newpa->kif)
4452 				pfi_kkif_unref(newpa->kif);
4453 			free(newpa, M_PFRULE);
4454 		}
4455 		PF_RULES_WUNLOCK();
4456 		pf_kkif_free(kif);
4457 		break;
4458 	}
4459 
4460 	case DIOCGETRULESETS: {
4461 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
4462 		struct pf_kruleset	*ruleset;
4463 		struct pf_kanchor	*anchor;
4464 
4465 		pr->path[sizeof(pr->path) - 1] = 0;
4466 
4467 		PF_RULES_RLOCK();
4468 		if ((ruleset = pf_find_kruleset(pr->path)) == NULL) {
4469 			PF_RULES_RUNLOCK();
4470 			error = ENOENT;
4471 			break;
4472 		}
4473 		pr->nr = 0;
4474 		if (ruleset->anchor == NULL) {
4475 			/* XXX kludge for pf_main_ruleset */
4476 			RB_FOREACH(anchor, pf_kanchor_global, &V_pf_anchors)
4477 				if (anchor->parent == NULL)
4478 					pr->nr++;
4479 		} else {
4480 			RB_FOREACH(anchor, pf_kanchor_node,
4481 			    &ruleset->anchor->children)
4482 				pr->nr++;
4483 		}
4484 		PF_RULES_RUNLOCK();
4485 		break;
4486 	}
4487 
4488 	case DIOCGETRULESET: {
4489 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
4490 		struct pf_kruleset	*ruleset;
4491 		struct pf_kanchor	*anchor;
4492 		u_int32_t		 nr = 0;
4493 
4494 		pr->path[sizeof(pr->path) - 1] = 0;
4495 
4496 		PF_RULES_RLOCK();
4497 		if ((ruleset = pf_find_kruleset(pr->path)) == NULL) {
4498 			PF_RULES_RUNLOCK();
4499 			error = ENOENT;
4500 			break;
4501 		}
4502 		pr->name[0] = 0;
4503 		if (ruleset->anchor == NULL) {
4504 			/* XXX kludge for pf_main_ruleset */
4505 			RB_FOREACH(anchor, pf_kanchor_global, &V_pf_anchors)
4506 				if (anchor->parent == NULL && nr++ == pr->nr) {
4507 					strlcpy(pr->name, anchor->name,
4508 					    sizeof(pr->name));
4509 					break;
4510 				}
4511 		} else {
4512 			RB_FOREACH(anchor, pf_kanchor_node,
4513 			    &ruleset->anchor->children)
4514 				if (nr++ == pr->nr) {
4515 					strlcpy(pr->name, anchor->name,
4516 					    sizeof(pr->name));
4517 					break;
4518 				}
4519 		}
4520 		if (!pr->name[0])
4521 			error = EBUSY;
4522 		PF_RULES_RUNLOCK();
4523 		break;
4524 	}
4525 
4526 	case DIOCRCLRTABLES: {
4527 		struct pfioc_table *io = (struct pfioc_table *)addr;
4528 
4529 		if (io->pfrio_esize != 0) {
4530 			error = ENODEV;
4531 			break;
4532 		}
4533 		PF_RULES_WLOCK();
4534 		error = pfr_clr_tables(&io->pfrio_table, &io->pfrio_ndel,
4535 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
4536 		PF_RULES_WUNLOCK();
4537 		break;
4538 	}
4539 
4540 	case DIOCRADDTABLES: {
4541 		struct pfioc_table *io = (struct pfioc_table *)addr;
4542 		struct pfr_table *pfrts;
4543 		size_t totlen;
4544 
4545 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
4546 			error = ENODEV;
4547 			break;
4548 		}
4549 
4550 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
4551 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
4552 			error = ENOMEM;
4553 			break;
4554 		}
4555 
4556 		totlen = io->pfrio_size * sizeof(struct pfr_table);
4557 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
4558 		    M_TEMP, M_WAITOK);
4559 		error = copyin(io->pfrio_buffer, pfrts, totlen);
4560 		if (error) {
4561 			free(pfrts, M_TEMP);
4562 			break;
4563 		}
4564 		PF_RULES_WLOCK();
4565 		error = pfr_add_tables(pfrts, io->pfrio_size,
4566 		    &io->pfrio_nadd, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4567 		PF_RULES_WUNLOCK();
4568 		free(pfrts, M_TEMP);
4569 		break;
4570 	}
4571 
4572 	case DIOCRDELTABLES: {
4573 		struct pfioc_table *io = (struct pfioc_table *)addr;
4574 		struct pfr_table *pfrts;
4575 		size_t totlen;
4576 
4577 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
4578 			error = ENODEV;
4579 			break;
4580 		}
4581 
4582 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
4583 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
4584 			error = ENOMEM;
4585 			break;
4586 		}
4587 
4588 		totlen = io->pfrio_size * sizeof(struct pfr_table);
4589 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
4590 		    M_TEMP, M_WAITOK);
4591 		error = copyin(io->pfrio_buffer, pfrts, totlen);
4592 		if (error) {
4593 			free(pfrts, M_TEMP);
4594 			break;
4595 		}
4596 		PF_RULES_WLOCK();
4597 		error = pfr_del_tables(pfrts, io->pfrio_size,
4598 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4599 		PF_RULES_WUNLOCK();
4600 		free(pfrts, M_TEMP);
4601 		break;
4602 	}
4603 
4604 	case DIOCRGETTABLES: {
4605 		struct pfioc_table *io = (struct pfioc_table *)addr;
4606 		struct pfr_table *pfrts;
4607 		size_t totlen;
4608 		int n;
4609 
4610 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
4611 			error = ENODEV;
4612 			break;
4613 		}
4614 		PF_RULES_RLOCK();
4615 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
4616 		if (n < 0) {
4617 			PF_RULES_RUNLOCK();
4618 			error = EINVAL;
4619 			break;
4620 		}
4621 		io->pfrio_size = min(io->pfrio_size, n);
4622 
4623 		totlen = io->pfrio_size * sizeof(struct pfr_table);
4624 
4625 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
4626 		    M_TEMP, M_NOWAIT | M_ZERO);
4627 		if (pfrts == NULL) {
4628 			error = ENOMEM;
4629 			PF_RULES_RUNLOCK();
4630 			break;
4631 		}
4632 		error = pfr_get_tables(&io->pfrio_table, pfrts,
4633 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4634 		PF_RULES_RUNLOCK();
4635 		if (error == 0)
4636 			error = copyout(pfrts, io->pfrio_buffer, totlen);
4637 		free(pfrts, M_TEMP);
4638 		break;
4639 	}
4640 
4641 	case DIOCRGETTSTATS: {
4642 		struct pfioc_table *io = (struct pfioc_table *)addr;
4643 		struct pfr_tstats *pfrtstats;
4644 		size_t totlen;
4645 		int n;
4646 
4647 		if (io->pfrio_esize != sizeof(struct pfr_tstats)) {
4648 			error = ENODEV;
4649 			break;
4650 		}
4651 		PF_TABLE_STATS_LOCK();
4652 		PF_RULES_RLOCK();
4653 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
4654 		if (n < 0) {
4655 			PF_RULES_RUNLOCK();
4656 			PF_TABLE_STATS_UNLOCK();
4657 			error = EINVAL;
4658 			break;
4659 		}
4660 		io->pfrio_size = min(io->pfrio_size, n);
4661 
4662 		totlen = io->pfrio_size * sizeof(struct pfr_tstats);
4663 		pfrtstats = mallocarray(io->pfrio_size,
4664 		    sizeof(struct pfr_tstats), M_TEMP, M_NOWAIT | M_ZERO);
4665 		if (pfrtstats == NULL) {
4666 			error = ENOMEM;
4667 			PF_RULES_RUNLOCK();
4668 			PF_TABLE_STATS_UNLOCK();
4669 			break;
4670 		}
4671 		error = pfr_get_tstats(&io->pfrio_table, pfrtstats,
4672 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4673 		PF_RULES_RUNLOCK();
4674 		PF_TABLE_STATS_UNLOCK();
4675 		if (error == 0)
4676 			error = copyout(pfrtstats, io->pfrio_buffer, totlen);
4677 		free(pfrtstats, M_TEMP);
4678 		break;
4679 	}
4680 
4681 	case DIOCRCLRTSTATS: {
4682 		struct pfioc_table *io = (struct pfioc_table *)addr;
4683 		struct pfr_table *pfrts;
4684 		size_t totlen;
4685 
4686 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
4687 			error = ENODEV;
4688 			break;
4689 		}
4690 
4691 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
4692 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
4693 			/* We used to count tables and use the minimum required
4694 			 * size, so we didn't fail on overly large requests.
4695 			 * Keep doing so. */
4696 			io->pfrio_size = pf_ioctl_maxcount;
4697 			break;
4698 		}
4699 
4700 		totlen = io->pfrio_size * sizeof(struct pfr_table);
4701 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
4702 		    M_TEMP, M_WAITOK);
4703 		error = copyin(io->pfrio_buffer, pfrts, totlen);
4704 		if (error) {
4705 			free(pfrts, M_TEMP);
4706 			break;
4707 		}
4708 
4709 		PF_TABLE_STATS_LOCK();
4710 		PF_RULES_RLOCK();
4711 		error = pfr_clr_tstats(pfrts, io->pfrio_size,
4712 		    &io->pfrio_nzero, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4713 		PF_RULES_RUNLOCK();
4714 		PF_TABLE_STATS_UNLOCK();
4715 		free(pfrts, M_TEMP);
4716 		break;
4717 	}
4718 
4719 	case DIOCRSETTFLAGS: {
4720 		struct pfioc_table *io = (struct pfioc_table *)addr;
4721 		struct pfr_table *pfrts;
4722 		size_t totlen;
4723 		int n;
4724 
4725 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
4726 			error = ENODEV;
4727 			break;
4728 		}
4729 
4730 		PF_RULES_RLOCK();
4731 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
4732 		if (n < 0) {
4733 			PF_RULES_RUNLOCK();
4734 			error = EINVAL;
4735 			break;
4736 		}
4737 
4738 		io->pfrio_size = min(io->pfrio_size, n);
4739 		PF_RULES_RUNLOCK();
4740 
4741 		totlen = io->pfrio_size * sizeof(struct pfr_table);
4742 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
4743 		    M_TEMP, M_WAITOK);
4744 		error = copyin(io->pfrio_buffer, pfrts, totlen);
4745 		if (error) {
4746 			free(pfrts, M_TEMP);
4747 			break;
4748 		}
4749 		PF_RULES_WLOCK();
4750 		error = pfr_set_tflags(pfrts, io->pfrio_size,
4751 		    io->pfrio_setflag, io->pfrio_clrflag, &io->pfrio_nchange,
4752 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4753 		PF_RULES_WUNLOCK();
4754 		free(pfrts, M_TEMP);
4755 		break;
4756 	}
4757 
4758 	case DIOCRCLRADDRS: {
4759 		struct pfioc_table *io = (struct pfioc_table *)addr;
4760 
4761 		if (io->pfrio_esize != 0) {
4762 			error = ENODEV;
4763 			break;
4764 		}
4765 		PF_RULES_WLOCK();
4766 		error = pfr_clr_addrs(&io->pfrio_table, &io->pfrio_ndel,
4767 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
4768 		PF_RULES_WUNLOCK();
4769 		break;
4770 	}
4771 
4772 	case DIOCRADDADDRS: {
4773 		struct pfioc_table *io = (struct pfioc_table *)addr;
4774 		struct pfr_addr *pfras;
4775 		size_t totlen;
4776 
4777 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4778 			error = ENODEV;
4779 			break;
4780 		}
4781 		if (io->pfrio_size < 0 ||
4782 		    io->pfrio_size > pf_ioctl_maxcount ||
4783 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4784 			error = EINVAL;
4785 			break;
4786 		}
4787 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4788 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4789 		    M_TEMP, M_WAITOK);
4790 		error = copyin(io->pfrio_buffer, pfras, totlen);
4791 		if (error) {
4792 			free(pfras, M_TEMP);
4793 			break;
4794 		}
4795 		PF_RULES_WLOCK();
4796 		error = pfr_add_addrs(&io->pfrio_table, pfras,
4797 		    io->pfrio_size, &io->pfrio_nadd, io->pfrio_flags |
4798 		    PFR_FLAG_USERIOCTL);
4799 		PF_RULES_WUNLOCK();
4800 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4801 			error = copyout(pfras, io->pfrio_buffer, totlen);
4802 		free(pfras, M_TEMP);
4803 		break;
4804 	}
4805 
4806 	case DIOCRDELADDRS: {
4807 		struct pfioc_table *io = (struct pfioc_table *)addr;
4808 		struct pfr_addr *pfras;
4809 		size_t totlen;
4810 
4811 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4812 			error = ENODEV;
4813 			break;
4814 		}
4815 		if (io->pfrio_size < 0 ||
4816 		    io->pfrio_size > pf_ioctl_maxcount ||
4817 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4818 			error = EINVAL;
4819 			break;
4820 		}
4821 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4822 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4823 		    M_TEMP, M_WAITOK);
4824 		error = copyin(io->pfrio_buffer, pfras, totlen);
4825 		if (error) {
4826 			free(pfras, M_TEMP);
4827 			break;
4828 		}
4829 		PF_RULES_WLOCK();
4830 		error = pfr_del_addrs(&io->pfrio_table, pfras,
4831 		    io->pfrio_size, &io->pfrio_ndel, io->pfrio_flags |
4832 		    PFR_FLAG_USERIOCTL);
4833 		PF_RULES_WUNLOCK();
4834 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4835 			error = copyout(pfras, io->pfrio_buffer, totlen);
4836 		free(pfras, M_TEMP);
4837 		break;
4838 	}
4839 
4840 	case DIOCRSETADDRS: {
4841 		struct pfioc_table *io = (struct pfioc_table *)addr;
4842 		struct pfr_addr *pfras;
4843 		size_t totlen, count;
4844 
4845 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4846 			error = ENODEV;
4847 			break;
4848 		}
4849 		if (io->pfrio_size < 0 || io->pfrio_size2 < 0) {
4850 			error = EINVAL;
4851 			break;
4852 		}
4853 		count = max(io->pfrio_size, io->pfrio_size2);
4854 		if (count > pf_ioctl_maxcount ||
4855 		    WOULD_OVERFLOW(count, sizeof(struct pfr_addr))) {
4856 			error = EINVAL;
4857 			break;
4858 		}
4859 		totlen = count * sizeof(struct pfr_addr);
4860 		pfras = mallocarray(count, sizeof(struct pfr_addr), M_TEMP,
4861 		    M_WAITOK);
4862 		error = copyin(io->pfrio_buffer, pfras, totlen);
4863 		if (error) {
4864 			free(pfras, M_TEMP);
4865 			break;
4866 		}
4867 		PF_RULES_WLOCK();
4868 		error = pfr_set_addrs(&io->pfrio_table, pfras,
4869 		    io->pfrio_size, &io->pfrio_size2, &io->pfrio_nadd,
4870 		    &io->pfrio_ndel, &io->pfrio_nchange, io->pfrio_flags |
4871 		    PFR_FLAG_USERIOCTL, 0);
4872 		PF_RULES_WUNLOCK();
4873 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4874 			error = copyout(pfras, io->pfrio_buffer, totlen);
4875 		free(pfras, M_TEMP);
4876 		break;
4877 	}
4878 
4879 	case DIOCRGETADDRS: {
4880 		struct pfioc_table *io = (struct pfioc_table *)addr;
4881 		struct pfr_addr *pfras;
4882 		size_t totlen;
4883 
4884 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4885 			error = ENODEV;
4886 			break;
4887 		}
4888 		if (io->pfrio_size < 0 ||
4889 		    io->pfrio_size > pf_ioctl_maxcount ||
4890 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4891 			error = EINVAL;
4892 			break;
4893 		}
4894 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4895 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4896 		    M_TEMP, M_WAITOK | M_ZERO);
4897 		PF_RULES_RLOCK();
4898 		error = pfr_get_addrs(&io->pfrio_table, pfras,
4899 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4900 		PF_RULES_RUNLOCK();
4901 		if (error == 0)
4902 			error = copyout(pfras, io->pfrio_buffer, totlen);
4903 		free(pfras, M_TEMP);
4904 		break;
4905 	}
4906 
4907 	case DIOCRGETASTATS: {
4908 		struct pfioc_table *io = (struct pfioc_table *)addr;
4909 		struct pfr_astats *pfrastats;
4910 		size_t totlen;
4911 
4912 		if (io->pfrio_esize != sizeof(struct pfr_astats)) {
4913 			error = ENODEV;
4914 			break;
4915 		}
4916 		if (io->pfrio_size < 0 ||
4917 		    io->pfrio_size > pf_ioctl_maxcount ||
4918 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_astats))) {
4919 			error = EINVAL;
4920 			break;
4921 		}
4922 		totlen = io->pfrio_size * sizeof(struct pfr_astats);
4923 		pfrastats = mallocarray(io->pfrio_size,
4924 		    sizeof(struct pfr_astats), M_TEMP, M_WAITOK | M_ZERO);
4925 		PF_RULES_RLOCK();
4926 		error = pfr_get_astats(&io->pfrio_table, pfrastats,
4927 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4928 		PF_RULES_RUNLOCK();
4929 		if (error == 0)
4930 			error = copyout(pfrastats, io->pfrio_buffer, totlen);
4931 		free(pfrastats, M_TEMP);
4932 		break;
4933 	}
4934 
4935 	case DIOCRCLRASTATS: {
4936 		struct pfioc_table *io = (struct pfioc_table *)addr;
4937 		struct pfr_addr *pfras;
4938 		size_t totlen;
4939 
4940 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4941 			error = ENODEV;
4942 			break;
4943 		}
4944 		if (io->pfrio_size < 0 ||
4945 		    io->pfrio_size > pf_ioctl_maxcount ||
4946 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4947 			error = EINVAL;
4948 			break;
4949 		}
4950 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4951 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4952 		    M_TEMP, M_WAITOK);
4953 		error = copyin(io->pfrio_buffer, pfras, totlen);
4954 		if (error) {
4955 			free(pfras, M_TEMP);
4956 			break;
4957 		}
4958 		PF_RULES_WLOCK();
4959 		error = pfr_clr_astats(&io->pfrio_table, pfras,
4960 		    io->pfrio_size, &io->pfrio_nzero, io->pfrio_flags |
4961 		    PFR_FLAG_USERIOCTL);
4962 		PF_RULES_WUNLOCK();
4963 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4964 			error = copyout(pfras, io->pfrio_buffer, totlen);
4965 		free(pfras, M_TEMP);
4966 		break;
4967 	}
4968 
4969 	case DIOCRTSTADDRS: {
4970 		struct pfioc_table *io = (struct pfioc_table *)addr;
4971 		struct pfr_addr *pfras;
4972 		size_t totlen;
4973 
4974 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4975 			error = ENODEV;
4976 			break;
4977 		}
4978 		if (io->pfrio_size < 0 ||
4979 		    io->pfrio_size > pf_ioctl_maxcount ||
4980 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4981 			error = EINVAL;
4982 			break;
4983 		}
4984 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4985 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4986 		    M_TEMP, M_WAITOK);
4987 		error = copyin(io->pfrio_buffer, pfras, totlen);
4988 		if (error) {
4989 			free(pfras, M_TEMP);
4990 			break;
4991 		}
4992 		PF_RULES_RLOCK();
4993 		error = pfr_tst_addrs(&io->pfrio_table, pfras,
4994 		    io->pfrio_size, &io->pfrio_nmatch, io->pfrio_flags |
4995 		    PFR_FLAG_USERIOCTL);
4996 		PF_RULES_RUNLOCK();
4997 		if (error == 0)
4998 			error = copyout(pfras, io->pfrio_buffer, totlen);
4999 		free(pfras, M_TEMP);
5000 		break;
5001 	}
5002 
5003 	case DIOCRINADEFINE: {
5004 		struct pfioc_table *io = (struct pfioc_table *)addr;
5005 		struct pfr_addr *pfras;
5006 		size_t totlen;
5007 
5008 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
5009 			error = ENODEV;
5010 			break;
5011 		}
5012 		if (io->pfrio_size < 0 ||
5013 		    io->pfrio_size > pf_ioctl_maxcount ||
5014 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
5015 			error = EINVAL;
5016 			break;
5017 		}
5018 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
5019 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
5020 		    M_TEMP, M_WAITOK);
5021 		error = copyin(io->pfrio_buffer, pfras, totlen);
5022 		if (error) {
5023 			free(pfras, M_TEMP);
5024 			break;
5025 		}
5026 		PF_RULES_WLOCK();
5027 		error = pfr_ina_define(&io->pfrio_table, pfras,
5028 		    io->pfrio_size, &io->pfrio_nadd, &io->pfrio_naddr,
5029 		    io->pfrio_ticket, io->pfrio_flags | PFR_FLAG_USERIOCTL);
5030 		PF_RULES_WUNLOCK();
5031 		free(pfras, M_TEMP);
5032 		break;
5033 	}
5034 
5035 	case DIOCOSFPADD: {
5036 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
5037 		PF_RULES_WLOCK();
5038 		error = pf_osfp_add(io);
5039 		PF_RULES_WUNLOCK();
5040 		break;
5041 	}
5042 
5043 	case DIOCOSFPGET: {
5044 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
5045 		PF_RULES_RLOCK();
5046 		error = pf_osfp_get(io);
5047 		PF_RULES_RUNLOCK();
5048 		break;
5049 	}
5050 
5051 	case DIOCXBEGIN: {
5052 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
5053 		struct pfioc_trans_e	*ioes, *ioe;
5054 		size_t			 totlen;
5055 		int			 i;
5056 
5057 		if (io->esize != sizeof(*ioe)) {
5058 			error = ENODEV;
5059 			break;
5060 		}
5061 		if (io->size < 0 ||
5062 		    io->size > pf_ioctl_maxcount ||
5063 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
5064 			error = EINVAL;
5065 			break;
5066 		}
5067 		totlen = sizeof(struct pfioc_trans_e) * io->size;
5068 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
5069 		    M_TEMP, M_WAITOK);
5070 		error = copyin(io->array, ioes, totlen);
5071 		if (error) {
5072 			free(ioes, M_TEMP);
5073 			break;
5074 		}
5075 		/* Ensure there's no more ethernet rules to clean up. */
5076 		NET_EPOCH_DRAIN_CALLBACKS();
5077 		PF_RULES_WLOCK();
5078 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
5079 			ioe->anchor[sizeof(ioe->anchor) - 1] = '\0';
5080 			switch (ioe->rs_num) {
5081 			case PF_RULESET_ETH:
5082 				if ((error = pf_begin_eth(&ioe->ticket, ioe->anchor))) {
5083 					PF_RULES_WUNLOCK();
5084 					free(ioes, M_TEMP);
5085 					goto fail;
5086 				}
5087 				break;
5088 #ifdef ALTQ
5089 			case PF_RULESET_ALTQ:
5090 				if (ioe->anchor[0]) {
5091 					PF_RULES_WUNLOCK();
5092 					free(ioes, M_TEMP);
5093 					error = EINVAL;
5094 					goto fail;
5095 				}
5096 				if ((error = pf_begin_altq(&ioe->ticket))) {
5097 					PF_RULES_WUNLOCK();
5098 					free(ioes, M_TEMP);
5099 					goto fail;
5100 				}
5101 				break;
5102 #endif /* ALTQ */
5103 			case PF_RULESET_TABLE:
5104 			    {
5105 				struct pfr_table table;
5106 
5107 				bzero(&table, sizeof(table));
5108 				strlcpy(table.pfrt_anchor, ioe->anchor,
5109 				    sizeof(table.pfrt_anchor));
5110 				if ((error = pfr_ina_begin(&table,
5111 				    &ioe->ticket, NULL, 0))) {
5112 					PF_RULES_WUNLOCK();
5113 					free(ioes, M_TEMP);
5114 					goto fail;
5115 				}
5116 				break;
5117 			    }
5118 			default:
5119 				if ((error = pf_begin_rules(&ioe->ticket,
5120 				    ioe->rs_num, ioe->anchor))) {
5121 					PF_RULES_WUNLOCK();
5122 					free(ioes, M_TEMP);
5123 					goto fail;
5124 				}
5125 				break;
5126 			}
5127 		}
5128 		PF_RULES_WUNLOCK();
5129 		error = copyout(ioes, io->array, totlen);
5130 		free(ioes, M_TEMP);
5131 		break;
5132 	}
5133 
5134 	case DIOCXROLLBACK: {
5135 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
5136 		struct pfioc_trans_e	*ioe, *ioes;
5137 		size_t			 totlen;
5138 		int			 i;
5139 
5140 		if (io->esize != sizeof(*ioe)) {
5141 			error = ENODEV;
5142 			break;
5143 		}
5144 		if (io->size < 0 ||
5145 		    io->size > pf_ioctl_maxcount ||
5146 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
5147 			error = EINVAL;
5148 			break;
5149 		}
5150 		totlen = sizeof(struct pfioc_trans_e) * io->size;
5151 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
5152 		    M_TEMP, M_WAITOK);
5153 		error = copyin(io->array, ioes, totlen);
5154 		if (error) {
5155 			free(ioes, M_TEMP);
5156 			break;
5157 		}
5158 		PF_RULES_WLOCK();
5159 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
5160 			ioe->anchor[sizeof(ioe->anchor) - 1] = '\0';
5161 			switch (ioe->rs_num) {
5162 			case PF_RULESET_ETH:
5163 				if ((error = pf_rollback_eth(ioe->ticket,
5164 				    ioe->anchor))) {
5165 					PF_RULES_WUNLOCK();
5166 					free(ioes, M_TEMP);
5167 					goto fail; /* really bad */
5168 				}
5169 				break;
5170 #ifdef ALTQ
5171 			case PF_RULESET_ALTQ:
5172 				if (ioe->anchor[0]) {
5173 					PF_RULES_WUNLOCK();
5174 					free(ioes, M_TEMP);
5175 					error = EINVAL;
5176 					goto fail;
5177 				}
5178 				if ((error = pf_rollback_altq(ioe->ticket))) {
5179 					PF_RULES_WUNLOCK();
5180 					free(ioes, M_TEMP);
5181 					goto fail; /* really bad */
5182 				}
5183 				break;
5184 #endif /* ALTQ */
5185 			case PF_RULESET_TABLE:
5186 			    {
5187 				struct pfr_table table;
5188 
5189 				bzero(&table, sizeof(table));
5190 				strlcpy(table.pfrt_anchor, ioe->anchor,
5191 				    sizeof(table.pfrt_anchor));
5192 				if ((error = pfr_ina_rollback(&table,
5193 				    ioe->ticket, NULL, 0))) {
5194 					PF_RULES_WUNLOCK();
5195 					free(ioes, M_TEMP);
5196 					goto fail; /* really bad */
5197 				}
5198 				break;
5199 			    }
5200 			default:
5201 				if ((error = pf_rollback_rules(ioe->ticket,
5202 				    ioe->rs_num, ioe->anchor))) {
5203 					PF_RULES_WUNLOCK();
5204 					free(ioes, M_TEMP);
5205 					goto fail; /* really bad */
5206 				}
5207 				break;
5208 			}
5209 		}
5210 		PF_RULES_WUNLOCK();
5211 		free(ioes, M_TEMP);
5212 		break;
5213 	}
5214 
5215 	case DIOCXCOMMIT: {
5216 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
5217 		struct pfioc_trans_e	*ioe, *ioes;
5218 		struct pf_kruleset	*rs;
5219 		struct pf_keth_ruleset	*ers;
5220 		size_t			 totlen;
5221 		int			 i;
5222 
5223 		if (io->esize != sizeof(*ioe)) {
5224 			error = ENODEV;
5225 			break;
5226 		}
5227 
5228 		if (io->size < 0 ||
5229 		    io->size > pf_ioctl_maxcount ||
5230 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
5231 			error = EINVAL;
5232 			break;
5233 		}
5234 
5235 		totlen = sizeof(struct pfioc_trans_e) * io->size;
5236 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
5237 		    M_TEMP, M_WAITOK);
5238 		error = copyin(io->array, ioes, totlen);
5239 		if (error) {
5240 			free(ioes, M_TEMP);
5241 			break;
5242 		}
5243 		PF_RULES_WLOCK();
5244 		/* First makes sure everything will succeed. */
5245 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
5246 			ioe->anchor[sizeof(ioe->anchor) - 1] = 0;
5247 			switch (ioe->rs_num) {
5248 			case PF_RULESET_ETH:
5249 				ers = pf_find_keth_ruleset(ioe->anchor);
5250 				if (ers == NULL || ioe->ticket == 0 ||
5251 				    ioe->ticket != ers->inactive.ticket) {
5252 					PF_RULES_WUNLOCK();
5253 					free(ioes, M_TEMP);
5254 					error = EINVAL;
5255 					goto fail;
5256 				}
5257 				break;
5258 #ifdef ALTQ
5259 			case PF_RULESET_ALTQ:
5260 				if (ioe->anchor[0]) {
5261 					PF_RULES_WUNLOCK();
5262 					free(ioes, M_TEMP);
5263 					error = EINVAL;
5264 					goto fail;
5265 				}
5266 				if (!V_altqs_inactive_open || ioe->ticket !=
5267 				    V_ticket_altqs_inactive) {
5268 					PF_RULES_WUNLOCK();
5269 					free(ioes, M_TEMP);
5270 					error = EBUSY;
5271 					goto fail;
5272 				}
5273 				break;
5274 #endif /* ALTQ */
5275 			case PF_RULESET_TABLE:
5276 				rs = pf_find_kruleset(ioe->anchor);
5277 				if (rs == NULL || !rs->topen || ioe->ticket !=
5278 				    rs->tticket) {
5279 					PF_RULES_WUNLOCK();
5280 					free(ioes, M_TEMP);
5281 					error = EBUSY;
5282 					goto fail;
5283 				}
5284 				break;
5285 			default:
5286 				if (ioe->rs_num < 0 || ioe->rs_num >=
5287 				    PF_RULESET_MAX) {
5288 					PF_RULES_WUNLOCK();
5289 					free(ioes, M_TEMP);
5290 					error = EINVAL;
5291 					goto fail;
5292 				}
5293 				rs = pf_find_kruleset(ioe->anchor);
5294 				if (rs == NULL ||
5295 				    !rs->rules[ioe->rs_num].inactive.open ||
5296 				    rs->rules[ioe->rs_num].inactive.ticket !=
5297 				    ioe->ticket) {
5298 					PF_RULES_WUNLOCK();
5299 					free(ioes, M_TEMP);
5300 					error = EBUSY;
5301 					goto fail;
5302 				}
5303 				break;
5304 			}
5305 		}
5306 		/* Now do the commit - no errors should happen here. */
5307 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
5308 			switch (ioe->rs_num) {
5309 			case PF_RULESET_ETH:
5310 				if ((error = pf_commit_eth(ioe->ticket, ioe->anchor))) {
5311 					PF_RULES_WUNLOCK();
5312 					free(ioes, M_TEMP);
5313 					goto fail; /* really bad */
5314 				}
5315 				break;
5316 #ifdef ALTQ
5317 			case PF_RULESET_ALTQ:
5318 				if ((error = pf_commit_altq(ioe->ticket))) {
5319 					PF_RULES_WUNLOCK();
5320 					free(ioes, M_TEMP);
5321 					goto fail; /* really bad */
5322 				}
5323 				break;
5324 #endif /* ALTQ */
5325 			case PF_RULESET_TABLE:
5326 			    {
5327 				struct pfr_table table;
5328 
5329 				bzero(&table, sizeof(table));
5330 				(void)strlcpy(table.pfrt_anchor, ioe->anchor,
5331 				    sizeof(table.pfrt_anchor));
5332 				if ((error = pfr_ina_commit(&table,
5333 				    ioe->ticket, NULL, NULL, 0))) {
5334 					PF_RULES_WUNLOCK();
5335 					free(ioes, M_TEMP);
5336 					goto fail; /* really bad */
5337 				}
5338 				break;
5339 			    }
5340 			default:
5341 				if ((error = pf_commit_rules(ioe->ticket,
5342 				    ioe->rs_num, ioe->anchor))) {
5343 					PF_RULES_WUNLOCK();
5344 					free(ioes, M_TEMP);
5345 					goto fail; /* really bad */
5346 				}
5347 				break;
5348 			}
5349 		}
5350 		PF_RULES_WUNLOCK();
5351 
5352 		/* Only hook into EtherNet taffic if we've got rules for it. */
5353 		if (! TAILQ_EMPTY(V_pf_keth->active.rules))
5354 			hook_pf_eth();
5355 		else
5356 			dehook_pf_eth();
5357 
5358 		free(ioes, M_TEMP);
5359 		break;
5360 	}
5361 
5362 	case DIOCGETSRCNODES: {
5363 		struct pfioc_src_nodes	*psn = (struct pfioc_src_nodes *)addr;
5364 		struct pf_srchash	*sh;
5365 		struct pf_ksrc_node	*n;
5366 		struct pf_src_node	*p, *pstore;
5367 		uint32_t		 i, nr = 0;
5368 
5369 		for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask;
5370 				i++, sh++) {
5371 			PF_HASHROW_LOCK(sh);
5372 			LIST_FOREACH(n, &sh->nodes, entry)
5373 				nr++;
5374 			PF_HASHROW_UNLOCK(sh);
5375 		}
5376 
5377 		psn->psn_len = min(psn->psn_len,
5378 		    sizeof(struct pf_src_node) * nr);
5379 
5380 		if (psn->psn_len == 0) {
5381 			psn->psn_len = sizeof(struct pf_src_node) * nr;
5382 			break;
5383 		}
5384 
5385 		nr = 0;
5386 
5387 		p = pstore = malloc(psn->psn_len, M_TEMP, M_WAITOK | M_ZERO);
5388 		for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask;
5389 		    i++, sh++) {
5390 		    PF_HASHROW_LOCK(sh);
5391 		    LIST_FOREACH(n, &sh->nodes, entry) {
5392 
5393 			if ((nr + 1) * sizeof(*p) > (unsigned)psn->psn_len)
5394 				break;
5395 
5396 			pf_src_node_copy(n, p);
5397 
5398 			p++;
5399 			nr++;
5400 		    }
5401 		    PF_HASHROW_UNLOCK(sh);
5402 		}
5403 		error = copyout(pstore, psn->psn_src_nodes,
5404 		    sizeof(struct pf_src_node) * nr);
5405 		if (error) {
5406 			free(pstore, M_TEMP);
5407 			break;
5408 		}
5409 		psn->psn_len = sizeof(struct pf_src_node) * nr;
5410 		free(pstore, M_TEMP);
5411 		break;
5412 	}
5413 
5414 	case DIOCCLRSRCNODES: {
5415 		pf_clear_srcnodes(NULL);
5416 		pf_purge_expired_src_nodes();
5417 		break;
5418 	}
5419 
5420 	case DIOCKILLSRCNODES:
5421 		pf_kill_srcnodes((struct pfioc_src_node_kill *)addr);
5422 		break;
5423 
5424 #ifdef COMPAT_FREEBSD13
5425 	case DIOCKEEPCOUNTERS_FREEBSD13:
5426 #endif
5427 	case DIOCKEEPCOUNTERS:
5428 		error = pf_keepcounters((struct pfioc_nv *)addr);
5429 		break;
5430 
5431 	case DIOCGETSYNCOOKIES:
5432 		error = pf_get_syncookies((struct pfioc_nv *)addr);
5433 		break;
5434 
5435 	case DIOCSETSYNCOOKIES:
5436 		error = pf_set_syncookies((struct pfioc_nv *)addr);
5437 		break;
5438 
5439 	case DIOCSETHOSTID: {
5440 		u_int32_t	*hostid = (u_int32_t *)addr;
5441 
5442 		PF_RULES_WLOCK();
5443 		if (*hostid == 0)
5444 			V_pf_status.hostid = arc4random();
5445 		else
5446 			V_pf_status.hostid = *hostid;
5447 		PF_RULES_WUNLOCK();
5448 		break;
5449 	}
5450 
5451 	case DIOCOSFPFLUSH:
5452 		PF_RULES_WLOCK();
5453 		pf_osfp_flush();
5454 		PF_RULES_WUNLOCK();
5455 		break;
5456 
5457 	case DIOCIGETIFACES: {
5458 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
5459 		struct pfi_kif *ifstore;
5460 		size_t bufsiz;
5461 
5462 		if (io->pfiio_esize != sizeof(struct pfi_kif)) {
5463 			error = ENODEV;
5464 			break;
5465 		}
5466 
5467 		if (io->pfiio_size < 0 ||
5468 		    io->pfiio_size > pf_ioctl_maxcount ||
5469 		    WOULD_OVERFLOW(io->pfiio_size, sizeof(struct pfi_kif))) {
5470 			error = EINVAL;
5471 			break;
5472 		}
5473 
5474 		io->pfiio_name[sizeof(io->pfiio_name) - 1] = '\0';
5475 
5476 		bufsiz = io->pfiio_size * sizeof(struct pfi_kif);
5477 		ifstore = mallocarray(io->pfiio_size, sizeof(struct pfi_kif),
5478 		    M_TEMP, M_WAITOK | M_ZERO);
5479 
5480 		PF_RULES_RLOCK();
5481 		pfi_get_ifaces(io->pfiio_name, ifstore, &io->pfiio_size);
5482 		PF_RULES_RUNLOCK();
5483 		error = copyout(ifstore, io->pfiio_buffer, bufsiz);
5484 		free(ifstore, M_TEMP);
5485 		break;
5486 	}
5487 
5488 	case DIOCSETIFFLAG: {
5489 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
5490 
5491 		io->pfiio_name[sizeof(io->pfiio_name) - 1] = '\0';
5492 
5493 		PF_RULES_WLOCK();
5494 		error = pfi_set_flags(io->pfiio_name, io->pfiio_flags);
5495 		PF_RULES_WUNLOCK();
5496 		break;
5497 	}
5498 
5499 	case DIOCCLRIFFLAG: {
5500 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
5501 
5502 		io->pfiio_name[sizeof(io->pfiio_name) - 1] = '\0';
5503 
5504 		PF_RULES_WLOCK();
5505 		error = pfi_clear_flags(io->pfiio_name, io->pfiio_flags);
5506 		PF_RULES_WUNLOCK();
5507 		break;
5508 	}
5509 
5510 	case DIOCSETREASS: {
5511 		u_int32_t	*reass = (u_int32_t *)addr;
5512 
5513 		V_pf_status.reass = *reass & (PF_REASS_ENABLED|PF_REASS_NODF);
5514 		/* Removal of DF flag without reassembly enabled is not a
5515 		 * valid combination. Disable reassembly in such case. */
5516 		if (!(V_pf_status.reass & PF_REASS_ENABLED))
5517 			V_pf_status.reass = 0;
5518 		break;
5519 	}
5520 
5521 	default:
5522 		error = ENODEV;
5523 		break;
5524 	}
5525 fail:
5526 	CURVNET_RESTORE();
5527 
5528 #undef ERROUT_IOCTL
5529 
5530 	return (error);
5531 }
5532 
5533 void
5534 pfsync_state_export(union pfsync_state_union *sp, struct pf_kstate *st, int msg_version)
5535 {
5536 	bzero(sp, sizeof(union pfsync_state_union));
5537 
5538 	/* copy from state key */
5539 	sp->pfs_1301.key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
5540 	sp->pfs_1301.key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
5541 	sp->pfs_1301.key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
5542 	sp->pfs_1301.key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
5543 	sp->pfs_1301.key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
5544 	sp->pfs_1301.key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
5545 	sp->pfs_1301.key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
5546 	sp->pfs_1301.key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
5547 	sp->pfs_1301.proto = st->key[PF_SK_WIRE]->proto;
5548 	sp->pfs_1301.af = st->key[PF_SK_WIRE]->af;
5549 
5550 	/* copy from state */
5551 	strlcpy(sp->pfs_1301.ifname, st->kif->pfik_name, sizeof(sp->pfs_1301.ifname));
5552 	bcopy(&st->rt_addr, &sp->pfs_1301.rt_addr, sizeof(sp->pfs_1301.rt_addr));
5553 	sp->pfs_1301.creation = htonl(time_uptime - (st->creation / 1000));
5554 	sp->pfs_1301.expire = pf_state_expires(st);
5555 	if (sp->pfs_1301.expire <= time_uptime)
5556 		sp->pfs_1301.expire = htonl(0);
5557 	else
5558 		sp->pfs_1301.expire = htonl(sp->pfs_1301.expire - time_uptime);
5559 
5560 	sp->pfs_1301.direction = st->direction;
5561 	sp->pfs_1301.log = st->act.log;
5562 	sp->pfs_1301.timeout = st->timeout;
5563 
5564 	switch (msg_version) {
5565 		case PFSYNC_MSG_VERSION_1301:
5566 			sp->pfs_1301.state_flags = st->state_flags;
5567 			break;
5568 		case PFSYNC_MSG_VERSION_1400:
5569 			sp->pfs_1400.state_flags = htons(st->state_flags);
5570 			sp->pfs_1400.qid = htons(st->act.qid);
5571 			sp->pfs_1400.pqid = htons(st->act.pqid);
5572 			sp->pfs_1400.dnpipe = htons(st->act.dnpipe);
5573 			sp->pfs_1400.dnrpipe = htons(st->act.dnrpipe);
5574 			sp->pfs_1400.rtableid = htonl(st->act.rtableid);
5575 			sp->pfs_1400.min_ttl = st->act.min_ttl;
5576 			sp->pfs_1400.set_tos = st->act.set_tos;
5577 			sp->pfs_1400.max_mss = htons(st->act.max_mss);
5578 			sp->pfs_1400.set_prio[0] = st->act.set_prio[0];
5579 			sp->pfs_1400.set_prio[1] = st->act.set_prio[1];
5580 			sp->pfs_1400.rt = st->rt;
5581 			if (st->rt_kif)
5582 				strlcpy(sp->pfs_1400.rt_ifname,
5583 				    st->rt_kif->pfik_name,
5584 				    sizeof(sp->pfs_1400.rt_ifname));
5585 			break;
5586 		default:
5587 			panic("%s: Unsupported pfsync_msg_version %d",
5588 			    __func__, msg_version);
5589 	}
5590 
5591 	if (st->src_node)
5592 		sp->pfs_1301.sync_flags |= PFSYNC_FLAG_SRCNODE;
5593 	if (st->nat_src_node)
5594 		sp->pfs_1301.sync_flags |= PFSYNC_FLAG_NATSRCNODE;
5595 
5596 	sp->pfs_1301.id = st->id;
5597 	sp->pfs_1301.creatorid = st->creatorid;
5598 	pf_state_peer_hton(&st->src, &sp->pfs_1301.src);
5599 	pf_state_peer_hton(&st->dst, &sp->pfs_1301.dst);
5600 
5601 	if (st->rule.ptr == NULL)
5602 		sp->pfs_1301.rule = htonl(-1);
5603 	else
5604 		sp->pfs_1301.rule = htonl(st->rule.ptr->nr);
5605 	if (st->anchor.ptr == NULL)
5606 		sp->pfs_1301.anchor = htonl(-1);
5607 	else
5608 		sp->pfs_1301.anchor = htonl(st->anchor.ptr->nr);
5609 	if (st->nat_rule.ptr == NULL)
5610 		sp->pfs_1301.nat_rule = htonl(-1);
5611 	else
5612 		sp->pfs_1301.nat_rule = htonl(st->nat_rule.ptr->nr);
5613 
5614 	pf_state_counter_hton(st->packets[0], sp->pfs_1301.packets[0]);
5615 	pf_state_counter_hton(st->packets[1], sp->pfs_1301.packets[1]);
5616 	pf_state_counter_hton(st->bytes[0], sp->pfs_1301.bytes[0]);
5617 	pf_state_counter_hton(st->bytes[1], sp->pfs_1301.bytes[1]);
5618 }
5619 
5620 void
5621 pf_state_export(struct pf_state_export *sp, struct pf_kstate *st)
5622 {
5623 	bzero(sp, sizeof(*sp));
5624 
5625 	sp->version = PF_STATE_VERSION;
5626 
5627 	/* copy from state key */
5628 	sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
5629 	sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
5630 	sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
5631 	sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
5632 	sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
5633 	sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
5634 	sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
5635 	sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
5636 	sp->proto = st->key[PF_SK_WIRE]->proto;
5637 	sp->af = st->key[PF_SK_WIRE]->af;
5638 
5639 	/* copy from state */
5640 	strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
5641 	strlcpy(sp->orig_ifname, st->orig_kif->pfik_name,
5642 	    sizeof(sp->orig_ifname));
5643 	bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));
5644 	sp->creation = htonl(time_uptime - (st->creation / 1000));
5645 	sp->expire = pf_state_expires(st);
5646 	if (sp->expire <= time_uptime)
5647 		sp->expire = htonl(0);
5648 	else
5649 		sp->expire = htonl(sp->expire - time_uptime);
5650 
5651 	sp->direction = st->direction;
5652 	sp->log = st->act.log;
5653 	sp->timeout = st->timeout;
5654 	/* 8 bits for the old libpfctl, 16 bits for the new libpfctl */
5655 	sp->state_flags_compat = st->state_flags;
5656 	sp->state_flags = htons(st->state_flags);
5657 	if (st->src_node)
5658 		sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
5659 	if (st->nat_src_node)
5660 		sp->sync_flags |= PFSYNC_FLAG_NATSRCNODE;
5661 
5662 	sp->id = st->id;
5663 	sp->creatorid = st->creatorid;
5664 	pf_state_peer_hton(&st->src, &sp->src);
5665 	pf_state_peer_hton(&st->dst, &sp->dst);
5666 
5667 	if (st->rule.ptr == NULL)
5668 		sp->rule = htonl(-1);
5669 	else
5670 		sp->rule = htonl(st->rule.ptr->nr);
5671 	if (st->anchor.ptr == NULL)
5672 		sp->anchor = htonl(-1);
5673 	else
5674 		sp->anchor = htonl(st->anchor.ptr->nr);
5675 	if (st->nat_rule.ptr == NULL)
5676 		sp->nat_rule = htonl(-1);
5677 	else
5678 		sp->nat_rule = htonl(st->nat_rule.ptr->nr);
5679 
5680 	sp->packets[0] = st->packets[0];
5681 	sp->packets[1] = st->packets[1];
5682 	sp->bytes[0] = st->bytes[0];
5683 	sp->bytes[1] = st->bytes[1];
5684 
5685 	sp->qid = htons(st->act.qid);
5686 	sp->pqid = htons(st->act.pqid);
5687 	sp->dnpipe = htons(st->act.dnpipe);
5688 	sp->dnrpipe = htons(st->act.dnrpipe);
5689 	sp->rtableid = htonl(st->act.rtableid);
5690 	sp->min_ttl = st->act.min_ttl;
5691 	sp->set_tos = st->act.set_tos;
5692 	sp->max_mss = htons(st->act.max_mss);
5693 	sp->rt = st->rt;
5694 	if (st->rt_kif)
5695 		strlcpy(sp->rt_ifname, st->rt_kif->pfik_name,
5696 		    sizeof(sp->rt_ifname));
5697 	sp->set_prio[0] = st->act.set_prio[0];
5698 	sp->set_prio[1] = st->act.set_prio[1];
5699 
5700 }
5701 
5702 static void
5703 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
5704 {
5705 	struct pfr_ktable *kt;
5706 
5707 	KASSERT(aw->type == PF_ADDR_TABLE, ("%s: type %u", __func__, aw->type));
5708 
5709 	kt = aw->p.tbl;
5710 	if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
5711 		kt = kt->pfrkt_root;
5712 	aw->p.tbl = NULL;
5713 	aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
5714 		kt->pfrkt_cnt : -1;
5715 }
5716 
5717 static int
5718 pf_add_status_counters(nvlist_t *nvl, const char *name, counter_u64_t *counters,
5719     size_t number, char **names)
5720 {
5721 	nvlist_t        *nvc;
5722 
5723 	nvc = nvlist_create(0);
5724 	if (nvc == NULL)
5725 		return (ENOMEM);
5726 
5727 	for (int i = 0; i < number; i++) {
5728 		nvlist_append_number_array(nvc, "counters",
5729 		    counter_u64_fetch(counters[i]));
5730 		nvlist_append_string_array(nvc, "names",
5731 		    names[i]);
5732 		nvlist_append_number_array(nvc, "ids",
5733 		    i);
5734 	}
5735 	nvlist_add_nvlist(nvl, name, nvc);
5736 	nvlist_destroy(nvc);
5737 
5738 	return (0);
5739 }
5740 
5741 static int
5742 pf_getstatus(struct pfioc_nv *nv)
5743 {
5744 	nvlist_t        *nvl = NULL, *nvc = NULL;
5745 	void            *nvlpacked = NULL;
5746 	int              error;
5747 	struct pf_status s;
5748 	char *pf_reasons[PFRES_MAX+1] = PFRES_NAMES;
5749 	char *pf_lcounter[KLCNT_MAX+1] = KLCNT_NAMES;
5750 	char *pf_fcounter[FCNT_MAX+1] = FCNT_NAMES;
5751 	PF_RULES_RLOCK_TRACKER;
5752 
5753 #define ERROUT(x)      ERROUT_FUNCTION(errout, x)
5754 
5755 	PF_RULES_RLOCK();
5756 
5757 	nvl = nvlist_create(0);
5758 	if (nvl == NULL)
5759 		ERROUT(ENOMEM);
5760 
5761 	nvlist_add_bool(nvl, "running", V_pf_status.running);
5762 	nvlist_add_number(nvl, "since", V_pf_status.since);
5763 	nvlist_add_number(nvl, "debug", V_pf_status.debug);
5764 	nvlist_add_number(nvl, "hostid", V_pf_status.hostid);
5765 	nvlist_add_number(nvl, "states", V_pf_status.states);
5766 	nvlist_add_number(nvl, "src_nodes", V_pf_status.src_nodes);
5767 	nvlist_add_number(nvl, "reass", V_pf_status.reass);
5768 	nvlist_add_bool(nvl, "syncookies_active",
5769 	    V_pf_status.syncookies_active);
5770 	nvlist_add_number(nvl, "halfopen_states", V_pf_status.states_halfopen);
5771 
5772 	/* counters */
5773 	error = pf_add_status_counters(nvl, "counters", V_pf_status.counters,
5774 	    PFRES_MAX, pf_reasons);
5775 	if (error != 0)
5776 		ERROUT(error);
5777 
5778 	/* lcounters */
5779 	error = pf_add_status_counters(nvl, "lcounters", V_pf_status.lcounters,
5780 	    KLCNT_MAX, pf_lcounter);
5781 	if (error != 0)
5782 		ERROUT(error);
5783 
5784 	/* fcounters */
5785 	nvc = nvlist_create(0);
5786 	if (nvc == NULL)
5787 		ERROUT(ENOMEM);
5788 
5789 	for (int i = 0; i < FCNT_MAX; i++) {
5790 		nvlist_append_number_array(nvc, "counters",
5791 		    pf_counter_u64_fetch(&V_pf_status.fcounters[i]));
5792 		nvlist_append_string_array(nvc, "names",
5793 		    pf_fcounter[i]);
5794 		nvlist_append_number_array(nvc, "ids",
5795 		    i);
5796 	}
5797 	nvlist_add_nvlist(nvl, "fcounters", nvc);
5798 	nvlist_destroy(nvc);
5799 	nvc = NULL;
5800 
5801 	/* scounters */
5802 	error = pf_add_status_counters(nvl, "scounters", V_pf_status.scounters,
5803 	    SCNT_MAX, pf_fcounter);
5804 	if (error != 0)
5805 		ERROUT(error);
5806 
5807 	nvlist_add_string(nvl, "ifname", V_pf_status.ifname);
5808 	nvlist_add_binary(nvl, "chksum", V_pf_status.pf_chksum,
5809 	    PF_MD5_DIGEST_LENGTH);
5810 
5811 	pfi_update_status(V_pf_status.ifname, &s);
5812 
5813 	/* pcounters / bcounters */
5814 	for (int i = 0; i < 2; i++) {
5815 		for (int j = 0; j < 2; j++) {
5816 			for (int k = 0; k < 2; k++) {
5817 				nvlist_append_number_array(nvl, "pcounters",
5818 				    s.pcounters[i][j][k]);
5819 			}
5820 			nvlist_append_number_array(nvl, "bcounters",
5821 			    s.bcounters[i][j]);
5822 		}
5823 	}
5824 
5825 	nvlpacked = nvlist_pack(nvl, &nv->len);
5826 	if (nvlpacked == NULL)
5827 		ERROUT(ENOMEM);
5828 
5829 	if (nv->size == 0)
5830 		ERROUT(0);
5831 	else if (nv->size < nv->len)
5832 		ERROUT(ENOSPC);
5833 
5834 	PF_RULES_RUNLOCK();
5835 	error = copyout(nvlpacked, nv->data, nv->len);
5836 	goto done;
5837 
5838 #undef ERROUT
5839 errout:
5840 	PF_RULES_RUNLOCK();
5841 done:
5842 	free(nvlpacked, M_NVLIST);
5843 	nvlist_destroy(nvc);
5844 	nvlist_destroy(nvl);
5845 
5846 	return (error);
5847 }
5848 
5849 /*
5850  * XXX - Check for version mismatch!!!
5851  */
5852 static void
5853 pf_clear_all_states(void)
5854 {
5855 	struct epoch_tracker	 et;
5856 	struct pf_kstate	*s;
5857 	u_int i;
5858 
5859 	NET_EPOCH_ENTER(et);
5860 	for (i = 0; i <= V_pf_hashmask; i++) {
5861 		struct pf_idhash *ih = &V_pf_idhash[i];
5862 relock:
5863 		PF_HASHROW_LOCK(ih);
5864 		LIST_FOREACH(s, &ih->states, entry) {
5865 			s->timeout = PFTM_PURGE;
5866 			/* Don't send out individual delete messages. */
5867 			s->state_flags |= PFSTATE_NOSYNC;
5868 			pf_unlink_state(s);
5869 			goto relock;
5870 		}
5871 		PF_HASHROW_UNLOCK(ih);
5872 	}
5873 	NET_EPOCH_EXIT(et);
5874 }
5875 
5876 static int
5877 pf_clear_tables(void)
5878 {
5879 	struct pfioc_table io;
5880 	int error;
5881 
5882 	bzero(&io, sizeof(io));
5883 	io.pfrio_flags |= PFR_FLAG_ALLRSETS;
5884 
5885 	error = pfr_clr_tables(&io.pfrio_table, &io.pfrio_ndel,
5886 	    io.pfrio_flags);
5887 
5888 	return (error);
5889 }
5890 
5891 static void
5892 pf_clear_srcnodes(struct pf_ksrc_node *n)
5893 {
5894 	struct pf_kstate *s;
5895 	int i;
5896 
5897 	for (i = 0; i <= V_pf_hashmask; i++) {
5898 		struct pf_idhash *ih = &V_pf_idhash[i];
5899 
5900 		PF_HASHROW_LOCK(ih);
5901 		LIST_FOREACH(s, &ih->states, entry) {
5902 			if (n == NULL || n == s->src_node)
5903 				s->src_node = NULL;
5904 			if (n == NULL || n == s->nat_src_node)
5905 				s->nat_src_node = NULL;
5906 		}
5907 		PF_HASHROW_UNLOCK(ih);
5908 	}
5909 
5910 	if (n == NULL) {
5911 		struct pf_srchash *sh;
5912 
5913 		for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask;
5914 		    i++, sh++) {
5915 			PF_HASHROW_LOCK(sh);
5916 			LIST_FOREACH(n, &sh->nodes, entry) {
5917 				n->expire = 1;
5918 				n->states = 0;
5919 			}
5920 			PF_HASHROW_UNLOCK(sh);
5921 		}
5922 	} else {
5923 		/* XXX: hash slot should already be locked here. */
5924 		n->expire = 1;
5925 		n->states = 0;
5926 	}
5927 }
5928 
5929 static void
5930 pf_kill_srcnodes(struct pfioc_src_node_kill *psnk)
5931 {
5932 	struct pf_ksrc_node_list	 kill;
5933 
5934 	LIST_INIT(&kill);
5935 	for (int i = 0; i <= V_pf_srchashmask; i++) {
5936 		struct pf_srchash *sh = &V_pf_srchash[i];
5937 		struct pf_ksrc_node *sn, *tmp;
5938 
5939 		PF_HASHROW_LOCK(sh);
5940 		LIST_FOREACH_SAFE(sn, &sh->nodes, entry, tmp)
5941 			if (PF_MATCHA(psnk->psnk_src.neg,
5942 			      &psnk->psnk_src.addr.v.a.addr,
5943 			      &psnk->psnk_src.addr.v.a.mask,
5944 			      &sn->addr, sn->af) &&
5945 			    PF_MATCHA(psnk->psnk_dst.neg,
5946 			      &psnk->psnk_dst.addr.v.a.addr,
5947 			      &psnk->psnk_dst.addr.v.a.mask,
5948 			      &sn->raddr, sn->af)) {
5949 				pf_unlink_src_node(sn);
5950 				LIST_INSERT_HEAD(&kill, sn, entry);
5951 				sn->expire = 1;
5952 			}
5953 		PF_HASHROW_UNLOCK(sh);
5954 	}
5955 
5956 	for (int i = 0; i <= V_pf_hashmask; i++) {
5957 		struct pf_idhash *ih = &V_pf_idhash[i];
5958 		struct pf_kstate *s;
5959 
5960 		PF_HASHROW_LOCK(ih);
5961 		LIST_FOREACH(s, &ih->states, entry) {
5962 			if (s->src_node && s->src_node->expire == 1)
5963 				s->src_node = NULL;
5964 			if (s->nat_src_node && s->nat_src_node->expire == 1)
5965 				s->nat_src_node = NULL;
5966 		}
5967 		PF_HASHROW_UNLOCK(ih);
5968 	}
5969 
5970 	psnk->psnk_killed = pf_free_src_nodes(&kill);
5971 }
5972 
5973 static int
5974 pf_keepcounters(struct pfioc_nv *nv)
5975 {
5976 	nvlist_t	*nvl = NULL;
5977 	void		*nvlpacked = NULL;
5978 	int		 error = 0;
5979 
5980 #define	ERROUT(x)	ERROUT_FUNCTION(on_error, x)
5981 
5982 	if (nv->len > pf_ioctl_maxcount)
5983 		ERROUT(ENOMEM);
5984 
5985 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
5986 	error = copyin(nv->data, nvlpacked, nv->len);
5987 	if (error)
5988 		ERROUT(error);
5989 
5990 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
5991 	if (nvl == NULL)
5992 		ERROUT(EBADMSG);
5993 
5994 	if (! nvlist_exists_bool(nvl, "keep_counters"))
5995 		ERROUT(EBADMSG);
5996 
5997 	V_pf_status.keep_counters = nvlist_get_bool(nvl, "keep_counters");
5998 
5999 on_error:
6000 	nvlist_destroy(nvl);
6001 	free(nvlpacked, M_NVLIST);
6002 	return (error);
6003 }
6004 
6005 unsigned int
6006 pf_clear_states(const struct pf_kstate_kill *kill)
6007 {
6008 	struct pf_state_key_cmp	 match_key;
6009 	struct pf_kstate	*s;
6010 	struct pfi_kkif	*kif;
6011 	int		 idx;
6012 	unsigned int	 killed = 0, dir;
6013 
6014 	NET_EPOCH_ASSERT();
6015 
6016 	for (unsigned int i = 0; i <= V_pf_hashmask; i++) {
6017 		struct pf_idhash *ih = &V_pf_idhash[i];
6018 
6019 relock_DIOCCLRSTATES:
6020 		PF_HASHROW_LOCK(ih);
6021 		LIST_FOREACH(s, &ih->states, entry) {
6022 			/* For floating states look at the original kif. */
6023 			kif = s->kif == V_pfi_all ? s->orig_kif : s->kif;
6024 
6025 			if (kill->psk_ifname[0] &&
6026 			    strcmp(kill->psk_ifname,
6027 			    kif->pfik_name))
6028 				continue;
6029 
6030 			if (kill->psk_kill_match) {
6031 				bzero(&match_key, sizeof(match_key));
6032 
6033 				if (s->direction == PF_OUT) {
6034 					dir = PF_IN;
6035 					idx = PF_SK_STACK;
6036 				} else {
6037 					dir = PF_OUT;
6038 					idx = PF_SK_WIRE;
6039 				}
6040 
6041 				match_key.af = s->key[idx]->af;
6042 				match_key.proto = s->key[idx]->proto;
6043 				PF_ACPY(&match_key.addr[0],
6044 				    &s->key[idx]->addr[1], match_key.af);
6045 				match_key.port[0] = s->key[idx]->port[1];
6046 				PF_ACPY(&match_key.addr[1],
6047 				    &s->key[idx]->addr[0], match_key.af);
6048 				match_key.port[1] = s->key[idx]->port[0];
6049 			}
6050 
6051 			/*
6052 			 * Don't send out individual
6053 			 * delete messages.
6054 			 */
6055 			s->state_flags |= PFSTATE_NOSYNC;
6056 			pf_unlink_state(s);
6057 			killed++;
6058 
6059 			if (kill->psk_kill_match)
6060 				killed += pf_kill_matching_state(&match_key,
6061 				    dir);
6062 
6063 			goto relock_DIOCCLRSTATES;
6064 		}
6065 		PF_HASHROW_UNLOCK(ih);
6066 	}
6067 
6068 	if (V_pfsync_clear_states_ptr != NULL)
6069 		V_pfsync_clear_states_ptr(V_pf_status.hostid, kill->psk_ifname);
6070 
6071 	return (killed);
6072 }
6073 
6074 void
6075 pf_killstates(struct pf_kstate_kill *kill, unsigned int *killed)
6076 {
6077 	struct pf_kstate	*s;
6078 
6079 	NET_EPOCH_ASSERT();
6080 	if (kill->psk_pfcmp.id) {
6081 		if (kill->psk_pfcmp.creatorid == 0)
6082 			kill->psk_pfcmp.creatorid = V_pf_status.hostid;
6083 		if ((s = pf_find_state_byid(kill->psk_pfcmp.id,
6084 		    kill->psk_pfcmp.creatorid))) {
6085 			pf_unlink_state(s);
6086 			*killed = 1;
6087 		}
6088 		return;
6089 	}
6090 
6091 	for (unsigned int i = 0; i <= V_pf_hashmask; i++)
6092 		*killed += pf_killstates_row(kill, &V_pf_idhash[i]);
6093 }
6094 
6095 static int
6096 pf_killstates_nv(struct pfioc_nv *nv)
6097 {
6098 	struct pf_kstate_kill	 kill;
6099 	struct epoch_tracker	 et;
6100 	nvlist_t		*nvl = NULL;
6101 	void			*nvlpacked = NULL;
6102 	int			 error = 0;
6103 	unsigned int		 killed = 0;
6104 
6105 #define ERROUT(x)	ERROUT_FUNCTION(on_error, x)
6106 
6107 	if (nv->len > pf_ioctl_maxcount)
6108 		ERROUT(ENOMEM);
6109 
6110 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
6111 	error = copyin(nv->data, nvlpacked, nv->len);
6112 	if (error)
6113 		ERROUT(error);
6114 
6115 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
6116 	if (nvl == NULL)
6117 		ERROUT(EBADMSG);
6118 
6119 	error = pf_nvstate_kill_to_kstate_kill(nvl, &kill);
6120 	if (error)
6121 		ERROUT(error);
6122 
6123 	NET_EPOCH_ENTER(et);
6124 	pf_killstates(&kill, &killed);
6125 	NET_EPOCH_EXIT(et);
6126 
6127 	free(nvlpacked, M_NVLIST);
6128 	nvlpacked = NULL;
6129 	nvlist_destroy(nvl);
6130 	nvl = nvlist_create(0);
6131 	if (nvl == NULL)
6132 		ERROUT(ENOMEM);
6133 
6134 	nvlist_add_number(nvl, "killed", killed);
6135 
6136 	nvlpacked = nvlist_pack(nvl, &nv->len);
6137 	if (nvlpacked == NULL)
6138 		ERROUT(ENOMEM);
6139 
6140 	if (nv->size == 0)
6141 		ERROUT(0);
6142 	else if (nv->size < nv->len)
6143 		ERROUT(ENOSPC);
6144 
6145 	error = copyout(nvlpacked, nv->data, nv->len);
6146 
6147 on_error:
6148 	nvlist_destroy(nvl);
6149 	free(nvlpacked, M_NVLIST);
6150 	return (error);
6151 }
6152 
6153 static int
6154 pf_clearstates_nv(struct pfioc_nv *nv)
6155 {
6156 	struct pf_kstate_kill	 kill;
6157 	struct epoch_tracker	 et;
6158 	nvlist_t		*nvl = NULL;
6159 	void			*nvlpacked = NULL;
6160 	int			 error = 0;
6161 	unsigned int		 killed;
6162 
6163 #define ERROUT(x)	ERROUT_FUNCTION(on_error, x)
6164 
6165 	if (nv->len > pf_ioctl_maxcount)
6166 		ERROUT(ENOMEM);
6167 
6168 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
6169 	error = copyin(nv->data, nvlpacked, nv->len);
6170 	if (error)
6171 		ERROUT(error);
6172 
6173 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
6174 	if (nvl == NULL)
6175 		ERROUT(EBADMSG);
6176 
6177 	error = pf_nvstate_kill_to_kstate_kill(nvl, &kill);
6178 	if (error)
6179 		ERROUT(error);
6180 
6181 	NET_EPOCH_ENTER(et);
6182 	killed = pf_clear_states(&kill);
6183 	NET_EPOCH_EXIT(et);
6184 
6185 	free(nvlpacked, M_NVLIST);
6186 	nvlpacked = NULL;
6187 	nvlist_destroy(nvl);
6188 	nvl = nvlist_create(0);
6189 	if (nvl == NULL)
6190 		ERROUT(ENOMEM);
6191 
6192 	nvlist_add_number(nvl, "killed", killed);
6193 
6194 	nvlpacked = nvlist_pack(nvl, &nv->len);
6195 	if (nvlpacked == NULL)
6196 		ERROUT(ENOMEM);
6197 
6198 	if (nv->size == 0)
6199 		ERROUT(0);
6200 	else if (nv->size < nv->len)
6201 		ERROUT(ENOSPC);
6202 
6203 	error = copyout(nvlpacked, nv->data, nv->len);
6204 
6205 #undef ERROUT
6206 on_error:
6207 	nvlist_destroy(nvl);
6208 	free(nvlpacked, M_NVLIST);
6209 	return (error);
6210 }
6211 
6212 static int
6213 pf_getstate(struct pfioc_nv *nv)
6214 {
6215 	nvlist_t		*nvl = NULL, *nvls;
6216 	void			*nvlpacked = NULL;
6217 	struct pf_kstate	*s = NULL;
6218 	int			 error = 0;
6219 	uint64_t		 id, creatorid;
6220 
6221 #define ERROUT(x)	ERROUT_FUNCTION(errout, x)
6222 
6223 	if (nv->len > pf_ioctl_maxcount)
6224 		ERROUT(ENOMEM);
6225 
6226 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
6227 	error = copyin(nv->data, nvlpacked, nv->len);
6228 	if (error)
6229 		ERROUT(error);
6230 
6231 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
6232 	if (nvl == NULL)
6233 		ERROUT(EBADMSG);
6234 
6235 	PFNV_CHK(pf_nvuint64(nvl, "id", &id));
6236 	PFNV_CHK(pf_nvuint64(nvl, "creatorid", &creatorid));
6237 
6238 	s = pf_find_state_byid(id, creatorid);
6239 	if (s == NULL)
6240 		ERROUT(ENOENT);
6241 
6242 	free(nvlpacked, M_NVLIST);
6243 	nvlpacked = NULL;
6244 	nvlist_destroy(nvl);
6245 	nvl = nvlist_create(0);
6246 	if (nvl == NULL)
6247 		ERROUT(ENOMEM);
6248 
6249 	nvls = pf_state_to_nvstate(s);
6250 	if (nvls == NULL)
6251 		ERROUT(ENOMEM);
6252 
6253 	nvlist_add_nvlist(nvl, "state", nvls);
6254 	nvlist_destroy(nvls);
6255 
6256 	nvlpacked = nvlist_pack(nvl, &nv->len);
6257 	if (nvlpacked == NULL)
6258 		ERROUT(ENOMEM);
6259 
6260 	if (nv->size == 0)
6261 		ERROUT(0);
6262 	else if (nv->size < nv->len)
6263 		ERROUT(ENOSPC);
6264 
6265 	error = copyout(nvlpacked, nv->data, nv->len);
6266 
6267 #undef ERROUT
6268 errout:
6269 	if (s != NULL)
6270 		PF_STATE_UNLOCK(s);
6271 	free(nvlpacked, M_NVLIST);
6272 	nvlist_destroy(nvl);
6273 	return (error);
6274 }
6275 
6276 /*
6277  * XXX - Check for version mismatch!!!
6278  */
6279 
6280 /*
6281  * Duplicate pfctl -Fa operation to get rid of as much as we can.
6282  */
6283 static int
6284 shutdown_pf(void)
6285 {
6286 	int error = 0;
6287 	u_int32_t t[5];
6288 	char nn = '\0';
6289 	struct pf_kanchor *anchor;
6290 	struct pf_keth_anchor *eth_anchor;
6291 	int rs_num;
6292 
6293 	do {
6294 		/* Unlink rules of all user defined anchors */
6295 		RB_FOREACH(anchor, pf_kanchor_global, &V_pf_anchors) {
6296 			/* Wildcard based anchors may not have a respective
6297 			 * explicit anchor rule or they may be left empty
6298 			 * without rules. It leads to anchor.refcnt=0, and the
6299 			 * rest of the logic does not expect it. */
6300 			if (anchor->refcnt == 0)
6301 				anchor->refcnt = 1;
6302 			for (rs_num = 0; rs_num < PF_RULESET_MAX; ++rs_num) {
6303 				if ((error = pf_begin_rules(&t[rs_num], rs_num,
6304 				    anchor->path)) != 0) {
6305 					DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: "
6306 					    "anchor.path=%s rs_num=%d\n",
6307 					    anchor->path, rs_num));
6308 					goto error;	/* XXX: rollback? */
6309 				}
6310 			}
6311 			for (rs_num = 0; rs_num < PF_RULESET_MAX; ++rs_num) {
6312 				error = pf_commit_rules(t[rs_num], rs_num,
6313 				    anchor->path);
6314 				MPASS(error == 0);
6315 			}
6316 		}
6317 
6318 		/* Unlink rules of all user defined ether anchors */
6319 		RB_FOREACH(eth_anchor, pf_keth_anchor_global,
6320 		    &V_pf_keth_anchors) {
6321 			/* Wildcard based anchors may not have a respective
6322 			 * explicit anchor rule or they may be left empty
6323 			 * without rules. It leads to anchor.refcnt=0, and the
6324 			 * rest of the logic does not expect it. */
6325 			if (eth_anchor->refcnt == 0)
6326 				eth_anchor->refcnt = 1;
6327 			if ((error = pf_begin_eth(&t[0], eth_anchor->path))
6328 			    != 0) {
6329 				DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: eth "
6330 				    "anchor.path=%s\n", eth_anchor->path));
6331 				goto error;
6332 			}
6333 			error = pf_commit_eth(t[0], eth_anchor->path);
6334 			MPASS(error == 0);
6335 		}
6336 
6337 		if ((error = pf_begin_rules(&t[0], PF_RULESET_SCRUB, &nn))
6338 		    != 0) {
6339 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: SCRUB\n"));
6340 			break;
6341 		}
6342 		if ((error = pf_begin_rules(&t[1], PF_RULESET_FILTER, &nn))
6343 		    != 0) {
6344 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: FILTER\n"));
6345 			break;		/* XXX: rollback? */
6346 		}
6347 		if ((error = pf_begin_rules(&t[2], PF_RULESET_NAT, &nn))
6348 		    != 0) {
6349 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: NAT\n"));
6350 			break;		/* XXX: rollback? */
6351 		}
6352 		if ((error = pf_begin_rules(&t[3], PF_RULESET_BINAT, &nn))
6353 		    != 0) {
6354 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: BINAT\n"));
6355 			break;		/* XXX: rollback? */
6356 		}
6357 		if ((error = pf_begin_rules(&t[4], PF_RULESET_RDR, &nn))
6358 		    != 0) {
6359 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: RDR\n"));
6360 			break;		/* XXX: rollback? */
6361 		}
6362 
6363 		error = pf_commit_rules(t[0], PF_RULESET_SCRUB, &nn);
6364 		MPASS(error == 0);
6365 		error = pf_commit_rules(t[1], PF_RULESET_FILTER, &nn);
6366 		MPASS(error == 0);
6367 		error = pf_commit_rules(t[2], PF_RULESET_NAT, &nn);
6368 		MPASS(error == 0);
6369 		error = pf_commit_rules(t[3], PF_RULESET_BINAT, &nn);
6370 		MPASS(error == 0);
6371 		error = pf_commit_rules(t[4], PF_RULESET_RDR, &nn);
6372 		MPASS(error == 0);
6373 
6374 		if ((error = pf_clear_tables()) != 0)
6375 			break;
6376 
6377 		if ((error = pf_begin_eth(&t[0], &nn)) != 0) {
6378 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: eth\n"));
6379 			break;
6380 		}
6381 		error = pf_commit_eth(t[0], &nn);
6382 		MPASS(error == 0);
6383 
6384 #ifdef ALTQ
6385 		if ((error = pf_begin_altq(&t[0])) != 0) {
6386 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: ALTQ\n"));
6387 			break;
6388 		}
6389 		pf_commit_altq(t[0]);
6390 #endif
6391 
6392 		pf_clear_all_states();
6393 
6394 		pf_clear_srcnodes(NULL);
6395 
6396 		/* status does not use malloced mem so no need to cleanup */
6397 		/* fingerprints and interfaces have their own cleanup code */
6398 	} while(0);
6399 
6400 error:
6401 	return (error);
6402 }
6403 
6404 static pfil_return_t
6405 pf_check_return(int chk, struct mbuf **m)
6406 {
6407 
6408 	switch (chk) {
6409 	case PF_PASS:
6410 		if (*m == NULL)
6411 			return (PFIL_CONSUMED);
6412 		else
6413 			return (PFIL_PASS);
6414 		break;
6415 	default:
6416 		if (*m != NULL) {
6417 			m_freem(*m);
6418 			*m = NULL;
6419 		}
6420 		return (PFIL_DROPPED);
6421 	}
6422 }
6423 
6424 static pfil_return_t
6425 pf_eth_check_in(struct mbuf **m, struct ifnet *ifp, int flags,
6426     void *ruleset __unused, struct inpcb *inp)
6427 {
6428 	int chk;
6429 
6430 	chk = pf_test_eth(PF_IN, flags, ifp, m, inp);
6431 
6432 	return (pf_check_return(chk, m));
6433 }
6434 
6435 static pfil_return_t
6436 pf_eth_check_out(struct mbuf **m, struct ifnet *ifp, int flags,
6437     void *ruleset __unused, struct inpcb *inp)
6438 {
6439 	int chk;
6440 
6441 	chk = pf_test_eth(PF_OUT, flags, ifp, m, inp);
6442 
6443 	return (pf_check_return(chk, m));
6444 }
6445 
6446 #ifdef INET
6447 static pfil_return_t
6448 pf_check_in(struct mbuf **m, struct ifnet *ifp, int flags,
6449     void *ruleset __unused, struct inpcb *inp)
6450 {
6451 	int chk;
6452 
6453 	chk = pf_test(PF_IN, flags, ifp, m, inp, NULL);
6454 
6455 	return (pf_check_return(chk, m));
6456 }
6457 
6458 static pfil_return_t
6459 pf_check_out(struct mbuf **m, struct ifnet *ifp, int flags,
6460     void *ruleset __unused,  struct inpcb *inp)
6461 {
6462 	int chk;
6463 
6464 	chk = pf_test(PF_OUT, flags, ifp, m, inp, NULL);
6465 
6466 	return (pf_check_return(chk, m));
6467 }
6468 #endif
6469 
6470 #ifdef INET6
6471 static pfil_return_t
6472 pf_check6_in(struct mbuf **m, struct ifnet *ifp, int flags,
6473     void *ruleset __unused,  struct inpcb *inp)
6474 {
6475 	int chk;
6476 
6477 	/*
6478 	 * In case of loopback traffic IPv6 uses the real interface in
6479 	 * order to support scoped addresses. In order to support stateful
6480 	 * filtering we have change this to lo0 as it is the case in IPv4.
6481 	 */
6482 	CURVNET_SET(ifp->if_vnet);
6483 	chk = pf_test6(PF_IN, flags, (*m)->m_flags & M_LOOP ? V_loif : ifp,
6484 	    m, inp, NULL);
6485 	CURVNET_RESTORE();
6486 
6487 	return (pf_check_return(chk, m));
6488 }
6489 
6490 static pfil_return_t
6491 pf_check6_out(struct mbuf **m, struct ifnet *ifp, int flags,
6492     void *ruleset __unused,  struct inpcb *inp)
6493 {
6494 	int chk;
6495 
6496 	CURVNET_SET(ifp->if_vnet);
6497 	chk = pf_test6(PF_OUT, flags, ifp, m, inp, NULL);
6498 	CURVNET_RESTORE();
6499 
6500 	return (pf_check_return(chk, m));
6501 }
6502 #endif /* INET6 */
6503 
6504 VNET_DEFINE_STATIC(pfil_hook_t, pf_eth_in_hook);
6505 VNET_DEFINE_STATIC(pfil_hook_t, pf_eth_out_hook);
6506 #define	V_pf_eth_in_hook	VNET(pf_eth_in_hook)
6507 #define	V_pf_eth_out_hook	VNET(pf_eth_out_hook)
6508 
6509 #ifdef INET
6510 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip4_in_hook);
6511 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip4_out_hook);
6512 #define	V_pf_ip4_in_hook	VNET(pf_ip4_in_hook)
6513 #define	V_pf_ip4_out_hook	VNET(pf_ip4_out_hook)
6514 #endif
6515 #ifdef INET6
6516 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip6_in_hook);
6517 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip6_out_hook);
6518 #define	V_pf_ip6_in_hook	VNET(pf_ip6_in_hook)
6519 #define	V_pf_ip6_out_hook	VNET(pf_ip6_out_hook)
6520 #endif
6521 
6522 static void
6523 hook_pf_eth(void)
6524 {
6525 	struct pfil_hook_args pha = {
6526 		.pa_version = PFIL_VERSION,
6527 		.pa_modname = "pf",
6528 		.pa_type = PFIL_TYPE_ETHERNET,
6529 	};
6530 	struct pfil_link_args pla = {
6531 		.pa_version = PFIL_VERSION,
6532 	};
6533 	int ret __diagused;
6534 
6535 	if (atomic_load_bool(&V_pf_pfil_eth_hooked))
6536 		return;
6537 
6538 	pha.pa_mbuf_chk = pf_eth_check_in;
6539 	pha.pa_flags = PFIL_IN;
6540 	pha.pa_rulname = "eth-in";
6541 	V_pf_eth_in_hook = pfil_add_hook(&pha);
6542 	pla.pa_flags = PFIL_IN | PFIL_HEADPTR | PFIL_HOOKPTR;
6543 	pla.pa_head = V_link_pfil_head;
6544 	pla.pa_hook = V_pf_eth_in_hook;
6545 	ret = pfil_link(&pla);
6546 	MPASS(ret == 0);
6547 	pha.pa_mbuf_chk = pf_eth_check_out;
6548 	pha.pa_flags = PFIL_OUT;
6549 	pha.pa_rulname = "eth-out";
6550 	V_pf_eth_out_hook = pfil_add_hook(&pha);
6551 	pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
6552 	pla.pa_head = V_link_pfil_head;
6553 	pla.pa_hook = V_pf_eth_out_hook;
6554 	ret = pfil_link(&pla);
6555 	MPASS(ret == 0);
6556 
6557 	atomic_store_bool(&V_pf_pfil_eth_hooked, true);
6558 }
6559 
6560 static void
6561 hook_pf(void)
6562 {
6563 	struct pfil_hook_args pha = {
6564 		.pa_version = PFIL_VERSION,
6565 		.pa_modname = "pf",
6566 	};
6567 	struct pfil_link_args pla = {
6568 		.pa_version = PFIL_VERSION,
6569 	};
6570 	int ret __diagused;
6571 
6572 	if (atomic_load_bool(&V_pf_pfil_hooked))
6573 		return;
6574 
6575 #ifdef INET
6576 	pha.pa_type = PFIL_TYPE_IP4;
6577 	pha.pa_mbuf_chk = pf_check_in;
6578 	pha.pa_flags = PFIL_IN;
6579 	pha.pa_rulname = "default-in";
6580 	V_pf_ip4_in_hook = pfil_add_hook(&pha);
6581 	pla.pa_flags = PFIL_IN | PFIL_HEADPTR | PFIL_HOOKPTR;
6582 	pla.pa_head = V_inet_pfil_head;
6583 	pla.pa_hook = V_pf_ip4_in_hook;
6584 	ret = pfil_link(&pla);
6585 	MPASS(ret == 0);
6586 	pha.pa_mbuf_chk = pf_check_out;
6587 	pha.pa_flags = PFIL_OUT;
6588 	pha.pa_rulname = "default-out";
6589 	V_pf_ip4_out_hook = pfil_add_hook(&pha);
6590 	pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
6591 	pla.pa_head = V_inet_pfil_head;
6592 	pla.pa_hook = V_pf_ip4_out_hook;
6593 	ret = pfil_link(&pla);
6594 	MPASS(ret == 0);
6595 	if (V_pf_filter_local) {
6596 		pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
6597 		pla.pa_head = V_inet_local_pfil_head;
6598 		pla.pa_hook = V_pf_ip4_out_hook;
6599 		ret = pfil_link(&pla);
6600 		MPASS(ret == 0);
6601 	}
6602 #endif
6603 #ifdef INET6
6604 	pha.pa_type = PFIL_TYPE_IP6;
6605 	pha.pa_mbuf_chk = pf_check6_in;
6606 	pha.pa_flags = PFIL_IN;
6607 	pha.pa_rulname = "default-in6";
6608 	V_pf_ip6_in_hook = pfil_add_hook(&pha);
6609 	pla.pa_flags = PFIL_IN | PFIL_HEADPTR | PFIL_HOOKPTR;
6610 	pla.pa_head = V_inet6_pfil_head;
6611 	pla.pa_hook = V_pf_ip6_in_hook;
6612 	ret = pfil_link(&pla);
6613 	MPASS(ret == 0);
6614 	pha.pa_mbuf_chk = pf_check6_out;
6615 	pha.pa_rulname = "default-out6";
6616 	pha.pa_flags = PFIL_OUT;
6617 	V_pf_ip6_out_hook = pfil_add_hook(&pha);
6618 	pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
6619 	pla.pa_head = V_inet6_pfil_head;
6620 	pla.pa_hook = V_pf_ip6_out_hook;
6621 	ret = pfil_link(&pla);
6622 	MPASS(ret == 0);
6623 	if (V_pf_filter_local) {
6624 		pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
6625 		pla.pa_head = V_inet6_local_pfil_head;
6626 		pla.pa_hook = V_pf_ip6_out_hook;
6627 		ret = pfil_link(&pla);
6628 		MPASS(ret == 0);
6629 	}
6630 #endif
6631 
6632 	atomic_store_bool(&V_pf_pfil_hooked, true);
6633 }
6634 
6635 static void
6636 dehook_pf_eth(void)
6637 {
6638 
6639 	if (!atomic_load_bool(&V_pf_pfil_eth_hooked))
6640 		return;
6641 
6642 	pfil_remove_hook(V_pf_eth_in_hook);
6643 	pfil_remove_hook(V_pf_eth_out_hook);
6644 
6645 	atomic_store_bool(&V_pf_pfil_eth_hooked, false);
6646 }
6647 
6648 static void
6649 dehook_pf(void)
6650 {
6651 
6652 	if (!atomic_load_bool(&V_pf_pfil_hooked))
6653 		return;
6654 
6655 #ifdef INET
6656 	pfil_remove_hook(V_pf_ip4_in_hook);
6657 	pfil_remove_hook(V_pf_ip4_out_hook);
6658 #endif
6659 #ifdef INET6
6660 	pfil_remove_hook(V_pf_ip6_in_hook);
6661 	pfil_remove_hook(V_pf_ip6_out_hook);
6662 #endif
6663 
6664 	atomic_store_bool(&V_pf_pfil_hooked, false);
6665 }
6666 
6667 static void
6668 pf_load_vnet(void)
6669 {
6670 	V_pf_tag_z = uma_zcreate("pf tags", sizeof(struct pf_tagname),
6671 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
6672 
6673 	rm_init_flags(&V_pf_rules_lock, "pf rulesets", RM_RECURSE);
6674 	sx_init(&V_pf_ioctl_lock, "pf ioctl");
6675 
6676 	pf_init_tagset(&V_pf_tags, &pf_rule_tag_hashsize,
6677 	    PF_RULE_TAG_HASH_SIZE_DEFAULT);
6678 #ifdef ALTQ
6679 	pf_init_tagset(&V_pf_qids, &pf_queue_tag_hashsize,
6680 	    PF_QUEUE_TAG_HASH_SIZE_DEFAULT);
6681 #endif
6682 
6683 	V_pf_keth = &V_pf_main_keth_anchor.ruleset;
6684 
6685 	pfattach_vnet();
6686 	V_pf_vnet_active = 1;
6687 }
6688 
6689 static int
6690 pf_load(void)
6691 {
6692 	int error;
6693 
6694 	sx_init(&pf_end_lock, "pf end thread");
6695 
6696 	pf_mtag_initialize();
6697 
6698 	pf_dev = make_dev(&pf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, PF_NAME);
6699 	if (pf_dev == NULL)
6700 		return (ENOMEM);
6701 
6702 	pf_end_threads = 0;
6703 	error = kproc_create(pf_purge_thread, NULL, &pf_purge_proc, 0, 0, "pf purge");
6704 	if (error != 0)
6705 		return (error);
6706 
6707 	pfi_initialize();
6708 
6709 	return (0);
6710 }
6711 
6712 static void
6713 pf_unload_vnet(void)
6714 {
6715 	int ret __diagused;
6716 
6717 	V_pf_vnet_active = 0;
6718 	V_pf_status.running = 0;
6719 	dehook_pf();
6720 	dehook_pf_eth();
6721 
6722 	PF_RULES_WLOCK();
6723 	pf_syncookies_cleanup();
6724 	shutdown_pf();
6725 	PF_RULES_WUNLOCK();
6726 
6727 	/* Make sure we've cleaned up ethernet rules before we continue. */
6728 	NET_EPOCH_DRAIN_CALLBACKS();
6729 
6730 	ret = swi_remove(V_pf_swi_cookie);
6731 	MPASS(ret == 0);
6732 	ret = intr_event_destroy(V_pf_swi_ie);
6733 	MPASS(ret == 0);
6734 
6735 	pf_unload_vnet_purge();
6736 
6737 	pf_normalize_cleanup();
6738 	PF_RULES_WLOCK();
6739 	pfi_cleanup_vnet();
6740 	PF_RULES_WUNLOCK();
6741 	pfr_cleanup();
6742 	pf_osfp_flush();
6743 	pf_cleanup();
6744 	if (IS_DEFAULT_VNET(curvnet))
6745 		pf_mtag_cleanup();
6746 
6747 	pf_cleanup_tagset(&V_pf_tags);
6748 #ifdef ALTQ
6749 	pf_cleanup_tagset(&V_pf_qids);
6750 #endif
6751 	uma_zdestroy(V_pf_tag_z);
6752 
6753 #ifdef PF_WANT_32_TO_64_COUNTER
6754 	PF_RULES_WLOCK();
6755 	LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
6756 
6757 	MPASS(LIST_EMPTY(&V_pf_allkiflist));
6758 	MPASS(V_pf_allkifcount == 0);
6759 
6760 	LIST_REMOVE(&V_pf_default_rule, allrulelist);
6761 	V_pf_allrulecount--;
6762 	LIST_REMOVE(V_pf_rulemarker, allrulelist);
6763 
6764 	MPASS(LIST_EMPTY(&V_pf_allrulelist));
6765 	MPASS(V_pf_allrulecount == 0);
6766 
6767 	PF_RULES_WUNLOCK();
6768 
6769 	free(V_pf_kifmarker, PFI_MTYPE);
6770 	free(V_pf_rulemarker, M_PFRULE);
6771 #endif
6772 
6773 	/* Free counters last as we updated them during shutdown. */
6774 	pf_counter_u64_deinit(&V_pf_default_rule.evaluations);
6775 	for (int i = 0; i < 2; i++) {
6776 		pf_counter_u64_deinit(&V_pf_default_rule.packets[i]);
6777 		pf_counter_u64_deinit(&V_pf_default_rule.bytes[i]);
6778 	}
6779 	counter_u64_free(V_pf_default_rule.states_cur);
6780 	counter_u64_free(V_pf_default_rule.states_tot);
6781 	counter_u64_free(V_pf_default_rule.src_nodes);
6782 	uma_zfree_pcpu(pf_timestamp_pcpu_zone, V_pf_default_rule.timestamp);
6783 
6784 	for (int i = 0; i < PFRES_MAX; i++)
6785 		counter_u64_free(V_pf_status.counters[i]);
6786 	for (int i = 0; i < KLCNT_MAX; i++)
6787 		counter_u64_free(V_pf_status.lcounters[i]);
6788 	for (int i = 0; i < FCNT_MAX; i++)
6789 		pf_counter_u64_deinit(&V_pf_status.fcounters[i]);
6790 	for (int i = 0; i < SCNT_MAX; i++)
6791 		counter_u64_free(V_pf_status.scounters[i]);
6792 
6793 	rm_destroy(&V_pf_rules_lock);
6794 	sx_destroy(&V_pf_ioctl_lock);
6795 }
6796 
6797 static void
6798 pf_unload(void)
6799 {
6800 
6801 	sx_xlock(&pf_end_lock);
6802 	pf_end_threads = 1;
6803 	while (pf_end_threads < 2) {
6804 		wakeup_one(pf_purge_thread);
6805 		sx_sleep(pf_purge_proc, &pf_end_lock, 0, "pftmo", 0);
6806 	}
6807 	sx_xunlock(&pf_end_lock);
6808 
6809 	pf_nl_unregister();
6810 
6811 	if (pf_dev != NULL)
6812 		destroy_dev(pf_dev);
6813 
6814 	pfi_cleanup();
6815 
6816 	sx_destroy(&pf_end_lock);
6817 }
6818 
6819 static void
6820 vnet_pf_init(void *unused __unused)
6821 {
6822 
6823 	pf_load_vnet();
6824 }
6825 VNET_SYSINIT(vnet_pf_init, SI_SUB_PROTO_FIREWALL, SI_ORDER_THIRD,
6826     vnet_pf_init, NULL);
6827 
6828 static void
6829 vnet_pf_uninit(const void *unused __unused)
6830 {
6831 
6832 	pf_unload_vnet();
6833 }
6834 SYSUNINIT(pf_unload, SI_SUB_PROTO_FIREWALL, SI_ORDER_SECOND, pf_unload, NULL);
6835 VNET_SYSUNINIT(vnet_pf_uninit, SI_SUB_PROTO_FIREWALL, SI_ORDER_THIRD,
6836     vnet_pf_uninit, NULL);
6837 
6838 static int
6839 pf_modevent(module_t mod, int type, void *data)
6840 {
6841 	int error = 0;
6842 
6843 	switch(type) {
6844 	case MOD_LOAD:
6845 		error = pf_load();
6846 		pf_nl_register();
6847 		break;
6848 	case MOD_UNLOAD:
6849 		/* Handled in SYSUNINIT(pf_unload) to ensure it's done after
6850 		 * the vnet_pf_uninit()s */
6851 		break;
6852 	default:
6853 		error = EINVAL;
6854 		break;
6855 	}
6856 
6857 	return (error);
6858 }
6859 
6860 static moduledata_t pf_mod = {
6861 	"pf",
6862 	pf_modevent,
6863 	0
6864 };
6865 
6866 DECLARE_MODULE(pf, pf_mod, SI_SUB_PROTO_FIREWALL, SI_ORDER_SECOND);
6867 MODULE_DEPEND(pf, netlink, 1, 1, 1);
6868 MODULE_VERSION(pf, PF_MODVER);
6869