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