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