xref: /freebsd/sys/netpfil/pf/pf_ioctl.c (revision 13ec1e3155c7e9bf037b12af186351b7fa9b9450)
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 struct pf_krule *
1516 pf_krule_alloc(void)
1517 {
1518 	struct pf_krule *rule;
1519 
1520 	rule = malloc(sizeof(struct pf_krule), M_PFRULE, M_WAITOK | M_ZERO);
1521 	mtx_init(&rule->rpool.mtx, "pf_krule_pool", NULL, MTX_DEF);
1522 	return (rule);
1523 }
1524 
1525 void
1526 pf_krule_free(struct pf_krule *rule)
1527 {
1528 #ifdef PF_WANT_32_TO_64_COUNTER
1529 	bool wowned;
1530 #endif
1531 
1532 	if (rule == NULL)
1533 		return;
1534 
1535 #ifdef PF_WANT_32_TO_64_COUNTER
1536 	if (rule->allrulelinked) {
1537 		wowned = PF_RULES_WOWNED();
1538 		if (!wowned)
1539 			PF_RULES_WLOCK();
1540 		LIST_REMOVE(rule, allrulelist);
1541 		V_pf_allrulecount--;
1542 		if (!wowned)
1543 			PF_RULES_WUNLOCK();
1544 	}
1545 #endif
1546 
1547 	pf_counter_u64_deinit(&rule->evaluations);
1548 	for (int i = 0; i < 2; i++) {
1549 		pf_counter_u64_deinit(&rule->packets[i]);
1550 		pf_counter_u64_deinit(&rule->bytes[i]);
1551 	}
1552 	counter_u64_free(rule->states_cur);
1553 	counter_u64_free(rule->states_tot);
1554 	counter_u64_free(rule->src_nodes);
1555 
1556 	mtx_destroy(&rule->rpool.mtx);
1557 	free(rule, M_PFRULE);
1558 }
1559 
1560 static void
1561 pf_kpooladdr_to_pooladdr(const struct pf_kpooladdr *kpool,
1562     struct pf_pooladdr *pool)
1563 {
1564 
1565 	bzero(pool, sizeof(*pool));
1566 	bcopy(&kpool->addr, &pool->addr, sizeof(pool->addr));
1567 	strlcpy(pool->ifname, kpool->ifname, sizeof(pool->ifname));
1568 }
1569 
1570 static int
1571 pf_pooladdr_to_kpooladdr(const struct pf_pooladdr *pool,
1572     struct pf_kpooladdr *kpool)
1573 {
1574 	int ret;
1575 
1576 	bzero(kpool, sizeof(*kpool));
1577 	bcopy(&pool->addr, &kpool->addr, sizeof(kpool->addr));
1578 	ret = pf_user_strcpy(kpool->ifname, pool->ifname,
1579 	    sizeof(kpool->ifname));
1580 	return (ret);
1581 }
1582 
1583 static void
1584 pf_kpool_to_pool(const struct pf_kpool *kpool, struct pf_pool *pool)
1585 {
1586 	bzero(pool, sizeof(*pool));
1587 
1588 	bcopy(&kpool->key, &pool->key, sizeof(pool->key));
1589 	bcopy(&kpool->counter, &pool->counter, sizeof(pool->counter));
1590 
1591 	pool->tblidx = kpool->tblidx;
1592 	pool->proxy_port[0] = kpool->proxy_port[0];
1593 	pool->proxy_port[1] = kpool->proxy_port[1];
1594 	pool->opts = kpool->opts;
1595 }
1596 
1597 static void
1598 pf_pool_to_kpool(const struct pf_pool *pool, struct pf_kpool *kpool)
1599 {
1600 	_Static_assert(sizeof(pool->key) == sizeof(kpool->key), "");
1601 	_Static_assert(sizeof(pool->counter) == sizeof(kpool->counter), "");
1602 
1603 	bcopy(&pool->key, &kpool->key, sizeof(kpool->key));
1604 	bcopy(&pool->counter, &kpool->counter, sizeof(kpool->counter));
1605 
1606 	kpool->tblidx = pool->tblidx;
1607 	kpool->proxy_port[0] = pool->proxy_port[0];
1608 	kpool->proxy_port[1] = pool->proxy_port[1];
1609 	kpool->opts = pool->opts;
1610 }
1611 
1612 static void
1613 pf_krule_to_rule(const struct pf_krule *krule, struct pf_rule *rule)
1614 {
1615 
1616 	bzero(rule, sizeof(*rule));
1617 
1618 	bcopy(&krule->src, &rule->src, sizeof(rule->src));
1619 	bcopy(&krule->dst, &rule->dst, sizeof(rule->dst));
1620 
1621 	for (int i = 0; i < PF_SKIP_COUNT; ++i) {
1622 		if (rule->skip[i].ptr == NULL)
1623 			rule->skip[i].nr = -1;
1624 		else
1625 			rule->skip[i].nr = krule->skip[i].ptr->nr;
1626 	}
1627 
1628 	strlcpy(rule->label, krule->label[0], sizeof(rule->label));
1629 	strlcpy(rule->ifname, krule->ifname, sizeof(rule->ifname));
1630 	strlcpy(rule->qname, krule->qname, sizeof(rule->qname));
1631 	strlcpy(rule->pqname, krule->pqname, sizeof(rule->pqname));
1632 	strlcpy(rule->tagname, krule->tagname, sizeof(rule->tagname));
1633 	strlcpy(rule->match_tagname, krule->match_tagname,
1634 	    sizeof(rule->match_tagname));
1635 	strlcpy(rule->overload_tblname, krule->overload_tblname,
1636 	    sizeof(rule->overload_tblname));
1637 
1638 	pf_kpool_to_pool(&krule->rpool, &rule->rpool);
1639 
1640 	rule->evaluations = pf_counter_u64_fetch(&krule->evaluations);
1641 	for (int i = 0; i < 2; i++) {
1642 		rule->packets[i] = pf_counter_u64_fetch(&krule->packets[i]);
1643 		rule->bytes[i] = pf_counter_u64_fetch(&krule->bytes[i]);
1644 	}
1645 
1646 	/* kif, anchor, overload_tbl are not copied over. */
1647 
1648 	rule->os_fingerprint = krule->os_fingerprint;
1649 
1650 	rule->rtableid = krule->rtableid;
1651 	bcopy(krule->timeout, rule->timeout, sizeof(krule->timeout));
1652 	rule->max_states = krule->max_states;
1653 	rule->max_src_nodes = krule->max_src_nodes;
1654 	rule->max_src_states = krule->max_src_states;
1655 	rule->max_src_conn = krule->max_src_conn;
1656 	rule->max_src_conn_rate.limit = krule->max_src_conn_rate.limit;
1657 	rule->max_src_conn_rate.seconds = krule->max_src_conn_rate.seconds;
1658 	rule->qid = krule->qid;
1659 	rule->pqid = krule->pqid;
1660 	rule->nr = krule->nr;
1661 	rule->prob = krule->prob;
1662 	rule->cuid = krule->cuid;
1663 	rule->cpid = krule->cpid;
1664 
1665 	rule->return_icmp = krule->return_icmp;
1666 	rule->return_icmp6 = krule->return_icmp6;
1667 	rule->max_mss = krule->max_mss;
1668 	rule->tag = krule->tag;
1669 	rule->match_tag = krule->match_tag;
1670 	rule->scrub_flags = krule->scrub_flags;
1671 
1672 	bcopy(&krule->uid, &rule->uid, sizeof(krule->uid));
1673 	bcopy(&krule->gid, &rule->gid, sizeof(krule->gid));
1674 
1675 	rule->rule_flag = krule->rule_flag;
1676 	rule->action = krule->action;
1677 	rule->direction = krule->direction;
1678 	rule->log = krule->log;
1679 	rule->logif = krule->logif;
1680 	rule->quick = krule->quick;
1681 	rule->ifnot = krule->ifnot;
1682 	rule->match_tag_not = krule->match_tag_not;
1683 	rule->natpass = krule->natpass;
1684 
1685 	rule->keep_state = krule->keep_state;
1686 	rule->af = krule->af;
1687 	rule->proto = krule->proto;
1688 	rule->type = krule->type;
1689 	rule->code = krule->code;
1690 	rule->flags = krule->flags;
1691 	rule->flagset = krule->flagset;
1692 	rule->min_ttl = krule->min_ttl;
1693 	rule->allow_opts = krule->allow_opts;
1694 	rule->rt = krule->rt;
1695 	rule->return_ttl = krule->return_ttl;
1696 	rule->tos = krule->tos;
1697 	rule->set_tos = krule->set_tos;
1698 	rule->anchor_relative = krule->anchor_relative;
1699 	rule->anchor_wildcard = krule->anchor_wildcard;
1700 
1701 	rule->flush = krule->flush;
1702 	rule->prio = krule->prio;
1703 	rule->set_prio[0] = krule->set_prio[0];
1704 	rule->set_prio[1] = krule->set_prio[1];
1705 
1706 	bcopy(&krule->divert, &rule->divert, sizeof(krule->divert));
1707 
1708 	rule->u_states_cur = counter_u64_fetch(krule->states_cur);
1709 	rule->u_states_tot = counter_u64_fetch(krule->states_tot);
1710 	rule->u_src_nodes = counter_u64_fetch(krule->src_nodes);
1711 }
1712 
1713 static int
1714 pf_rule_to_krule(const struct pf_rule *rule, struct pf_krule *krule)
1715 {
1716 	int ret;
1717 
1718 #ifndef INET
1719 	if (rule->af == AF_INET) {
1720 		return (EAFNOSUPPORT);
1721 	}
1722 #endif /* INET */
1723 #ifndef INET6
1724 	if (rule->af == AF_INET6) {
1725 		return (EAFNOSUPPORT);
1726 	}
1727 #endif /* INET6 */
1728 
1729 	ret = pf_check_rule_addr(&rule->src);
1730 	if (ret != 0)
1731 		return (ret);
1732 	ret = pf_check_rule_addr(&rule->dst);
1733 	if (ret != 0)
1734 		return (ret);
1735 
1736 	bcopy(&rule->src, &krule->src, sizeof(rule->src));
1737 	bcopy(&rule->dst, &krule->dst, sizeof(rule->dst));
1738 
1739 	ret = pf_user_strcpy(krule->label[0], rule->label, sizeof(rule->label));
1740 	if (ret != 0)
1741 		return (ret);
1742 	ret = pf_user_strcpy(krule->ifname, rule->ifname, sizeof(rule->ifname));
1743 	if (ret != 0)
1744 		return (ret);
1745 	ret = pf_user_strcpy(krule->qname, rule->qname, sizeof(rule->qname));
1746 	if (ret != 0)
1747 		return (ret);
1748 	ret = pf_user_strcpy(krule->pqname, rule->pqname, sizeof(rule->pqname));
1749 	if (ret != 0)
1750 		return (ret);
1751 	ret = pf_user_strcpy(krule->tagname, rule->tagname,
1752 	    sizeof(rule->tagname));
1753 	if (ret != 0)
1754 		return (ret);
1755 	ret = pf_user_strcpy(krule->match_tagname, rule->match_tagname,
1756 	    sizeof(rule->match_tagname));
1757 	if (ret != 0)
1758 		return (ret);
1759 	ret = pf_user_strcpy(krule->overload_tblname, rule->overload_tblname,
1760 	    sizeof(rule->overload_tblname));
1761 	if (ret != 0)
1762 		return (ret);
1763 
1764 	pf_pool_to_kpool(&rule->rpool, &krule->rpool);
1765 
1766 	/* Don't allow userspace to set evaulations, packets or bytes. */
1767 	/* kif, anchor, overload_tbl are not copied over. */
1768 
1769 	krule->os_fingerprint = rule->os_fingerprint;
1770 
1771 	krule->rtableid = rule->rtableid;
1772 	bcopy(rule->timeout, krule->timeout, sizeof(krule->timeout));
1773 	krule->max_states = rule->max_states;
1774 	krule->max_src_nodes = rule->max_src_nodes;
1775 	krule->max_src_states = rule->max_src_states;
1776 	krule->max_src_conn = rule->max_src_conn;
1777 	krule->max_src_conn_rate.limit = rule->max_src_conn_rate.limit;
1778 	krule->max_src_conn_rate.seconds = rule->max_src_conn_rate.seconds;
1779 	krule->qid = rule->qid;
1780 	krule->pqid = rule->pqid;
1781 	krule->nr = rule->nr;
1782 	krule->prob = rule->prob;
1783 	krule->cuid = rule->cuid;
1784 	krule->cpid = rule->cpid;
1785 
1786 	krule->return_icmp = rule->return_icmp;
1787 	krule->return_icmp6 = rule->return_icmp6;
1788 	krule->max_mss = rule->max_mss;
1789 	krule->tag = rule->tag;
1790 	krule->match_tag = rule->match_tag;
1791 	krule->scrub_flags = rule->scrub_flags;
1792 
1793 	bcopy(&rule->uid, &krule->uid, sizeof(krule->uid));
1794 	bcopy(&rule->gid, &krule->gid, sizeof(krule->gid));
1795 
1796 	krule->rule_flag = rule->rule_flag;
1797 	krule->action = rule->action;
1798 	krule->direction = rule->direction;
1799 	krule->log = rule->log;
1800 	krule->logif = rule->logif;
1801 	krule->quick = rule->quick;
1802 	krule->ifnot = rule->ifnot;
1803 	krule->match_tag_not = rule->match_tag_not;
1804 	krule->natpass = rule->natpass;
1805 
1806 	krule->keep_state = rule->keep_state;
1807 	krule->af = rule->af;
1808 	krule->proto = rule->proto;
1809 	krule->type = rule->type;
1810 	krule->code = rule->code;
1811 	krule->flags = rule->flags;
1812 	krule->flagset = rule->flagset;
1813 	krule->min_ttl = rule->min_ttl;
1814 	krule->allow_opts = rule->allow_opts;
1815 	krule->rt = rule->rt;
1816 	krule->return_ttl = rule->return_ttl;
1817 	krule->tos = rule->tos;
1818 	krule->set_tos = rule->set_tos;
1819 
1820 	krule->flush = rule->flush;
1821 	krule->prio = rule->prio;
1822 	krule->set_prio[0] = rule->set_prio[0];
1823 	krule->set_prio[1] = rule->set_prio[1];
1824 
1825 	bcopy(&rule->divert, &krule->divert, sizeof(krule->divert));
1826 
1827 	return (0);
1828 }
1829 
1830 static int
1831 pf_state_kill_to_kstate_kill(const struct pfioc_state_kill *psk,
1832     struct pf_kstate_kill *kill)
1833 {
1834 	int ret;
1835 
1836 	bzero(kill, sizeof(*kill));
1837 
1838 	bcopy(&psk->psk_pfcmp, &kill->psk_pfcmp, sizeof(kill->psk_pfcmp));
1839 	kill->psk_af = psk->psk_af;
1840 	kill->psk_proto = psk->psk_proto;
1841 	bcopy(&psk->psk_src, &kill->psk_src, sizeof(kill->psk_src));
1842 	bcopy(&psk->psk_dst, &kill->psk_dst, sizeof(kill->psk_dst));
1843 	ret = pf_user_strcpy(kill->psk_ifname, psk->psk_ifname,
1844 	    sizeof(kill->psk_ifname));
1845 	if (ret != 0)
1846 		return (ret);
1847 	ret = pf_user_strcpy(kill->psk_label, psk->psk_label,
1848 	    sizeof(kill->psk_label));
1849 	if (ret != 0)
1850 		return (ret);
1851 
1852 	return (0);
1853 }
1854 
1855 static int
1856 pf_ioctl_addrule(struct pf_krule *rule, uint32_t ticket,
1857     uint32_t pool_ticket, const char *anchor, const char *anchor_call,
1858     struct thread *td)
1859 {
1860 	struct pf_kruleset	*ruleset;
1861 	struct pf_krule		*tail;
1862 	struct pf_kpooladdr	*pa;
1863 	struct pfi_kkif		*kif = NULL;
1864 	int			 rs_num;
1865 	int			 error = 0;
1866 
1867 	if ((rule->return_icmp >> 8) > ICMP_MAXTYPE) {
1868 		error = EINVAL;
1869 		goto errout_unlocked;
1870 	}
1871 
1872 #define	ERROUT(x)	ERROUT_FUNCTION(errout, x)
1873 
1874 	if (rule->ifname[0])
1875 		kif = pf_kkif_create(M_WAITOK);
1876 	pf_counter_u64_init(&rule->evaluations, M_WAITOK);
1877 	for (int i = 0; i < 2; i++) {
1878 		pf_counter_u64_init(&rule->packets[i], M_WAITOK);
1879 		pf_counter_u64_init(&rule->bytes[i], M_WAITOK);
1880 	}
1881 	rule->states_cur = counter_u64_alloc(M_WAITOK);
1882 	rule->states_tot = counter_u64_alloc(M_WAITOK);
1883 	rule->src_nodes = counter_u64_alloc(M_WAITOK);
1884 	rule->cuid = td->td_ucred->cr_ruid;
1885 	rule->cpid = td->td_proc ? td->td_proc->p_pid : 0;
1886 	TAILQ_INIT(&rule->rpool.list);
1887 
1888 	PF_RULES_WLOCK();
1889 #ifdef PF_WANT_32_TO_64_COUNTER
1890 	LIST_INSERT_HEAD(&V_pf_allrulelist, rule, allrulelist);
1891 	MPASS(!rule->allrulelinked);
1892 	rule->allrulelinked = true;
1893 	V_pf_allrulecount++;
1894 #endif
1895 	ruleset = pf_find_kruleset(anchor);
1896 	if (ruleset == NULL)
1897 		ERROUT(EINVAL);
1898 	rs_num = pf_get_ruleset_number(rule->action);
1899 	if (rs_num >= PF_RULESET_MAX)
1900 		ERROUT(EINVAL);
1901 	if (ticket != ruleset->rules[rs_num].inactive.ticket) {
1902 		DPFPRINTF(PF_DEBUG_MISC,
1903 		    ("ticket: %d != [%d]%d\n", ticket, rs_num,
1904 		    ruleset->rules[rs_num].inactive.ticket));
1905 		ERROUT(EBUSY);
1906 	}
1907 	if (pool_ticket != V_ticket_pabuf) {
1908 		DPFPRINTF(PF_DEBUG_MISC,
1909 		    ("pool_ticket: %d != %d\n", pool_ticket,
1910 		    V_ticket_pabuf));
1911 		ERROUT(EBUSY);
1912 	}
1913 
1914 	tail = TAILQ_LAST(ruleset->rules[rs_num].inactive.ptr,
1915 	    pf_krulequeue);
1916 	if (tail)
1917 		rule->nr = tail->nr + 1;
1918 	else
1919 		rule->nr = 0;
1920 	if (rule->ifname[0]) {
1921 		rule->kif = pfi_kkif_attach(kif, rule->ifname);
1922 		kif = NULL;
1923 		pfi_kkif_ref(rule->kif);
1924 	} else
1925 		rule->kif = NULL;
1926 
1927 	if (rule->rtableid > 0 && rule->rtableid >= rt_numfibs)
1928 		error = EBUSY;
1929 
1930 #ifdef ALTQ
1931 	/* set queue IDs */
1932 	if (rule->qname[0] != 0) {
1933 		if ((rule->qid = pf_qname2qid(rule->qname)) == 0)
1934 			error = EBUSY;
1935 		else if (rule->pqname[0] != 0) {
1936 			if ((rule->pqid =
1937 			    pf_qname2qid(rule->pqname)) == 0)
1938 				error = EBUSY;
1939 		} else
1940 			rule->pqid = rule->qid;
1941 	}
1942 #endif
1943 	if (rule->tagname[0])
1944 		if ((rule->tag = pf_tagname2tag(rule->tagname)) == 0)
1945 			error = EBUSY;
1946 	if (rule->match_tagname[0])
1947 		if ((rule->match_tag =
1948 		    pf_tagname2tag(rule->match_tagname)) == 0)
1949 			error = EBUSY;
1950 	if (rule->rt && !rule->direction)
1951 		error = EINVAL;
1952 	if (!rule->log)
1953 		rule->logif = 0;
1954 	if (rule->logif >= PFLOGIFS_MAX)
1955 		error = EINVAL;
1956 	if (pf_addr_setup(ruleset, &rule->src.addr, rule->af))
1957 		error = ENOMEM;
1958 	if (pf_addr_setup(ruleset, &rule->dst.addr, rule->af))
1959 		error = ENOMEM;
1960 	if (pf_kanchor_setup(rule, ruleset, anchor_call))
1961 		error = EINVAL;
1962 	if (rule->scrub_flags & PFSTATE_SETPRIO &&
1963 	    (rule->set_prio[0] > PF_PRIO_MAX ||
1964 	    rule->set_prio[1] > PF_PRIO_MAX))
1965 		error = EINVAL;
1966 	TAILQ_FOREACH(pa, &V_pf_pabuf, entries)
1967 		if (pa->addr.type == PF_ADDR_TABLE) {
1968 			pa->addr.p.tbl = pfr_attach_table(ruleset,
1969 			    pa->addr.v.tblname);
1970 			if (pa->addr.p.tbl == NULL)
1971 				error = ENOMEM;
1972 		}
1973 
1974 	rule->overload_tbl = NULL;
1975 	if (rule->overload_tblname[0]) {
1976 		if ((rule->overload_tbl = pfr_attach_table(ruleset,
1977 		    rule->overload_tblname)) == NULL)
1978 			error = EINVAL;
1979 		else
1980 			rule->overload_tbl->pfrkt_flags |=
1981 			    PFR_TFLAG_ACTIVE;
1982 	}
1983 
1984 	pf_mv_kpool(&V_pf_pabuf, &rule->rpool.list);
1985 	if (((((rule->action == PF_NAT) || (rule->action == PF_RDR) ||
1986 	    (rule->action == PF_BINAT)) && rule->anchor == NULL) ||
1987 	    (rule->rt > PF_NOPFROUTE)) &&
1988 	    (TAILQ_FIRST(&rule->rpool.list) == NULL))
1989 		error = EINVAL;
1990 
1991 	if (error) {
1992 		pf_free_rule(rule);
1993 		rule = NULL;
1994 		ERROUT(error);
1995 	}
1996 
1997 	rule->rpool.cur = TAILQ_FIRST(&rule->rpool.list);
1998 	pf_counter_u64_zero(&rule->evaluations);
1999 	for (int i = 0; i < 2; i++) {
2000 		pf_counter_u64_zero(&rule->packets[i]);
2001 		pf_counter_u64_zero(&rule->bytes[i]);
2002 	}
2003 	TAILQ_INSERT_TAIL(ruleset->rules[rs_num].inactive.ptr,
2004 	    rule, entries);
2005 	ruleset->rules[rs_num].inactive.rcount++;
2006 
2007 	PF_RULES_WUNLOCK();
2008 
2009 	return (0);
2010 
2011 #undef ERROUT
2012 errout:
2013 	PF_RULES_WUNLOCK();
2014 errout_unlocked:
2015 	pf_kkif_free(kif);
2016 	pf_krule_free(rule);
2017 	return (error);
2018 }
2019 
2020 static bool
2021 pf_label_match(const struct pf_krule *rule, const char *label)
2022 {
2023 	int i = 0;
2024 
2025 	while (*rule->label[i]) {
2026 		if (strcmp(rule->label[i], label) == 0)
2027 			return (true);
2028 		i++;
2029 	}
2030 
2031 	return (false);
2032 }
2033 
2034 static unsigned int
2035 pf_kill_matching_state(struct pf_state_key_cmp *key, int dir)
2036 {
2037 	struct pf_kstate *s;
2038 	int more = 0;
2039 
2040 	s = pf_find_state_all(key, dir, &more);
2041 	if (s == NULL)
2042 		return (0);
2043 
2044 	if (more) {
2045 		PF_STATE_UNLOCK(s);
2046 		return (0);
2047 	}
2048 
2049 	pf_unlink_state(s);
2050 	return (1);
2051 }
2052 
2053 static int
2054 pf_killstates_row(struct pf_kstate_kill *psk, struct pf_idhash *ih)
2055 {
2056 	struct pf_kstate	*s;
2057 	struct pf_state_key	*sk;
2058 	struct pf_addr		*srcaddr, *dstaddr;
2059 	struct pf_state_key_cmp	 match_key;
2060 	int			 idx, killed = 0;
2061 	unsigned int		 dir;
2062 	u_int16_t		 srcport, dstport;
2063 	struct pfi_kkif		*kif;
2064 
2065 relock_DIOCKILLSTATES:
2066 	PF_HASHROW_LOCK(ih);
2067 	LIST_FOREACH(s, &ih->states, entry) {
2068 		/* For floating states look at the original kif. */
2069 		kif = s->kif == V_pfi_all ? s->orig_kif : s->kif;
2070 
2071 		sk = s->key[PF_SK_WIRE];
2072 		if (s->direction == PF_OUT) {
2073 			srcaddr = &sk->addr[1];
2074 			dstaddr = &sk->addr[0];
2075 			srcport = sk->port[1];
2076 			dstport = sk->port[0];
2077 		} else {
2078 			srcaddr = &sk->addr[0];
2079 			dstaddr = &sk->addr[1];
2080 			srcport = sk->port[0];
2081 			dstport = sk->port[1];
2082 		}
2083 
2084 		if (psk->psk_af && sk->af != psk->psk_af)
2085 			continue;
2086 
2087 		if (psk->psk_proto && psk->psk_proto != sk->proto)
2088 			continue;
2089 
2090 		if (! PF_MATCHA(psk->psk_src.neg, &psk->psk_src.addr.v.a.addr,
2091 		    &psk->psk_src.addr.v.a.mask, srcaddr, sk->af))
2092 			continue;
2093 
2094 		if (! PF_MATCHA(psk->psk_dst.neg, &psk->psk_dst.addr.v.a.addr,
2095 		    &psk->psk_dst.addr.v.a.mask, dstaddr, sk->af))
2096 			continue;
2097 
2098 		if (!  PF_MATCHA(psk->psk_rt_addr.neg,
2099 		    &psk->psk_rt_addr.addr.v.a.addr,
2100 		    &psk->psk_rt_addr.addr.v.a.mask,
2101 		    &s->rt_addr, sk->af))
2102 			continue;
2103 
2104 		if (psk->psk_src.port_op != 0 &&
2105 		    ! pf_match_port(psk->psk_src.port_op,
2106 		    psk->psk_src.port[0], psk->psk_src.port[1], srcport))
2107 			continue;
2108 
2109 		if (psk->psk_dst.port_op != 0 &&
2110 		    ! pf_match_port(psk->psk_dst.port_op,
2111 		    psk->psk_dst.port[0], psk->psk_dst.port[1], dstport))
2112 			continue;
2113 
2114 		if (psk->psk_label[0] &&
2115 		    ! pf_label_match(s->rule.ptr, psk->psk_label))
2116 			continue;
2117 
2118 		if (psk->psk_ifname[0] && strcmp(psk->psk_ifname,
2119 		    kif->pfik_name))
2120 			continue;
2121 
2122 		if (psk->psk_kill_match) {
2123 			/* Create the key to find matching states, with lock
2124 			 * held. */
2125 
2126 			bzero(&match_key, sizeof(match_key));
2127 
2128 			if (s->direction == PF_OUT) {
2129 				dir = PF_IN;
2130 				idx = PF_SK_STACK;
2131 			} else {
2132 				dir = PF_OUT;
2133 				idx = PF_SK_WIRE;
2134 			}
2135 
2136 			match_key.af = s->key[idx]->af;
2137 			match_key.proto = s->key[idx]->proto;
2138 			PF_ACPY(&match_key.addr[0],
2139 			    &s->key[idx]->addr[1], match_key.af);
2140 			match_key.port[0] = s->key[idx]->port[1];
2141 			PF_ACPY(&match_key.addr[1],
2142 			    &s->key[idx]->addr[0], match_key.af);
2143 			match_key.port[1] = s->key[idx]->port[0];
2144 		}
2145 
2146 		pf_unlink_state(s);
2147 		killed++;
2148 
2149 		if (psk->psk_kill_match)
2150 			killed += pf_kill_matching_state(&match_key, dir);
2151 
2152 		goto relock_DIOCKILLSTATES;
2153 	}
2154 	PF_HASHROW_UNLOCK(ih);
2155 
2156 	return (killed);
2157 }
2158 
2159 static int
2160 pfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
2161 {
2162 	int			 error = 0;
2163 	PF_RULES_RLOCK_TRACKER;
2164 
2165 #define	ERROUT_IOCTL(target, x)					\
2166     do {								\
2167 	    error = (x);						\
2168 	    SDT_PROBE3(pf, ioctl, ioctl, error, cmd, error, __LINE__);	\
2169 	    goto target;						\
2170     } while (0)
2171 
2172 
2173 	/* XXX keep in sync with switch() below */
2174 	if (securelevel_gt(td->td_ucred, 2))
2175 		switch (cmd) {
2176 		case DIOCGETRULES:
2177 		case DIOCGETRULE:
2178 		case DIOCGETRULENV:
2179 		case DIOCGETADDRS:
2180 		case DIOCGETADDR:
2181 		case DIOCGETSTATE:
2182 		case DIOCGETSTATENV:
2183 		case DIOCSETSTATUSIF:
2184 		case DIOCGETSTATUS:
2185 		case DIOCGETSTATUSNV:
2186 		case DIOCCLRSTATUS:
2187 		case DIOCNATLOOK:
2188 		case DIOCSETDEBUG:
2189 		case DIOCGETSTATES:
2190 		case DIOCGETSTATESV2:
2191 		case DIOCGETTIMEOUT:
2192 		case DIOCCLRRULECTRS:
2193 		case DIOCGETLIMIT:
2194 		case DIOCGETALTQSV0:
2195 		case DIOCGETALTQSV1:
2196 		case DIOCGETALTQV0:
2197 		case DIOCGETALTQV1:
2198 		case DIOCGETQSTATSV0:
2199 		case DIOCGETQSTATSV1:
2200 		case DIOCGETRULESETS:
2201 		case DIOCGETRULESET:
2202 		case DIOCRGETTABLES:
2203 		case DIOCRGETTSTATS:
2204 		case DIOCRCLRTSTATS:
2205 		case DIOCRCLRADDRS:
2206 		case DIOCRADDADDRS:
2207 		case DIOCRDELADDRS:
2208 		case DIOCRSETADDRS:
2209 		case DIOCRGETADDRS:
2210 		case DIOCRGETASTATS:
2211 		case DIOCRCLRASTATS:
2212 		case DIOCRTSTADDRS:
2213 		case DIOCOSFPGET:
2214 		case DIOCGETSRCNODES:
2215 		case DIOCCLRSRCNODES:
2216 		case DIOCGETSYNCOOKIES:
2217 		case DIOCIGETIFACES:
2218 		case DIOCGIFSPEEDV0:
2219 		case DIOCGIFSPEEDV1:
2220 		case DIOCSETIFFLAG:
2221 		case DIOCCLRIFFLAG:
2222 			break;
2223 		case DIOCRCLRTABLES:
2224 		case DIOCRADDTABLES:
2225 		case DIOCRDELTABLES:
2226 		case DIOCRSETTFLAGS:
2227 			if (((struct pfioc_table *)addr)->pfrio_flags &
2228 			    PFR_FLAG_DUMMY)
2229 				break; /* dummy operation ok */
2230 			return (EPERM);
2231 		default:
2232 			return (EPERM);
2233 		}
2234 
2235 	if (!(flags & FWRITE))
2236 		switch (cmd) {
2237 		case DIOCGETRULES:
2238 		case DIOCGETADDRS:
2239 		case DIOCGETADDR:
2240 		case DIOCGETSTATE:
2241 		case DIOCGETSTATENV:
2242 		case DIOCGETSTATUS:
2243 		case DIOCGETSTATUSNV:
2244 		case DIOCGETSTATES:
2245 		case DIOCGETSTATESV2:
2246 		case DIOCGETTIMEOUT:
2247 		case DIOCGETLIMIT:
2248 		case DIOCGETALTQSV0:
2249 		case DIOCGETALTQSV1:
2250 		case DIOCGETALTQV0:
2251 		case DIOCGETALTQV1:
2252 		case DIOCGETQSTATSV0:
2253 		case DIOCGETQSTATSV1:
2254 		case DIOCGETRULESETS:
2255 		case DIOCGETRULESET:
2256 		case DIOCNATLOOK:
2257 		case DIOCRGETTABLES:
2258 		case DIOCRGETTSTATS:
2259 		case DIOCRGETADDRS:
2260 		case DIOCRGETASTATS:
2261 		case DIOCRTSTADDRS:
2262 		case DIOCOSFPGET:
2263 		case DIOCGETSRCNODES:
2264 		case DIOCGETSYNCOOKIES:
2265 		case DIOCIGETIFACES:
2266 		case DIOCGIFSPEEDV1:
2267 		case DIOCGIFSPEEDV0:
2268 		case DIOCGETRULENV:
2269 			break;
2270 		case DIOCRCLRTABLES:
2271 		case DIOCRADDTABLES:
2272 		case DIOCRDELTABLES:
2273 		case DIOCRCLRTSTATS:
2274 		case DIOCRCLRADDRS:
2275 		case DIOCRADDADDRS:
2276 		case DIOCRDELADDRS:
2277 		case DIOCRSETADDRS:
2278 		case DIOCRSETTFLAGS:
2279 			if (((struct pfioc_table *)addr)->pfrio_flags &
2280 			    PFR_FLAG_DUMMY) {
2281 				flags |= FWRITE; /* need write lock for dummy */
2282 				break; /* dummy operation ok */
2283 			}
2284 			return (EACCES);
2285 		case DIOCGETRULE:
2286 			if (((struct pfioc_rule *)addr)->action ==
2287 			    PF_GET_CLR_CNTR)
2288 				return (EACCES);
2289 			break;
2290 		default:
2291 			return (EACCES);
2292 		}
2293 
2294 	CURVNET_SET(TD_TO_VNET(td));
2295 
2296 	switch (cmd) {
2297 	case DIOCSTART:
2298 		sx_xlock(&pf_ioctl_lock);
2299 		if (V_pf_status.running)
2300 			error = EEXIST;
2301 		else {
2302 			int cpu;
2303 
2304 			hook_pf();
2305 			V_pf_status.running = 1;
2306 			V_pf_status.since = time_second;
2307 
2308 			CPU_FOREACH(cpu)
2309 				V_pf_stateid[cpu] = time_second;
2310 
2311 			DPFPRINTF(PF_DEBUG_MISC, ("pf: started\n"));
2312 		}
2313 		break;
2314 
2315 	case DIOCSTOP:
2316 		sx_xlock(&pf_ioctl_lock);
2317 		if (!V_pf_status.running)
2318 			error = ENOENT;
2319 		else {
2320 			V_pf_status.running = 0;
2321 			dehook_pf();
2322 			V_pf_status.since = time_second;
2323 			DPFPRINTF(PF_DEBUG_MISC, ("pf: stopped\n"));
2324 		}
2325 		break;
2326 
2327 	case DIOCADDRULENV: {
2328 		struct pfioc_nv	*nv = (struct pfioc_nv *)addr;
2329 		nvlist_t	*nvl = NULL;
2330 		void		*nvlpacked = NULL;
2331 		struct pf_krule	*rule = NULL;
2332 		const char	*anchor = "", *anchor_call = "";
2333 		uint32_t	 ticket = 0, pool_ticket = 0;
2334 
2335 #define	ERROUT(x)	ERROUT_IOCTL(DIOCADDRULENV_error, x)
2336 
2337 		if (nv->len > pf_ioctl_maxcount)
2338 			ERROUT(ENOMEM);
2339 
2340 		nvlpacked = malloc(nv->len, M_TEMP, M_WAITOK);
2341 		error = copyin(nv->data, nvlpacked, nv->len);
2342 		if (error)
2343 			ERROUT(error);
2344 
2345 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
2346 		if (nvl == NULL)
2347 			ERROUT(EBADMSG);
2348 
2349 		if (! nvlist_exists_number(nvl, "ticket"))
2350 			ERROUT(EINVAL);
2351 		ticket = nvlist_get_number(nvl, "ticket");
2352 
2353 		if (! nvlist_exists_number(nvl, "pool_ticket"))
2354 			ERROUT(EINVAL);
2355 		pool_ticket = nvlist_get_number(nvl, "pool_ticket");
2356 
2357 		if (! nvlist_exists_nvlist(nvl, "rule"))
2358 			ERROUT(EINVAL);
2359 
2360 		rule = pf_krule_alloc();
2361 		error = pf_nvrule_to_krule(nvlist_get_nvlist(nvl, "rule"),
2362 		    rule);
2363 		if (error)
2364 			ERROUT(error);
2365 
2366 		if (nvlist_exists_string(nvl, "anchor"))
2367 			anchor = nvlist_get_string(nvl, "anchor");
2368 		if (nvlist_exists_string(nvl, "anchor_call"))
2369 			anchor_call = nvlist_get_string(nvl, "anchor_call");
2370 
2371 		if ((error = nvlist_error(nvl)))
2372 			ERROUT(error);
2373 
2374 		/* Frees rule on error */
2375 		error = pf_ioctl_addrule(rule, ticket, pool_ticket, anchor,
2376 		    anchor_call, td);
2377 
2378 		nvlist_destroy(nvl);
2379 		free(nvlpacked, M_TEMP);
2380 		break;
2381 #undef ERROUT
2382 DIOCADDRULENV_error:
2383 		pf_krule_free(rule);
2384 		nvlist_destroy(nvl);
2385 		free(nvlpacked, M_TEMP);
2386 
2387 		break;
2388 	}
2389 	case DIOCADDRULE: {
2390 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
2391 		struct pf_krule		*rule;
2392 
2393 		rule = pf_krule_alloc();
2394 		error = pf_rule_to_krule(&pr->rule, rule);
2395 		if (error != 0) {
2396 			pf_krule_free(rule);
2397 			break;
2398 		}
2399 
2400 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
2401 
2402 		/* Frees rule on error */
2403 		error = pf_ioctl_addrule(rule, pr->ticket, pr->pool_ticket,
2404 		    pr->anchor, pr->anchor_call, td);
2405 		break;
2406 	}
2407 
2408 	case DIOCGETRULES: {
2409 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
2410 		struct pf_kruleset	*ruleset;
2411 		struct pf_krule		*tail;
2412 		int			 rs_num;
2413 
2414 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
2415 
2416 		PF_RULES_WLOCK();
2417 		ruleset = pf_find_kruleset(pr->anchor);
2418 		if (ruleset == NULL) {
2419 			PF_RULES_WUNLOCK();
2420 			error = EINVAL;
2421 			break;
2422 		}
2423 		rs_num = pf_get_ruleset_number(pr->rule.action);
2424 		if (rs_num >= PF_RULESET_MAX) {
2425 			PF_RULES_WUNLOCK();
2426 			error = EINVAL;
2427 			break;
2428 		}
2429 		tail = TAILQ_LAST(ruleset->rules[rs_num].active.ptr,
2430 		    pf_krulequeue);
2431 		if (tail)
2432 			pr->nr = tail->nr + 1;
2433 		else
2434 			pr->nr = 0;
2435 		pr->ticket = ruleset->rules[rs_num].active.ticket;
2436 		PF_RULES_WUNLOCK();
2437 		break;
2438 	}
2439 
2440 	case DIOCGETRULE: {
2441 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
2442 		struct pf_kruleset	*ruleset;
2443 		struct pf_krule		*rule;
2444 		int			 rs_num;
2445 
2446 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
2447 
2448 		PF_RULES_WLOCK();
2449 		ruleset = pf_find_kruleset(pr->anchor);
2450 		if (ruleset == NULL) {
2451 			PF_RULES_WUNLOCK();
2452 			error = EINVAL;
2453 			break;
2454 		}
2455 		rs_num = pf_get_ruleset_number(pr->rule.action);
2456 		if (rs_num >= PF_RULESET_MAX) {
2457 			PF_RULES_WUNLOCK();
2458 			error = EINVAL;
2459 			break;
2460 		}
2461 		if (pr->ticket != ruleset->rules[rs_num].active.ticket) {
2462 			PF_RULES_WUNLOCK();
2463 			error = EBUSY;
2464 			break;
2465 		}
2466 		rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
2467 		while ((rule != NULL) && (rule->nr != pr->nr))
2468 			rule = TAILQ_NEXT(rule, entries);
2469 		if (rule == NULL) {
2470 			PF_RULES_WUNLOCK();
2471 			error = EBUSY;
2472 			break;
2473 		}
2474 
2475 		pf_krule_to_rule(rule, &pr->rule);
2476 
2477 		if (pf_kanchor_copyout(ruleset, rule, pr)) {
2478 			PF_RULES_WUNLOCK();
2479 			error = EBUSY;
2480 			break;
2481 		}
2482 		pf_addr_copyout(&pr->rule.src.addr);
2483 		pf_addr_copyout(&pr->rule.dst.addr);
2484 
2485 		if (pr->action == PF_GET_CLR_CNTR) {
2486 			pf_counter_u64_zero(&rule->evaluations);
2487 			for (int i = 0; i < 2; i++) {
2488 				pf_counter_u64_zero(&rule->packets[i]);
2489 				pf_counter_u64_zero(&rule->bytes[i]);
2490 			}
2491 			counter_u64_zero(rule->states_tot);
2492 		}
2493 		PF_RULES_WUNLOCK();
2494 		break;
2495 	}
2496 
2497 	case DIOCGETRULENV: {
2498 		struct pfioc_nv		*nv = (struct pfioc_nv *)addr;
2499 		nvlist_t		*nvrule = NULL;
2500 		nvlist_t		*nvl = NULL;
2501 		struct pf_kruleset	*ruleset;
2502 		struct pf_krule		*rule;
2503 		void			*nvlpacked = NULL;
2504 		int			 rs_num, nr;
2505 		bool			 clear_counter = false;
2506 
2507 #define	ERROUT(x)	ERROUT_IOCTL(DIOCGETRULENV_error, x)
2508 
2509 		if (nv->len > pf_ioctl_maxcount)
2510 			ERROUT(ENOMEM);
2511 
2512 		/* Copy the request in */
2513 		nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
2514 		if (nvlpacked == NULL)
2515 			ERROUT(ENOMEM);
2516 
2517 		error = copyin(nv->data, nvlpacked, nv->len);
2518 		if (error)
2519 			ERROUT(error);
2520 
2521 		nvl = nvlist_unpack(nvlpacked, nv->len, 0);
2522 		if (nvl == NULL)
2523 			ERROUT(EBADMSG);
2524 
2525 		if (! nvlist_exists_string(nvl, "anchor"))
2526 			ERROUT(EBADMSG);
2527 		if (! nvlist_exists_number(nvl, "ruleset"))
2528 			ERROUT(EBADMSG);
2529 		if (! nvlist_exists_number(nvl, "ticket"))
2530 			ERROUT(EBADMSG);
2531 		if (! nvlist_exists_number(nvl, "nr"))
2532 			ERROUT(EBADMSG);
2533 
2534 		if (nvlist_exists_bool(nvl, "clear_counter"))
2535 			clear_counter = nvlist_get_bool(nvl, "clear_counter");
2536 
2537 		if (clear_counter && !(flags & FWRITE))
2538 			ERROUT(EACCES);
2539 
2540 		nr = nvlist_get_number(nvl, "nr");
2541 
2542 		PF_RULES_WLOCK();
2543 		ruleset = pf_find_kruleset(nvlist_get_string(nvl, "anchor"));
2544 		if (ruleset == NULL) {
2545 			PF_RULES_WUNLOCK();
2546 			ERROUT(ENOENT);
2547 		}
2548 
2549 		rs_num = pf_get_ruleset_number(nvlist_get_number(nvl, "ruleset"));
2550 		if (rs_num >= PF_RULESET_MAX) {
2551 			PF_RULES_WUNLOCK();
2552 			ERROUT(EINVAL);
2553 		}
2554 
2555 		if (nvlist_get_number(nvl, "ticket") !=
2556 		    ruleset->rules[rs_num].active.ticket) {
2557 			PF_RULES_WUNLOCK();
2558 			ERROUT(EBUSY);
2559 		}
2560 
2561 		if ((error = nvlist_error(nvl))) {
2562 			PF_RULES_WUNLOCK();
2563 			ERROUT(error);
2564 		}
2565 
2566 		rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
2567 		while ((rule != NULL) && (rule->nr != nr))
2568 			rule = TAILQ_NEXT(rule, entries);
2569 		if (rule == NULL) {
2570 			PF_RULES_WUNLOCK();
2571 			ERROUT(EBUSY);
2572 		}
2573 
2574 		nvrule = pf_krule_to_nvrule(rule);
2575 
2576 		nvlist_destroy(nvl);
2577 		nvl = nvlist_create(0);
2578 		if (nvl == NULL) {
2579 			PF_RULES_WUNLOCK();
2580 			ERROUT(ENOMEM);
2581 		}
2582 		nvlist_add_number(nvl, "nr", nr);
2583 		nvlist_add_nvlist(nvl, "rule", nvrule);
2584 		nvlist_destroy(nvrule);
2585 		nvrule = NULL;
2586 		if (pf_kanchor_nvcopyout(ruleset, rule, nvl)) {
2587 			PF_RULES_WUNLOCK();
2588 			ERROUT(EBUSY);
2589 		}
2590 
2591 		free(nvlpacked, M_NVLIST);
2592 		nvlpacked = nvlist_pack(nvl, &nv->len);
2593 		if (nvlpacked == NULL) {
2594 			PF_RULES_WUNLOCK();
2595 			ERROUT(ENOMEM);
2596 		}
2597 
2598 		if (nv->size == 0) {
2599 			PF_RULES_WUNLOCK();
2600 			ERROUT(0);
2601 		}
2602 		else if (nv->size < nv->len) {
2603 			PF_RULES_WUNLOCK();
2604 			ERROUT(ENOSPC);
2605 		}
2606 
2607 		if (clear_counter) {
2608 			pf_counter_u64_zero(&rule->evaluations);
2609 			for (int i = 0; i < 2; i++) {
2610 				pf_counter_u64_zero(&rule->packets[i]);
2611 				pf_counter_u64_zero(&rule->bytes[i]);
2612 			}
2613 			counter_u64_zero(rule->states_tot);
2614 		}
2615 		PF_RULES_WUNLOCK();
2616 
2617 		error = copyout(nvlpacked, nv->data, nv->len);
2618 
2619 #undef ERROUT
2620 DIOCGETRULENV_error:
2621 		free(nvlpacked, M_NVLIST);
2622 		nvlist_destroy(nvrule);
2623 		nvlist_destroy(nvl);
2624 
2625 		break;
2626 	}
2627 
2628 	case DIOCCHANGERULE: {
2629 		struct pfioc_rule	*pcr = (struct pfioc_rule *)addr;
2630 		struct pf_kruleset	*ruleset;
2631 		struct pf_krule		*oldrule = NULL, *newrule = NULL;
2632 		struct pfi_kkif		*kif = NULL;
2633 		struct pf_kpooladdr	*pa;
2634 		u_int32_t		 nr = 0;
2635 		int			 rs_num;
2636 
2637 		pcr->anchor[sizeof(pcr->anchor) - 1] = 0;
2638 
2639 		if (pcr->action < PF_CHANGE_ADD_HEAD ||
2640 		    pcr->action > PF_CHANGE_GET_TICKET) {
2641 			error = EINVAL;
2642 			break;
2643 		}
2644 		if (pcr->rule.return_icmp >> 8 > ICMP_MAXTYPE) {
2645 			error = EINVAL;
2646 			break;
2647 		}
2648 
2649 		if (pcr->action != PF_CHANGE_REMOVE) {
2650 			newrule = pf_krule_alloc();
2651 			error = pf_rule_to_krule(&pcr->rule, newrule);
2652 			if (error != 0) {
2653 				free(newrule, M_PFRULE);
2654 				break;
2655 			}
2656 
2657 			if (newrule->ifname[0])
2658 				kif = pf_kkif_create(M_WAITOK);
2659 			pf_counter_u64_init(&newrule->evaluations, M_WAITOK);
2660 			for (int i = 0; i < 2; i++) {
2661 				pf_counter_u64_init(&newrule->packets[i], M_WAITOK);
2662 				pf_counter_u64_init(&newrule->bytes[i], M_WAITOK);
2663 			}
2664 			newrule->states_cur = counter_u64_alloc(M_WAITOK);
2665 			newrule->states_tot = counter_u64_alloc(M_WAITOK);
2666 			newrule->src_nodes = counter_u64_alloc(M_WAITOK);
2667 			newrule->cuid = td->td_ucred->cr_ruid;
2668 			newrule->cpid = td->td_proc ? td->td_proc->p_pid : 0;
2669 			TAILQ_INIT(&newrule->rpool.list);
2670 		}
2671 #define	ERROUT(x)	{ error = (x); goto DIOCCHANGERULE_error; }
2672 
2673 		PF_RULES_WLOCK();
2674 #ifdef PF_WANT_32_TO_64_COUNTER
2675 		if (newrule != NULL) {
2676 			LIST_INSERT_HEAD(&V_pf_allrulelist, newrule, allrulelist);
2677 			newrule->allrulelinked = true;
2678 			V_pf_allrulecount++;
2679 		}
2680 #endif
2681 
2682 		if (!(pcr->action == PF_CHANGE_REMOVE ||
2683 		    pcr->action == PF_CHANGE_GET_TICKET) &&
2684 		    pcr->pool_ticket != V_ticket_pabuf)
2685 			ERROUT(EBUSY);
2686 
2687 		ruleset = pf_find_kruleset(pcr->anchor);
2688 		if (ruleset == NULL)
2689 			ERROUT(EINVAL);
2690 
2691 		rs_num = pf_get_ruleset_number(pcr->rule.action);
2692 		if (rs_num >= PF_RULESET_MAX)
2693 			ERROUT(EINVAL);
2694 
2695 		if (pcr->action == PF_CHANGE_GET_TICKET) {
2696 			pcr->ticket = ++ruleset->rules[rs_num].active.ticket;
2697 			ERROUT(0);
2698 		} else if (pcr->ticket !=
2699 			    ruleset->rules[rs_num].active.ticket)
2700 				ERROUT(EINVAL);
2701 
2702 		if (pcr->action != PF_CHANGE_REMOVE) {
2703 			if (newrule->ifname[0]) {
2704 				newrule->kif = pfi_kkif_attach(kif,
2705 				    newrule->ifname);
2706 				kif = NULL;
2707 				pfi_kkif_ref(newrule->kif);
2708 			} else
2709 				newrule->kif = NULL;
2710 
2711 			if (newrule->rtableid > 0 &&
2712 			    newrule->rtableid >= rt_numfibs)
2713 				error = EBUSY;
2714 
2715 #ifdef ALTQ
2716 			/* set queue IDs */
2717 			if (newrule->qname[0] != 0) {
2718 				if ((newrule->qid =
2719 				    pf_qname2qid(newrule->qname)) == 0)
2720 					error = EBUSY;
2721 				else if (newrule->pqname[0] != 0) {
2722 					if ((newrule->pqid =
2723 					    pf_qname2qid(newrule->pqname)) == 0)
2724 						error = EBUSY;
2725 				} else
2726 					newrule->pqid = newrule->qid;
2727 			}
2728 #endif /* ALTQ */
2729 			if (newrule->tagname[0])
2730 				if ((newrule->tag =
2731 				    pf_tagname2tag(newrule->tagname)) == 0)
2732 					error = EBUSY;
2733 			if (newrule->match_tagname[0])
2734 				if ((newrule->match_tag = pf_tagname2tag(
2735 				    newrule->match_tagname)) == 0)
2736 					error = EBUSY;
2737 			if (newrule->rt && !newrule->direction)
2738 				error = EINVAL;
2739 			if (!newrule->log)
2740 				newrule->logif = 0;
2741 			if (newrule->logif >= PFLOGIFS_MAX)
2742 				error = EINVAL;
2743 			if (pf_addr_setup(ruleset, &newrule->src.addr, newrule->af))
2744 				error = ENOMEM;
2745 			if (pf_addr_setup(ruleset, &newrule->dst.addr, newrule->af))
2746 				error = ENOMEM;
2747 			if (pf_kanchor_setup(newrule, ruleset, pcr->anchor_call))
2748 				error = EINVAL;
2749 			TAILQ_FOREACH(pa, &V_pf_pabuf, entries)
2750 				if (pa->addr.type == PF_ADDR_TABLE) {
2751 					pa->addr.p.tbl =
2752 					    pfr_attach_table(ruleset,
2753 					    pa->addr.v.tblname);
2754 					if (pa->addr.p.tbl == NULL)
2755 						error = ENOMEM;
2756 				}
2757 
2758 			newrule->overload_tbl = NULL;
2759 			if (newrule->overload_tblname[0]) {
2760 				if ((newrule->overload_tbl = pfr_attach_table(
2761 				    ruleset, newrule->overload_tblname)) ==
2762 				    NULL)
2763 					error = EINVAL;
2764 				else
2765 					newrule->overload_tbl->pfrkt_flags |=
2766 					    PFR_TFLAG_ACTIVE;
2767 			}
2768 
2769 			pf_mv_kpool(&V_pf_pabuf, &newrule->rpool.list);
2770 			if (((((newrule->action == PF_NAT) ||
2771 			    (newrule->action == PF_RDR) ||
2772 			    (newrule->action == PF_BINAT) ||
2773 			    (newrule->rt > PF_NOPFROUTE)) &&
2774 			    !newrule->anchor)) &&
2775 			    (TAILQ_FIRST(&newrule->rpool.list) == NULL))
2776 				error = EINVAL;
2777 
2778 			if (error) {
2779 				pf_free_rule(newrule);
2780 				PF_RULES_WUNLOCK();
2781 				break;
2782 			}
2783 
2784 			newrule->rpool.cur = TAILQ_FIRST(&newrule->rpool.list);
2785 		}
2786 		pf_empty_kpool(&V_pf_pabuf);
2787 
2788 		if (pcr->action == PF_CHANGE_ADD_HEAD)
2789 			oldrule = TAILQ_FIRST(
2790 			    ruleset->rules[rs_num].active.ptr);
2791 		else if (pcr->action == PF_CHANGE_ADD_TAIL)
2792 			oldrule = TAILQ_LAST(
2793 			    ruleset->rules[rs_num].active.ptr, pf_krulequeue);
2794 		else {
2795 			oldrule = TAILQ_FIRST(
2796 			    ruleset->rules[rs_num].active.ptr);
2797 			while ((oldrule != NULL) && (oldrule->nr != pcr->nr))
2798 				oldrule = TAILQ_NEXT(oldrule, entries);
2799 			if (oldrule == NULL) {
2800 				if (newrule != NULL)
2801 					pf_free_rule(newrule);
2802 				PF_RULES_WUNLOCK();
2803 				error = EINVAL;
2804 				break;
2805 			}
2806 		}
2807 
2808 		if (pcr->action == PF_CHANGE_REMOVE) {
2809 			pf_unlink_rule(ruleset->rules[rs_num].active.ptr,
2810 			    oldrule);
2811 			ruleset->rules[rs_num].active.rcount--;
2812 		} else {
2813 			if (oldrule == NULL)
2814 				TAILQ_INSERT_TAIL(
2815 				    ruleset->rules[rs_num].active.ptr,
2816 				    newrule, entries);
2817 			else if (pcr->action == PF_CHANGE_ADD_HEAD ||
2818 			    pcr->action == PF_CHANGE_ADD_BEFORE)
2819 				TAILQ_INSERT_BEFORE(oldrule, newrule, entries);
2820 			else
2821 				TAILQ_INSERT_AFTER(
2822 				    ruleset->rules[rs_num].active.ptr,
2823 				    oldrule, newrule, entries);
2824 			ruleset->rules[rs_num].active.rcount++;
2825 		}
2826 
2827 		nr = 0;
2828 		TAILQ_FOREACH(oldrule,
2829 		    ruleset->rules[rs_num].active.ptr, entries)
2830 			oldrule->nr = nr++;
2831 
2832 		ruleset->rules[rs_num].active.ticket++;
2833 
2834 		pf_calc_skip_steps(ruleset->rules[rs_num].active.ptr);
2835 		pf_remove_if_empty_kruleset(ruleset);
2836 
2837 		PF_RULES_WUNLOCK();
2838 		break;
2839 
2840 #undef ERROUT
2841 DIOCCHANGERULE_error:
2842 		PF_RULES_WUNLOCK();
2843 		pf_krule_free(newrule);
2844 		pf_kkif_free(kif);
2845 		break;
2846 	}
2847 
2848 	case DIOCCLRSTATES: {
2849 		struct pfioc_state_kill *psk = (struct pfioc_state_kill *)addr;
2850 		struct pf_kstate_kill	 kill;
2851 
2852 		error = pf_state_kill_to_kstate_kill(psk, &kill);
2853 		if (error)
2854 			break;
2855 
2856 		psk->psk_killed = pf_clear_states(&kill);
2857 		break;
2858 	}
2859 
2860 	case DIOCCLRSTATESNV: {
2861 		error = pf_clearstates_nv((struct pfioc_nv *)addr);
2862 		break;
2863 	}
2864 
2865 	case DIOCKILLSTATES: {
2866 		struct pfioc_state_kill	*psk = (struct pfioc_state_kill *)addr;
2867 		struct pf_kstate_kill	 kill;
2868 
2869 		error = pf_state_kill_to_kstate_kill(psk, &kill);
2870 		if (error)
2871 			break;
2872 
2873 		psk->psk_killed = 0;
2874 		pf_killstates(&kill, &psk->psk_killed);
2875 		break;
2876 	}
2877 
2878 	case DIOCKILLSTATESNV: {
2879 		error = pf_killstates_nv((struct pfioc_nv *)addr);
2880 		break;
2881 	}
2882 
2883 	case DIOCADDSTATE: {
2884 		struct pfioc_state	*ps = (struct pfioc_state *)addr;
2885 		struct pfsync_state	*sp = &ps->state;
2886 
2887 		if (sp->timeout >= PFTM_MAX) {
2888 			error = EINVAL;
2889 			break;
2890 		}
2891 		if (V_pfsync_state_import_ptr != NULL) {
2892 			PF_RULES_RLOCK();
2893 			error = V_pfsync_state_import_ptr(sp, PFSYNC_SI_IOCTL);
2894 			PF_RULES_RUNLOCK();
2895 		} else
2896 			error = EOPNOTSUPP;
2897 		break;
2898 	}
2899 
2900 	case DIOCGETSTATE: {
2901 		struct pfioc_state	*ps = (struct pfioc_state *)addr;
2902 		struct pf_kstate	*s;
2903 
2904 		s = pf_find_state_byid(ps->state.id, ps->state.creatorid);
2905 		if (s == NULL) {
2906 			error = ENOENT;
2907 			break;
2908 		}
2909 
2910 		pfsync_state_export(&ps->state, s);
2911 		PF_STATE_UNLOCK(s);
2912 		break;
2913 	}
2914 
2915 	case DIOCGETSTATENV: {
2916 		error = pf_getstate((struct pfioc_nv *)addr);
2917 		break;
2918 	}
2919 
2920 	case DIOCGETSTATES: {
2921 		struct pfioc_states	*ps = (struct pfioc_states *)addr;
2922 		struct pf_kstate	*s;
2923 		struct pfsync_state	*pstore, *p;
2924 		int			 i, nr;
2925 		size_t			 slice_count = 16, count;
2926 		void			*out;
2927 
2928 		if (ps->ps_len <= 0) {
2929 			nr = uma_zone_get_cur(V_pf_state_z);
2930 			ps->ps_len = sizeof(struct pfsync_state) * nr;
2931 			break;
2932 		}
2933 
2934 		out = ps->ps_states;
2935 		pstore = mallocarray(slice_count,
2936 		    sizeof(struct pfsync_state), M_TEMP, M_WAITOK | M_ZERO);
2937 		nr = 0;
2938 
2939 		for (i = 0; i <= pf_hashmask; i++) {
2940 			struct pf_idhash *ih = &V_pf_idhash[i];
2941 
2942 DIOCGETSTATES_retry:
2943 			p = pstore;
2944 
2945 			if (LIST_EMPTY(&ih->states))
2946 				continue;
2947 
2948 			PF_HASHROW_LOCK(ih);
2949 			count = 0;
2950 			LIST_FOREACH(s, &ih->states, entry) {
2951 				if (s->timeout == PFTM_UNLINKED)
2952 					continue;
2953 				count++;
2954 			}
2955 
2956 			if (count > slice_count) {
2957 				PF_HASHROW_UNLOCK(ih);
2958 				free(pstore, M_TEMP);
2959 				slice_count = count * 2;
2960 				pstore = mallocarray(slice_count,
2961 				    sizeof(struct pfsync_state), M_TEMP,
2962 				    M_WAITOK | M_ZERO);
2963 				goto DIOCGETSTATES_retry;
2964 			}
2965 
2966 			if ((nr+count) * sizeof(*p) > ps->ps_len) {
2967 				PF_HASHROW_UNLOCK(ih);
2968 				goto DIOCGETSTATES_full;
2969 			}
2970 
2971 			LIST_FOREACH(s, &ih->states, entry) {
2972 				if (s->timeout == PFTM_UNLINKED)
2973 					continue;
2974 
2975 				pfsync_state_export(p, s);
2976 				p++;
2977 				nr++;
2978 			}
2979 			PF_HASHROW_UNLOCK(ih);
2980 			error = copyout(pstore, out,
2981 			    sizeof(struct pfsync_state) * count);
2982 			if (error)
2983 				break;
2984 			out = ps->ps_states + nr;
2985 		}
2986 DIOCGETSTATES_full:
2987 		ps->ps_len = sizeof(struct pfsync_state) * nr;
2988 		free(pstore, M_TEMP);
2989 
2990 		break;
2991 	}
2992 
2993 	case DIOCGETSTATESV2: {
2994 		struct pfioc_states_v2	*ps = (struct pfioc_states_v2 *)addr;
2995 		struct pf_kstate	*s;
2996 		struct pf_state_export	*pstore, *p;
2997 		int i, nr;
2998 		size_t slice_count = 16, count;
2999 		void *out;
3000 
3001 		if (ps->ps_req_version > PF_STATE_VERSION) {
3002 			error = ENOTSUP;
3003 			break;
3004 		}
3005 
3006 		if (ps->ps_len <= 0) {
3007 			nr = uma_zone_get_cur(V_pf_state_z);
3008 			ps->ps_len = sizeof(struct pf_state_export) * nr;
3009 			break;
3010 		}
3011 
3012 		out = ps->ps_states;
3013 		pstore = mallocarray(slice_count,
3014 		    sizeof(struct pf_state_export), M_TEMP, M_WAITOK | M_ZERO);
3015 		nr = 0;
3016 
3017 		for (i = 0; i <= pf_hashmask; i++) {
3018 			struct pf_idhash *ih = &V_pf_idhash[i];
3019 
3020 DIOCGETSTATESV2_retry:
3021 			p = pstore;
3022 
3023 			if (LIST_EMPTY(&ih->states))
3024 				continue;
3025 
3026 			PF_HASHROW_LOCK(ih);
3027 			count = 0;
3028 			LIST_FOREACH(s, &ih->states, entry) {
3029 				if (s->timeout == PFTM_UNLINKED)
3030 					continue;
3031 				count++;
3032 			}
3033 
3034 			if (count > slice_count) {
3035 				PF_HASHROW_UNLOCK(ih);
3036 				free(pstore, M_TEMP);
3037 				slice_count = count * 2;
3038 				pstore = mallocarray(slice_count,
3039 				    sizeof(struct pf_state_export), M_TEMP,
3040 				    M_WAITOK | M_ZERO);
3041 				goto DIOCGETSTATESV2_retry;
3042 			}
3043 
3044 			if ((nr+count) * sizeof(*p) > ps->ps_len) {
3045 				PF_HASHROW_UNLOCK(ih);
3046 				goto DIOCGETSTATESV2_full;
3047 			}
3048 
3049 			LIST_FOREACH(s, &ih->states, entry) {
3050 				if (s->timeout == PFTM_UNLINKED)
3051 					continue;
3052 
3053 				pf_state_export(p, s);
3054 				p++;
3055 				nr++;
3056 			}
3057 			PF_HASHROW_UNLOCK(ih);
3058 			error = copyout(pstore, out,
3059 			    sizeof(struct pf_state_export) * count);
3060 			if (error)
3061 				break;
3062 			out = ps->ps_states + nr;
3063 		}
3064 DIOCGETSTATESV2_full:
3065 		ps->ps_len = nr * sizeof(struct pf_state_export);
3066 		free(pstore, M_TEMP);
3067 
3068 		break;
3069 	}
3070 
3071 	case DIOCGETSTATUS: {
3072 		struct pf_status *s = (struct pf_status *)addr;
3073 
3074 		PF_RULES_RLOCK();
3075 		s->running = V_pf_status.running;
3076 		s->since   = V_pf_status.since;
3077 		s->debug   = V_pf_status.debug;
3078 		s->hostid  = V_pf_status.hostid;
3079 		s->states  = V_pf_status.states;
3080 		s->src_nodes = V_pf_status.src_nodes;
3081 
3082 		for (int i = 0; i < PFRES_MAX; i++)
3083 			s->counters[i] =
3084 			    counter_u64_fetch(V_pf_status.counters[i]);
3085 		for (int i = 0; i < LCNT_MAX; i++)
3086 			s->lcounters[i] =
3087 			    counter_u64_fetch(V_pf_status.lcounters[i]);
3088 		for (int i = 0; i < FCNT_MAX; i++)
3089 			s->fcounters[i] =
3090 			    pf_counter_u64_fetch(&V_pf_status.fcounters[i]);
3091 		for (int i = 0; i < SCNT_MAX; i++)
3092 			s->scounters[i] =
3093 			    counter_u64_fetch(V_pf_status.scounters[i]);
3094 
3095 		bcopy(V_pf_status.ifname, s->ifname, IFNAMSIZ);
3096 		bcopy(V_pf_status.pf_chksum, s->pf_chksum,
3097 		    PF_MD5_DIGEST_LENGTH);
3098 
3099 		pfi_update_status(s->ifname, s);
3100 		PF_RULES_RUNLOCK();
3101 		break;
3102 	}
3103 
3104 	case DIOCGETSTATUSNV: {
3105 		error = pf_getstatus((struct pfioc_nv *)addr);
3106 		break;
3107 	}
3108 
3109 	case DIOCSETSTATUSIF: {
3110 		struct pfioc_if	*pi = (struct pfioc_if *)addr;
3111 
3112 		if (pi->ifname[0] == 0) {
3113 			bzero(V_pf_status.ifname, IFNAMSIZ);
3114 			break;
3115 		}
3116 		PF_RULES_WLOCK();
3117 		error = pf_user_strcpy(V_pf_status.ifname, pi->ifname, IFNAMSIZ);
3118 		PF_RULES_WUNLOCK();
3119 		break;
3120 	}
3121 
3122 	case DIOCCLRSTATUS: {
3123 		PF_RULES_WLOCK();
3124 		for (int i = 0; i < PFRES_MAX; i++)
3125 			counter_u64_zero(V_pf_status.counters[i]);
3126 		for (int i = 0; i < FCNT_MAX; i++)
3127 			pf_counter_u64_zero(&V_pf_status.fcounters[i]);
3128 		for (int i = 0; i < SCNT_MAX; i++)
3129 			counter_u64_zero(V_pf_status.scounters[i]);
3130 		for (int i = 0; i < KLCNT_MAX; i++)
3131 			counter_u64_zero(V_pf_status.lcounters[i]);
3132 		V_pf_status.since = time_second;
3133 		if (*V_pf_status.ifname)
3134 			pfi_update_status(V_pf_status.ifname, NULL);
3135 		PF_RULES_WUNLOCK();
3136 		break;
3137 	}
3138 
3139 	case DIOCNATLOOK: {
3140 		struct pfioc_natlook	*pnl = (struct pfioc_natlook *)addr;
3141 		struct pf_state_key	*sk;
3142 		struct pf_kstate	*state;
3143 		struct pf_state_key_cmp	 key;
3144 		int			 m = 0, direction = pnl->direction;
3145 		int			 sidx, didx;
3146 
3147 		/* NATLOOK src and dst are reversed, so reverse sidx/didx */
3148 		sidx = (direction == PF_IN) ? 1 : 0;
3149 		didx = (direction == PF_IN) ? 0 : 1;
3150 
3151 		if (!pnl->proto ||
3152 		    PF_AZERO(&pnl->saddr, pnl->af) ||
3153 		    PF_AZERO(&pnl->daddr, pnl->af) ||
3154 		    ((pnl->proto == IPPROTO_TCP ||
3155 		    pnl->proto == IPPROTO_UDP) &&
3156 		    (!pnl->dport || !pnl->sport)))
3157 			error = EINVAL;
3158 		else {
3159 			bzero(&key, sizeof(key));
3160 			key.af = pnl->af;
3161 			key.proto = pnl->proto;
3162 			PF_ACPY(&key.addr[sidx], &pnl->saddr, pnl->af);
3163 			key.port[sidx] = pnl->sport;
3164 			PF_ACPY(&key.addr[didx], &pnl->daddr, pnl->af);
3165 			key.port[didx] = pnl->dport;
3166 
3167 			state = pf_find_state_all(&key, direction, &m);
3168 			if (state == NULL) {
3169 				error = ENOENT;
3170 			} else {
3171 				if (m > 1) {
3172 					PF_STATE_UNLOCK(state);
3173 					error = E2BIG;	/* more than one state */
3174 				} else {
3175 					sk = state->key[sidx];
3176 					PF_ACPY(&pnl->rsaddr, &sk->addr[sidx], sk->af);
3177 					pnl->rsport = sk->port[sidx];
3178 					PF_ACPY(&pnl->rdaddr, &sk->addr[didx], sk->af);
3179 					pnl->rdport = sk->port[didx];
3180 					PF_STATE_UNLOCK(state);
3181 				}
3182 			}
3183 		}
3184 		break;
3185 	}
3186 
3187 	case DIOCSETTIMEOUT: {
3188 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
3189 		int		 old;
3190 
3191 		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX ||
3192 		    pt->seconds < 0) {
3193 			error = EINVAL;
3194 			break;
3195 		}
3196 		PF_RULES_WLOCK();
3197 		old = V_pf_default_rule.timeout[pt->timeout];
3198 		if (pt->timeout == PFTM_INTERVAL && pt->seconds == 0)
3199 			pt->seconds = 1;
3200 		V_pf_default_rule.timeout[pt->timeout] = pt->seconds;
3201 		if (pt->timeout == PFTM_INTERVAL && pt->seconds < old)
3202 			wakeup(pf_purge_thread);
3203 		pt->seconds = old;
3204 		PF_RULES_WUNLOCK();
3205 		break;
3206 	}
3207 
3208 	case DIOCGETTIMEOUT: {
3209 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
3210 
3211 		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX) {
3212 			error = EINVAL;
3213 			break;
3214 		}
3215 		PF_RULES_RLOCK();
3216 		pt->seconds = V_pf_default_rule.timeout[pt->timeout];
3217 		PF_RULES_RUNLOCK();
3218 		break;
3219 	}
3220 
3221 	case DIOCGETLIMIT: {
3222 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
3223 
3224 		if (pl->index < 0 || pl->index >= PF_LIMIT_MAX) {
3225 			error = EINVAL;
3226 			break;
3227 		}
3228 		PF_RULES_RLOCK();
3229 		pl->limit = V_pf_limits[pl->index].limit;
3230 		PF_RULES_RUNLOCK();
3231 		break;
3232 	}
3233 
3234 	case DIOCSETLIMIT: {
3235 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
3236 		int			 old_limit;
3237 
3238 		PF_RULES_WLOCK();
3239 		if (pl->index < 0 || pl->index >= PF_LIMIT_MAX ||
3240 		    V_pf_limits[pl->index].zone == NULL) {
3241 			PF_RULES_WUNLOCK();
3242 			error = EINVAL;
3243 			break;
3244 		}
3245 		uma_zone_set_max(V_pf_limits[pl->index].zone, pl->limit);
3246 		old_limit = V_pf_limits[pl->index].limit;
3247 		V_pf_limits[pl->index].limit = pl->limit;
3248 		pl->limit = old_limit;
3249 		PF_RULES_WUNLOCK();
3250 		break;
3251 	}
3252 
3253 	case DIOCSETDEBUG: {
3254 		u_int32_t	*level = (u_int32_t *)addr;
3255 
3256 		PF_RULES_WLOCK();
3257 		V_pf_status.debug = *level;
3258 		PF_RULES_WUNLOCK();
3259 		break;
3260 	}
3261 
3262 	case DIOCCLRRULECTRS: {
3263 		/* obsoleted by DIOCGETRULE with action=PF_GET_CLR_CNTR */
3264 		struct pf_kruleset	*ruleset = &pf_main_ruleset;
3265 		struct pf_krule		*rule;
3266 
3267 		PF_RULES_WLOCK();
3268 		TAILQ_FOREACH(rule,
3269 		    ruleset->rules[PF_RULESET_FILTER].active.ptr, entries) {
3270 			pf_counter_u64_zero(&rule->evaluations);
3271 			for (int i = 0; i < 2; i++) {
3272 				pf_counter_u64_zero(&rule->packets[i]);
3273 				pf_counter_u64_zero(&rule->bytes[i]);
3274 			}
3275 		}
3276 		PF_RULES_WUNLOCK();
3277 		break;
3278 	}
3279 
3280 	case DIOCGIFSPEEDV0:
3281 	case DIOCGIFSPEEDV1: {
3282 		struct pf_ifspeed_v1	*psp = (struct pf_ifspeed_v1 *)addr;
3283 		struct pf_ifspeed_v1	ps;
3284 		struct ifnet		*ifp;
3285 
3286 		if (psp->ifname[0] == '\0') {
3287 			error = EINVAL;
3288 			break;
3289 		}
3290 
3291 		error = pf_user_strcpy(ps.ifname, psp->ifname, IFNAMSIZ);
3292 		if (error != 0)
3293 			break;
3294 		ifp = ifunit(ps.ifname);
3295 		if (ifp != NULL) {
3296 			psp->baudrate32 =
3297 			    (u_int32_t)uqmin(ifp->if_baudrate, UINT_MAX);
3298 			if (cmd == DIOCGIFSPEEDV1)
3299 				psp->baudrate = ifp->if_baudrate;
3300 		} else {
3301 			error = EINVAL;
3302 		}
3303 		break;
3304 	}
3305 
3306 #ifdef ALTQ
3307 	case DIOCSTARTALTQ: {
3308 		struct pf_altq		*altq;
3309 
3310 		PF_RULES_WLOCK();
3311 		/* enable all altq interfaces on active list */
3312 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries) {
3313 			if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
3314 				error = pf_enable_altq(altq);
3315 				if (error != 0)
3316 					break;
3317 			}
3318 		}
3319 		if (error == 0)
3320 			V_pf_altq_running = 1;
3321 		PF_RULES_WUNLOCK();
3322 		DPFPRINTF(PF_DEBUG_MISC, ("altq: started\n"));
3323 		break;
3324 	}
3325 
3326 	case DIOCSTOPALTQ: {
3327 		struct pf_altq		*altq;
3328 
3329 		PF_RULES_WLOCK();
3330 		/* disable all altq interfaces on active list */
3331 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries) {
3332 			if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
3333 				error = pf_disable_altq(altq);
3334 				if (error != 0)
3335 					break;
3336 			}
3337 		}
3338 		if (error == 0)
3339 			V_pf_altq_running = 0;
3340 		PF_RULES_WUNLOCK();
3341 		DPFPRINTF(PF_DEBUG_MISC, ("altq: stopped\n"));
3342 		break;
3343 	}
3344 
3345 	case DIOCADDALTQV0:
3346 	case DIOCADDALTQV1: {
3347 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
3348 		struct pf_altq		*altq, *a;
3349 		struct ifnet		*ifp;
3350 
3351 		altq = malloc(sizeof(*altq), M_PFALTQ, M_WAITOK | M_ZERO);
3352 		error = pf_import_kaltq(pa, altq, IOCPARM_LEN(cmd));
3353 		if (error)
3354 			break;
3355 		altq->local_flags = 0;
3356 
3357 		PF_RULES_WLOCK();
3358 		if (pa->ticket != V_ticket_altqs_inactive) {
3359 			PF_RULES_WUNLOCK();
3360 			free(altq, M_PFALTQ);
3361 			error = EBUSY;
3362 			break;
3363 		}
3364 
3365 		/*
3366 		 * if this is for a queue, find the discipline and
3367 		 * copy the necessary fields
3368 		 */
3369 		if (altq->qname[0] != 0) {
3370 			if ((altq->qid = pf_qname2qid(altq->qname)) == 0) {
3371 				PF_RULES_WUNLOCK();
3372 				error = EBUSY;
3373 				free(altq, M_PFALTQ);
3374 				break;
3375 			}
3376 			altq->altq_disc = NULL;
3377 			TAILQ_FOREACH(a, V_pf_altq_ifs_inactive, entries) {
3378 				if (strncmp(a->ifname, altq->ifname,
3379 				    IFNAMSIZ) == 0) {
3380 					altq->altq_disc = a->altq_disc;
3381 					break;
3382 				}
3383 			}
3384 		}
3385 
3386 		if ((ifp = ifunit(altq->ifname)) == NULL)
3387 			altq->local_flags |= PFALTQ_FLAG_IF_REMOVED;
3388 		else
3389 			error = altq_add(ifp, altq);
3390 
3391 		if (error) {
3392 			PF_RULES_WUNLOCK();
3393 			free(altq, M_PFALTQ);
3394 			break;
3395 		}
3396 
3397 		if (altq->qname[0] != 0)
3398 			TAILQ_INSERT_TAIL(V_pf_altqs_inactive, altq, entries);
3399 		else
3400 			TAILQ_INSERT_TAIL(V_pf_altq_ifs_inactive, altq, entries);
3401 		/* version error check done on import above */
3402 		pf_export_kaltq(altq, pa, IOCPARM_LEN(cmd));
3403 		PF_RULES_WUNLOCK();
3404 		break;
3405 	}
3406 
3407 	case DIOCGETALTQSV0:
3408 	case DIOCGETALTQSV1: {
3409 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
3410 		struct pf_altq		*altq;
3411 
3412 		PF_RULES_RLOCK();
3413 		pa->nr = 0;
3414 		TAILQ_FOREACH(altq, V_pf_altq_ifs_active, entries)
3415 			pa->nr++;
3416 		TAILQ_FOREACH(altq, V_pf_altqs_active, entries)
3417 			pa->nr++;
3418 		pa->ticket = V_ticket_altqs_active;
3419 		PF_RULES_RUNLOCK();
3420 		break;
3421 	}
3422 
3423 	case DIOCGETALTQV0:
3424 	case DIOCGETALTQV1: {
3425 		struct pfioc_altq_v1	*pa = (struct pfioc_altq_v1 *)addr;
3426 		struct pf_altq		*altq;
3427 
3428 		PF_RULES_RLOCK();
3429 		if (pa->ticket != V_ticket_altqs_active) {
3430 			PF_RULES_RUNLOCK();
3431 			error = EBUSY;
3432 			break;
3433 		}
3434 		altq = pf_altq_get_nth_active(pa->nr);
3435 		if (altq == NULL) {
3436 			PF_RULES_RUNLOCK();
3437 			error = EBUSY;
3438 			break;
3439 		}
3440 		pf_export_kaltq(altq, pa, IOCPARM_LEN(cmd));
3441 		PF_RULES_RUNLOCK();
3442 		break;
3443 	}
3444 
3445 	case DIOCCHANGEALTQV0:
3446 	case DIOCCHANGEALTQV1:
3447 		/* CHANGEALTQ not supported yet! */
3448 		error = ENODEV;
3449 		break;
3450 
3451 	case DIOCGETQSTATSV0:
3452 	case DIOCGETQSTATSV1: {
3453 		struct pfioc_qstats_v1	*pq = (struct pfioc_qstats_v1 *)addr;
3454 		struct pf_altq		*altq;
3455 		int			 nbytes;
3456 		u_int32_t		 version;
3457 
3458 		PF_RULES_RLOCK();
3459 		if (pq->ticket != V_ticket_altqs_active) {
3460 			PF_RULES_RUNLOCK();
3461 			error = EBUSY;
3462 			break;
3463 		}
3464 		nbytes = pq->nbytes;
3465 		altq = pf_altq_get_nth_active(pq->nr);
3466 		if (altq == NULL) {
3467 			PF_RULES_RUNLOCK();
3468 			error = EBUSY;
3469 			break;
3470 		}
3471 
3472 		if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) != 0) {
3473 			PF_RULES_RUNLOCK();
3474 			error = ENXIO;
3475 			break;
3476 		}
3477 		PF_RULES_RUNLOCK();
3478 		if (cmd == DIOCGETQSTATSV0)
3479 			version = 0;  /* DIOCGETQSTATSV0 means stats struct v0 */
3480 		else
3481 			version = pq->version;
3482 		error = altq_getqstats(altq, pq->buf, &nbytes, version);
3483 		if (error == 0) {
3484 			pq->scheduler = altq->scheduler;
3485 			pq->nbytes = nbytes;
3486 		}
3487 		break;
3488 	}
3489 #endif /* ALTQ */
3490 
3491 	case DIOCBEGINADDRS: {
3492 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
3493 
3494 		PF_RULES_WLOCK();
3495 		pf_empty_kpool(&V_pf_pabuf);
3496 		pp->ticket = ++V_ticket_pabuf;
3497 		PF_RULES_WUNLOCK();
3498 		break;
3499 	}
3500 
3501 	case DIOCADDADDR: {
3502 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
3503 		struct pf_kpooladdr	*pa;
3504 		struct pfi_kkif		*kif = NULL;
3505 
3506 #ifndef INET
3507 		if (pp->af == AF_INET) {
3508 			error = EAFNOSUPPORT;
3509 			break;
3510 		}
3511 #endif /* INET */
3512 #ifndef INET6
3513 		if (pp->af == AF_INET6) {
3514 			error = EAFNOSUPPORT;
3515 			break;
3516 		}
3517 #endif /* INET6 */
3518 		if (pp->addr.addr.type != PF_ADDR_ADDRMASK &&
3519 		    pp->addr.addr.type != PF_ADDR_DYNIFTL &&
3520 		    pp->addr.addr.type != PF_ADDR_TABLE) {
3521 			error = EINVAL;
3522 			break;
3523 		}
3524 		if (pp->addr.addr.p.dyn != NULL) {
3525 			error = EINVAL;
3526 			break;
3527 		}
3528 		pa = malloc(sizeof(*pa), M_PFRULE, M_WAITOK);
3529 		error = pf_pooladdr_to_kpooladdr(&pp->addr, pa);
3530 		if (error != 0)
3531 			break;
3532 		if (pa->ifname[0])
3533 			kif = pf_kkif_create(M_WAITOK);
3534 		PF_RULES_WLOCK();
3535 		if (pp->ticket != V_ticket_pabuf) {
3536 			PF_RULES_WUNLOCK();
3537 			if (pa->ifname[0])
3538 				pf_kkif_free(kif);
3539 			free(pa, M_PFRULE);
3540 			error = EBUSY;
3541 			break;
3542 		}
3543 		if (pa->ifname[0]) {
3544 			pa->kif = pfi_kkif_attach(kif, pa->ifname);
3545 			kif = NULL;
3546 			pfi_kkif_ref(pa->kif);
3547 		} else
3548 			pa->kif = NULL;
3549 		if (pa->addr.type == PF_ADDR_DYNIFTL && ((error =
3550 		    pfi_dynaddr_setup(&pa->addr, pp->af)) != 0)) {
3551 			if (pa->ifname[0])
3552 				pfi_kkif_unref(pa->kif);
3553 			PF_RULES_WUNLOCK();
3554 			free(pa, M_PFRULE);
3555 			break;
3556 		}
3557 		TAILQ_INSERT_TAIL(&V_pf_pabuf, pa, entries);
3558 		PF_RULES_WUNLOCK();
3559 		break;
3560 	}
3561 
3562 	case DIOCGETADDRS: {
3563 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
3564 		struct pf_kpool		*pool;
3565 		struct pf_kpooladdr	*pa;
3566 
3567 		pp->anchor[sizeof(pp->anchor) - 1] = 0;
3568 		pp->nr = 0;
3569 
3570 		PF_RULES_RLOCK();
3571 		pool = pf_get_kpool(pp->anchor, pp->ticket, pp->r_action,
3572 		    pp->r_num, 0, 1, 0);
3573 		if (pool == NULL) {
3574 			PF_RULES_RUNLOCK();
3575 			error = EBUSY;
3576 			break;
3577 		}
3578 		TAILQ_FOREACH(pa, &pool->list, entries)
3579 			pp->nr++;
3580 		PF_RULES_RUNLOCK();
3581 		break;
3582 	}
3583 
3584 	case DIOCGETADDR: {
3585 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
3586 		struct pf_kpool		*pool;
3587 		struct pf_kpooladdr	*pa;
3588 		u_int32_t		 nr = 0;
3589 
3590 		pp->anchor[sizeof(pp->anchor) - 1] = 0;
3591 
3592 		PF_RULES_RLOCK();
3593 		pool = pf_get_kpool(pp->anchor, pp->ticket, pp->r_action,
3594 		    pp->r_num, 0, 1, 1);
3595 		if (pool == NULL) {
3596 			PF_RULES_RUNLOCK();
3597 			error = EBUSY;
3598 			break;
3599 		}
3600 		pa = TAILQ_FIRST(&pool->list);
3601 		while ((pa != NULL) && (nr < pp->nr)) {
3602 			pa = TAILQ_NEXT(pa, entries);
3603 			nr++;
3604 		}
3605 		if (pa == NULL) {
3606 			PF_RULES_RUNLOCK();
3607 			error = EBUSY;
3608 			break;
3609 		}
3610 		pf_kpooladdr_to_pooladdr(pa, &pp->addr);
3611 		pf_addr_copyout(&pp->addr.addr);
3612 		PF_RULES_RUNLOCK();
3613 		break;
3614 	}
3615 
3616 	case DIOCCHANGEADDR: {
3617 		struct pfioc_pooladdr	*pca = (struct pfioc_pooladdr *)addr;
3618 		struct pf_kpool		*pool;
3619 		struct pf_kpooladdr	*oldpa = NULL, *newpa = NULL;
3620 		struct pf_kruleset	*ruleset;
3621 		struct pfi_kkif		*kif = NULL;
3622 
3623 		pca->anchor[sizeof(pca->anchor) - 1] = 0;
3624 
3625 		if (pca->action < PF_CHANGE_ADD_HEAD ||
3626 		    pca->action > PF_CHANGE_REMOVE) {
3627 			error = EINVAL;
3628 			break;
3629 		}
3630 		if (pca->addr.addr.type != PF_ADDR_ADDRMASK &&
3631 		    pca->addr.addr.type != PF_ADDR_DYNIFTL &&
3632 		    pca->addr.addr.type != PF_ADDR_TABLE) {
3633 			error = EINVAL;
3634 			break;
3635 		}
3636 		if (pca->addr.addr.p.dyn != NULL) {
3637 			error = EINVAL;
3638 			break;
3639 		}
3640 
3641 		if (pca->action != PF_CHANGE_REMOVE) {
3642 #ifndef INET
3643 			if (pca->af == AF_INET) {
3644 				error = EAFNOSUPPORT;
3645 				break;
3646 			}
3647 #endif /* INET */
3648 #ifndef INET6
3649 			if (pca->af == AF_INET6) {
3650 				error = EAFNOSUPPORT;
3651 				break;
3652 			}
3653 #endif /* INET6 */
3654 			newpa = malloc(sizeof(*newpa), M_PFRULE, M_WAITOK);
3655 			bcopy(&pca->addr, newpa, sizeof(struct pf_pooladdr));
3656 			if (newpa->ifname[0])
3657 				kif = pf_kkif_create(M_WAITOK);
3658 			newpa->kif = NULL;
3659 		}
3660 #define	ERROUT(x)	ERROUT_IOCTL(DIOCCHANGEADDR_error, x)
3661 		PF_RULES_WLOCK();
3662 		ruleset = pf_find_kruleset(pca->anchor);
3663 		if (ruleset == NULL)
3664 			ERROUT(EBUSY);
3665 
3666 		pool = pf_get_kpool(pca->anchor, pca->ticket, pca->r_action,
3667 		    pca->r_num, pca->r_last, 1, 1);
3668 		if (pool == NULL)
3669 			ERROUT(EBUSY);
3670 
3671 		if (pca->action != PF_CHANGE_REMOVE) {
3672 			if (newpa->ifname[0]) {
3673 				newpa->kif = pfi_kkif_attach(kif, newpa->ifname);
3674 				pfi_kkif_ref(newpa->kif);
3675 				kif = NULL;
3676 			}
3677 
3678 			switch (newpa->addr.type) {
3679 			case PF_ADDR_DYNIFTL:
3680 				error = pfi_dynaddr_setup(&newpa->addr,
3681 				    pca->af);
3682 				break;
3683 			case PF_ADDR_TABLE:
3684 				newpa->addr.p.tbl = pfr_attach_table(ruleset,
3685 				    newpa->addr.v.tblname);
3686 				if (newpa->addr.p.tbl == NULL)
3687 					error = ENOMEM;
3688 				break;
3689 			}
3690 			if (error)
3691 				goto DIOCCHANGEADDR_error;
3692 		}
3693 
3694 		switch (pca->action) {
3695 		case PF_CHANGE_ADD_HEAD:
3696 			oldpa = TAILQ_FIRST(&pool->list);
3697 			break;
3698 		case PF_CHANGE_ADD_TAIL:
3699 			oldpa = TAILQ_LAST(&pool->list, pf_kpalist);
3700 			break;
3701 		default:
3702 			oldpa = TAILQ_FIRST(&pool->list);
3703 			for (int i = 0; oldpa && i < pca->nr; i++)
3704 				oldpa = TAILQ_NEXT(oldpa, entries);
3705 
3706 			if (oldpa == NULL)
3707 				ERROUT(EINVAL);
3708 		}
3709 
3710 		if (pca->action == PF_CHANGE_REMOVE) {
3711 			TAILQ_REMOVE(&pool->list, oldpa, entries);
3712 			switch (oldpa->addr.type) {
3713 			case PF_ADDR_DYNIFTL:
3714 				pfi_dynaddr_remove(oldpa->addr.p.dyn);
3715 				break;
3716 			case PF_ADDR_TABLE:
3717 				pfr_detach_table(oldpa->addr.p.tbl);
3718 				break;
3719 			}
3720 			if (oldpa->kif)
3721 				pfi_kkif_unref(oldpa->kif);
3722 			free(oldpa, M_PFRULE);
3723 		} else {
3724 			if (oldpa == NULL)
3725 				TAILQ_INSERT_TAIL(&pool->list, newpa, entries);
3726 			else if (pca->action == PF_CHANGE_ADD_HEAD ||
3727 			    pca->action == PF_CHANGE_ADD_BEFORE)
3728 				TAILQ_INSERT_BEFORE(oldpa, newpa, entries);
3729 			else
3730 				TAILQ_INSERT_AFTER(&pool->list, oldpa,
3731 				    newpa, entries);
3732 		}
3733 
3734 		pool->cur = TAILQ_FIRST(&pool->list);
3735 		PF_ACPY(&pool->counter, &pool->cur->addr.v.a.addr, pca->af);
3736 		PF_RULES_WUNLOCK();
3737 		break;
3738 
3739 #undef ERROUT
3740 DIOCCHANGEADDR_error:
3741 		if (newpa != NULL) {
3742 			if (newpa->kif)
3743 				pfi_kkif_unref(newpa->kif);
3744 			free(newpa, M_PFRULE);
3745 		}
3746 		PF_RULES_WUNLOCK();
3747 		pf_kkif_free(kif);
3748 		break;
3749 	}
3750 
3751 	case DIOCGETRULESETS: {
3752 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
3753 		struct pf_kruleset	*ruleset;
3754 		struct pf_kanchor	*anchor;
3755 
3756 		pr->path[sizeof(pr->path) - 1] = 0;
3757 
3758 		PF_RULES_RLOCK();
3759 		if ((ruleset = pf_find_kruleset(pr->path)) == NULL) {
3760 			PF_RULES_RUNLOCK();
3761 			error = ENOENT;
3762 			break;
3763 		}
3764 		pr->nr = 0;
3765 		if (ruleset->anchor == NULL) {
3766 			/* XXX kludge for pf_main_ruleset */
3767 			RB_FOREACH(anchor, pf_kanchor_global, &V_pf_anchors)
3768 				if (anchor->parent == NULL)
3769 					pr->nr++;
3770 		} else {
3771 			RB_FOREACH(anchor, pf_kanchor_node,
3772 			    &ruleset->anchor->children)
3773 				pr->nr++;
3774 		}
3775 		PF_RULES_RUNLOCK();
3776 		break;
3777 	}
3778 
3779 	case DIOCGETRULESET: {
3780 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
3781 		struct pf_kruleset	*ruleset;
3782 		struct pf_kanchor	*anchor;
3783 		u_int32_t		 nr = 0;
3784 
3785 		pr->path[sizeof(pr->path) - 1] = 0;
3786 
3787 		PF_RULES_RLOCK();
3788 		if ((ruleset = pf_find_kruleset(pr->path)) == NULL) {
3789 			PF_RULES_RUNLOCK();
3790 			error = ENOENT;
3791 			break;
3792 		}
3793 		pr->name[0] = 0;
3794 		if (ruleset->anchor == NULL) {
3795 			/* XXX kludge for pf_main_ruleset */
3796 			RB_FOREACH(anchor, pf_kanchor_global, &V_pf_anchors)
3797 				if (anchor->parent == NULL && nr++ == pr->nr) {
3798 					strlcpy(pr->name, anchor->name,
3799 					    sizeof(pr->name));
3800 					break;
3801 				}
3802 		} else {
3803 			RB_FOREACH(anchor, pf_kanchor_node,
3804 			    &ruleset->anchor->children)
3805 				if (nr++ == pr->nr) {
3806 					strlcpy(pr->name, anchor->name,
3807 					    sizeof(pr->name));
3808 					break;
3809 				}
3810 		}
3811 		if (!pr->name[0])
3812 			error = EBUSY;
3813 		PF_RULES_RUNLOCK();
3814 		break;
3815 	}
3816 
3817 	case DIOCRCLRTABLES: {
3818 		struct pfioc_table *io = (struct pfioc_table *)addr;
3819 
3820 		if (io->pfrio_esize != 0) {
3821 			error = ENODEV;
3822 			break;
3823 		}
3824 		PF_RULES_WLOCK();
3825 		error = pfr_clr_tables(&io->pfrio_table, &io->pfrio_ndel,
3826 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
3827 		PF_RULES_WUNLOCK();
3828 		break;
3829 	}
3830 
3831 	case DIOCRADDTABLES: {
3832 		struct pfioc_table *io = (struct pfioc_table *)addr;
3833 		struct pfr_table *pfrts;
3834 		size_t totlen;
3835 
3836 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3837 			error = ENODEV;
3838 			break;
3839 		}
3840 
3841 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
3842 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
3843 			error = ENOMEM;
3844 			break;
3845 		}
3846 
3847 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3848 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3849 		    M_TEMP, M_WAITOK);
3850 		error = copyin(io->pfrio_buffer, pfrts, totlen);
3851 		if (error) {
3852 			free(pfrts, M_TEMP);
3853 			break;
3854 		}
3855 		PF_RULES_WLOCK();
3856 		error = pfr_add_tables(pfrts, io->pfrio_size,
3857 		    &io->pfrio_nadd, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3858 		PF_RULES_WUNLOCK();
3859 		free(pfrts, M_TEMP);
3860 		break;
3861 	}
3862 
3863 	case DIOCRDELTABLES: {
3864 		struct pfioc_table *io = (struct pfioc_table *)addr;
3865 		struct pfr_table *pfrts;
3866 		size_t totlen;
3867 
3868 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3869 			error = ENODEV;
3870 			break;
3871 		}
3872 
3873 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
3874 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
3875 			error = ENOMEM;
3876 			break;
3877 		}
3878 
3879 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3880 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3881 		    M_TEMP, M_WAITOK);
3882 		error = copyin(io->pfrio_buffer, pfrts, totlen);
3883 		if (error) {
3884 			free(pfrts, M_TEMP);
3885 			break;
3886 		}
3887 		PF_RULES_WLOCK();
3888 		error = pfr_del_tables(pfrts, io->pfrio_size,
3889 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3890 		PF_RULES_WUNLOCK();
3891 		free(pfrts, M_TEMP);
3892 		break;
3893 	}
3894 
3895 	case DIOCRGETTABLES: {
3896 		struct pfioc_table *io = (struct pfioc_table *)addr;
3897 		struct pfr_table *pfrts;
3898 		size_t totlen;
3899 		int n;
3900 
3901 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3902 			error = ENODEV;
3903 			break;
3904 		}
3905 		PF_RULES_RLOCK();
3906 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
3907 		if (n < 0) {
3908 			PF_RULES_RUNLOCK();
3909 			error = EINVAL;
3910 			break;
3911 		}
3912 		io->pfrio_size = min(io->pfrio_size, n);
3913 
3914 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3915 
3916 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3917 		    M_TEMP, M_NOWAIT | M_ZERO);
3918 		if (pfrts == NULL) {
3919 			error = ENOMEM;
3920 			PF_RULES_RUNLOCK();
3921 			break;
3922 		}
3923 		error = pfr_get_tables(&io->pfrio_table, pfrts,
3924 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3925 		PF_RULES_RUNLOCK();
3926 		if (error == 0)
3927 			error = copyout(pfrts, io->pfrio_buffer, totlen);
3928 		free(pfrts, M_TEMP);
3929 		break;
3930 	}
3931 
3932 	case DIOCRGETTSTATS: {
3933 		struct pfioc_table *io = (struct pfioc_table *)addr;
3934 		struct pfr_tstats *pfrtstats;
3935 		size_t totlen;
3936 		int n;
3937 
3938 		if (io->pfrio_esize != sizeof(struct pfr_tstats)) {
3939 			error = ENODEV;
3940 			break;
3941 		}
3942 		PF_TABLE_STATS_LOCK();
3943 		PF_RULES_RLOCK();
3944 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
3945 		if (n < 0) {
3946 			PF_RULES_RUNLOCK();
3947 			PF_TABLE_STATS_UNLOCK();
3948 			error = EINVAL;
3949 			break;
3950 		}
3951 		io->pfrio_size = min(io->pfrio_size, n);
3952 
3953 		totlen = io->pfrio_size * sizeof(struct pfr_tstats);
3954 		pfrtstats = mallocarray(io->pfrio_size,
3955 		    sizeof(struct pfr_tstats), M_TEMP, M_NOWAIT | M_ZERO);
3956 		if (pfrtstats == NULL) {
3957 			error = ENOMEM;
3958 			PF_RULES_RUNLOCK();
3959 			PF_TABLE_STATS_UNLOCK();
3960 			break;
3961 		}
3962 		error = pfr_get_tstats(&io->pfrio_table, pfrtstats,
3963 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
3964 		PF_RULES_RUNLOCK();
3965 		PF_TABLE_STATS_UNLOCK();
3966 		if (error == 0)
3967 			error = copyout(pfrtstats, io->pfrio_buffer, totlen);
3968 		free(pfrtstats, M_TEMP);
3969 		break;
3970 	}
3971 
3972 	case DIOCRCLRTSTATS: {
3973 		struct pfioc_table *io = (struct pfioc_table *)addr;
3974 		struct pfr_table *pfrts;
3975 		size_t totlen;
3976 
3977 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
3978 			error = ENODEV;
3979 			break;
3980 		}
3981 
3982 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
3983 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
3984 			/* We used to count tables and use the minimum required
3985 			 * size, so we didn't fail on overly large requests.
3986 			 * Keep doing so. */
3987 			io->pfrio_size = pf_ioctl_maxcount;
3988 			break;
3989 		}
3990 
3991 		totlen = io->pfrio_size * sizeof(struct pfr_table);
3992 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
3993 		    M_TEMP, M_WAITOK);
3994 		error = copyin(io->pfrio_buffer, pfrts, totlen);
3995 		if (error) {
3996 			free(pfrts, M_TEMP);
3997 			break;
3998 		}
3999 
4000 		PF_TABLE_STATS_LOCK();
4001 		PF_RULES_RLOCK();
4002 		error = pfr_clr_tstats(pfrts, io->pfrio_size,
4003 		    &io->pfrio_nzero, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4004 		PF_RULES_RUNLOCK();
4005 		PF_TABLE_STATS_UNLOCK();
4006 		free(pfrts, M_TEMP);
4007 		break;
4008 	}
4009 
4010 	case DIOCRSETTFLAGS: {
4011 		struct pfioc_table *io = (struct pfioc_table *)addr;
4012 		struct pfr_table *pfrts;
4013 		size_t totlen;
4014 		int n;
4015 
4016 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
4017 			error = ENODEV;
4018 			break;
4019 		}
4020 
4021 		PF_RULES_RLOCK();
4022 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
4023 		if (n < 0) {
4024 			PF_RULES_RUNLOCK();
4025 			error = EINVAL;
4026 			break;
4027 		}
4028 
4029 		io->pfrio_size = min(io->pfrio_size, n);
4030 		PF_RULES_RUNLOCK();
4031 
4032 		totlen = io->pfrio_size * sizeof(struct pfr_table);
4033 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
4034 		    M_TEMP, M_WAITOK);
4035 		error = copyin(io->pfrio_buffer, pfrts, totlen);
4036 		if (error) {
4037 			free(pfrts, M_TEMP);
4038 			break;
4039 		}
4040 		PF_RULES_WLOCK();
4041 		error = pfr_set_tflags(pfrts, io->pfrio_size,
4042 		    io->pfrio_setflag, io->pfrio_clrflag, &io->pfrio_nchange,
4043 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4044 		PF_RULES_WUNLOCK();
4045 		free(pfrts, M_TEMP);
4046 		break;
4047 	}
4048 
4049 	case DIOCRCLRADDRS: {
4050 		struct pfioc_table *io = (struct pfioc_table *)addr;
4051 
4052 		if (io->pfrio_esize != 0) {
4053 			error = ENODEV;
4054 			break;
4055 		}
4056 		PF_RULES_WLOCK();
4057 		error = pfr_clr_addrs(&io->pfrio_table, &io->pfrio_ndel,
4058 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
4059 		PF_RULES_WUNLOCK();
4060 		break;
4061 	}
4062 
4063 	case DIOCRADDADDRS: {
4064 		struct pfioc_table *io = (struct pfioc_table *)addr;
4065 		struct pfr_addr *pfras;
4066 		size_t totlen;
4067 
4068 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4069 			error = ENODEV;
4070 			break;
4071 		}
4072 		if (io->pfrio_size < 0 ||
4073 		    io->pfrio_size > pf_ioctl_maxcount ||
4074 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4075 			error = EINVAL;
4076 			break;
4077 		}
4078 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4079 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4080 		    M_TEMP, M_WAITOK);
4081 		error = copyin(io->pfrio_buffer, pfras, totlen);
4082 		if (error) {
4083 			free(pfras, M_TEMP);
4084 			break;
4085 		}
4086 		PF_RULES_WLOCK();
4087 		error = pfr_add_addrs(&io->pfrio_table, pfras,
4088 		    io->pfrio_size, &io->pfrio_nadd, io->pfrio_flags |
4089 		    PFR_FLAG_USERIOCTL);
4090 		PF_RULES_WUNLOCK();
4091 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4092 			error = copyout(pfras, io->pfrio_buffer, totlen);
4093 		free(pfras, M_TEMP);
4094 		break;
4095 	}
4096 
4097 	case DIOCRDELADDRS: {
4098 		struct pfioc_table *io = (struct pfioc_table *)addr;
4099 		struct pfr_addr *pfras;
4100 		size_t totlen;
4101 
4102 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4103 			error = ENODEV;
4104 			break;
4105 		}
4106 		if (io->pfrio_size < 0 ||
4107 		    io->pfrio_size > pf_ioctl_maxcount ||
4108 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4109 			error = EINVAL;
4110 			break;
4111 		}
4112 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4113 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4114 		    M_TEMP, M_WAITOK);
4115 		error = copyin(io->pfrio_buffer, pfras, totlen);
4116 		if (error) {
4117 			free(pfras, M_TEMP);
4118 			break;
4119 		}
4120 		PF_RULES_WLOCK();
4121 		error = pfr_del_addrs(&io->pfrio_table, pfras,
4122 		    io->pfrio_size, &io->pfrio_ndel, io->pfrio_flags |
4123 		    PFR_FLAG_USERIOCTL);
4124 		PF_RULES_WUNLOCK();
4125 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4126 			error = copyout(pfras, io->pfrio_buffer, totlen);
4127 		free(pfras, M_TEMP);
4128 		break;
4129 	}
4130 
4131 	case DIOCRSETADDRS: {
4132 		struct pfioc_table *io = (struct pfioc_table *)addr;
4133 		struct pfr_addr *pfras;
4134 		size_t totlen, count;
4135 
4136 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4137 			error = ENODEV;
4138 			break;
4139 		}
4140 		if (io->pfrio_size < 0 || io->pfrio_size2 < 0) {
4141 			error = EINVAL;
4142 			break;
4143 		}
4144 		count = max(io->pfrio_size, io->pfrio_size2);
4145 		if (count > pf_ioctl_maxcount ||
4146 		    WOULD_OVERFLOW(count, sizeof(struct pfr_addr))) {
4147 			error = EINVAL;
4148 			break;
4149 		}
4150 		totlen = count * sizeof(struct pfr_addr);
4151 		pfras = mallocarray(count, sizeof(struct pfr_addr), M_TEMP,
4152 		    M_WAITOK);
4153 		error = copyin(io->pfrio_buffer, pfras, totlen);
4154 		if (error) {
4155 			free(pfras, M_TEMP);
4156 			break;
4157 		}
4158 		PF_RULES_WLOCK();
4159 		error = pfr_set_addrs(&io->pfrio_table, pfras,
4160 		    io->pfrio_size, &io->pfrio_size2, &io->pfrio_nadd,
4161 		    &io->pfrio_ndel, &io->pfrio_nchange, io->pfrio_flags |
4162 		    PFR_FLAG_USERIOCTL, 0);
4163 		PF_RULES_WUNLOCK();
4164 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4165 			error = copyout(pfras, io->pfrio_buffer, totlen);
4166 		free(pfras, M_TEMP);
4167 		break;
4168 	}
4169 
4170 	case DIOCRGETADDRS: {
4171 		struct pfioc_table *io = (struct pfioc_table *)addr;
4172 		struct pfr_addr *pfras;
4173 		size_t totlen;
4174 
4175 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4176 			error = ENODEV;
4177 			break;
4178 		}
4179 		if (io->pfrio_size < 0 ||
4180 		    io->pfrio_size > pf_ioctl_maxcount ||
4181 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4182 			error = EINVAL;
4183 			break;
4184 		}
4185 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4186 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4187 		    M_TEMP, M_WAITOK | M_ZERO);
4188 		PF_RULES_RLOCK();
4189 		error = pfr_get_addrs(&io->pfrio_table, pfras,
4190 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4191 		PF_RULES_RUNLOCK();
4192 		if (error == 0)
4193 			error = copyout(pfras, io->pfrio_buffer, totlen);
4194 		free(pfras, M_TEMP);
4195 		break;
4196 	}
4197 
4198 	case DIOCRGETASTATS: {
4199 		struct pfioc_table *io = (struct pfioc_table *)addr;
4200 		struct pfr_astats *pfrastats;
4201 		size_t totlen;
4202 
4203 		if (io->pfrio_esize != sizeof(struct pfr_astats)) {
4204 			error = ENODEV;
4205 			break;
4206 		}
4207 		if (io->pfrio_size < 0 ||
4208 		    io->pfrio_size > pf_ioctl_maxcount ||
4209 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_astats))) {
4210 			error = EINVAL;
4211 			break;
4212 		}
4213 		totlen = io->pfrio_size * sizeof(struct pfr_astats);
4214 		pfrastats = mallocarray(io->pfrio_size,
4215 		    sizeof(struct pfr_astats), M_TEMP, M_WAITOK | M_ZERO);
4216 		PF_RULES_RLOCK();
4217 		error = pfr_get_astats(&io->pfrio_table, pfrastats,
4218 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4219 		PF_RULES_RUNLOCK();
4220 		if (error == 0)
4221 			error = copyout(pfrastats, io->pfrio_buffer, totlen);
4222 		free(pfrastats, M_TEMP);
4223 		break;
4224 	}
4225 
4226 	case DIOCRCLRASTATS: {
4227 		struct pfioc_table *io = (struct pfioc_table *)addr;
4228 		struct pfr_addr *pfras;
4229 		size_t totlen;
4230 
4231 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4232 			error = ENODEV;
4233 			break;
4234 		}
4235 		if (io->pfrio_size < 0 ||
4236 		    io->pfrio_size > pf_ioctl_maxcount ||
4237 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4238 			error = EINVAL;
4239 			break;
4240 		}
4241 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4242 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4243 		    M_TEMP, M_WAITOK);
4244 		error = copyin(io->pfrio_buffer, pfras, totlen);
4245 		if (error) {
4246 			free(pfras, M_TEMP);
4247 			break;
4248 		}
4249 		PF_RULES_WLOCK();
4250 		error = pfr_clr_astats(&io->pfrio_table, pfras,
4251 		    io->pfrio_size, &io->pfrio_nzero, io->pfrio_flags |
4252 		    PFR_FLAG_USERIOCTL);
4253 		PF_RULES_WUNLOCK();
4254 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
4255 			error = copyout(pfras, io->pfrio_buffer, totlen);
4256 		free(pfras, M_TEMP);
4257 		break;
4258 	}
4259 
4260 	case DIOCRTSTADDRS: {
4261 		struct pfioc_table *io = (struct pfioc_table *)addr;
4262 		struct pfr_addr *pfras;
4263 		size_t totlen;
4264 
4265 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4266 			error = ENODEV;
4267 			break;
4268 		}
4269 		if (io->pfrio_size < 0 ||
4270 		    io->pfrio_size > pf_ioctl_maxcount ||
4271 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4272 			error = EINVAL;
4273 			break;
4274 		}
4275 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4276 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4277 		    M_TEMP, M_WAITOK);
4278 		error = copyin(io->pfrio_buffer, pfras, totlen);
4279 		if (error) {
4280 			free(pfras, M_TEMP);
4281 			break;
4282 		}
4283 		PF_RULES_RLOCK();
4284 		error = pfr_tst_addrs(&io->pfrio_table, pfras,
4285 		    io->pfrio_size, &io->pfrio_nmatch, io->pfrio_flags |
4286 		    PFR_FLAG_USERIOCTL);
4287 		PF_RULES_RUNLOCK();
4288 		if (error == 0)
4289 			error = copyout(pfras, io->pfrio_buffer, totlen);
4290 		free(pfras, M_TEMP);
4291 		break;
4292 	}
4293 
4294 	case DIOCRINADEFINE: {
4295 		struct pfioc_table *io = (struct pfioc_table *)addr;
4296 		struct pfr_addr *pfras;
4297 		size_t totlen;
4298 
4299 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
4300 			error = ENODEV;
4301 			break;
4302 		}
4303 		if (io->pfrio_size < 0 ||
4304 		    io->pfrio_size > pf_ioctl_maxcount ||
4305 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
4306 			error = EINVAL;
4307 			break;
4308 		}
4309 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
4310 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
4311 		    M_TEMP, M_WAITOK);
4312 		error = copyin(io->pfrio_buffer, pfras, totlen);
4313 		if (error) {
4314 			free(pfras, M_TEMP);
4315 			break;
4316 		}
4317 		PF_RULES_WLOCK();
4318 		error = pfr_ina_define(&io->pfrio_table, pfras,
4319 		    io->pfrio_size, &io->pfrio_nadd, &io->pfrio_naddr,
4320 		    io->pfrio_ticket, io->pfrio_flags | PFR_FLAG_USERIOCTL);
4321 		PF_RULES_WUNLOCK();
4322 		free(pfras, M_TEMP);
4323 		break;
4324 	}
4325 
4326 	case DIOCOSFPADD: {
4327 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
4328 		PF_RULES_WLOCK();
4329 		error = pf_osfp_add(io);
4330 		PF_RULES_WUNLOCK();
4331 		break;
4332 	}
4333 
4334 	case DIOCOSFPGET: {
4335 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
4336 		PF_RULES_RLOCK();
4337 		error = pf_osfp_get(io);
4338 		PF_RULES_RUNLOCK();
4339 		break;
4340 	}
4341 
4342 	case DIOCXBEGIN: {
4343 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
4344 		struct pfioc_trans_e	*ioes, *ioe;
4345 		size_t			 totlen;
4346 		int			 i;
4347 
4348 		if (io->esize != sizeof(*ioe)) {
4349 			error = ENODEV;
4350 			break;
4351 		}
4352 		if (io->size < 0 ||
4353 		    io->size > pf_ioctl_maxcount ||
4354 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
4355 			error = EINVAL;
4356 			break;
4357 		}
4358 		totlen = sizeof(struct pfioc_trans_e) * io->size;
4359 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
4360 		    M_TEMP, M_WAITOK);
4361 		error = copyin(io->array, ioes, totlen);
4362 		if (error) {
4363 			free(ioes, M_TEMP);
4364 			break;
4365 		}
4366 		PF_RULES_WLOCK();
4367 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
4368 			ioe->anchor[sizeof(ioe->anchor) - 1] = '\0';
4369 			switch (ioe->rs_num) {
4370 #ifdef ALTQ
4371 			case PF_RULESET_ALTQ:
4372 				if (ioe->anchor[0]) {
4373 					PF_RULES_WUNLOCK();
4374 					free(ioes, M_TEMP);
4375 					error = EINVAL;
4376 					goto fail;
4377 				}
4378 				if ((error = pf_begin_altq(&ioe->ticket))) {
4379 					PF_RULES_WUNLOCK();
4380 					free(ioes, M_TEMP);
4381 					goto fail;
4382 				}
4383 				break;
4384 #endif /* ALTQ */
4385 			case PF_RULESET_TABLE:
4386 			    {
4387 				struct pfr_table table;
4388 
4389 				bzero(&table, sizeof(table));
4390 				strlcpy(table.pfrt_anchor, ioe->anchor,
4391 				    sizeof(table.pfrt_anchor));
4392 				if ((error = pfr_ina_begin(&table,
4393 				    &ioe->ticket, NULL, 0))) {
4394 					PF_RULES_WUNLOCK();
4395 					free(ioes, M_TEMP);
4396 					goto fail;
4397 				}
4398 				break;
4399 			    }
4400 			default:
4401 				if ((error = pf_begin_rules(&ioe->ticket,
4402 				    ioe->rs_num, ioe->anchor))) {
4403 					PF_RULES_WUNLOCK();
4404 					free(ioes, M_TEMP);
4405 					goto fail;
4406 				}
4407 				break;
4408 			}
4409 		}
4410 		PF_RULES_WUNLOCK();
4411 		error = copyout(ioes, io->array, totlen);
4412 		free(ioes, M_TEMP);
4413 		break;
4414 	}
4415 
4416 	case DIOCXROLLBACK: {
4417 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
4418 		struct pfioc_trans_e	*ioe, *ioes;
4419 		size_t			 totlen;
4420 		int			 i;
4421 
4422 		if (io->esize != sizeof(*ioe)) {
4423 			error = ENODEV;
4424 			break;
4425 		}
4426 		if (io->size < 0 ||
4427 		    io->size > pf_ioctl_maxcount ||
4428 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
4429 			error = EINVAL;
4430 			break;
4431 		}
4432 		totlen = sizeof(struct pfioc_trans_e) * io->size;
4433 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
4434 		    M_TEMP, M_WAITOK);
4435 		error = copyin(io->array, ioes, totlen);
4436 		if (error) {
4437 			free(ioes, M_TEMP);
4438 			break;
4439 		}
4440 		PF_RULES_WLOCK();
4441 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
4442 			ioe->anchor[sizeof(ioe->anchor) - 1] = '\0';
4443 			switch (ioe->rs_num) {
4444 #ifdef ALTQ
4445 			case PF_RULESET_ALTQ:
4446 				if (ioe->anchor[0]) {
4447 					PF_RULES_WUNLOCK();
4448 					free(ioes, M_TEMP);
4449 					error = EINVAL;
4450 					goto fail;
4451 				}
4452 				if ((error = pf_rollback_altq(ioe->ticket))) {
4453 					PF_RULES_WUNLOCK();
4454 					free(ioes, M_TEMP);
4455 					goto fail; /* really bad */
4456 				}
4457 				break;
4458 #endif /* ALTQ */
4459 			case PF_RULESET_TABLE:
4460 			    {
4461 				struct pfr_table table;
4462 
4463 				bzero(&table, sizeof(table));
4464 				strlcpy(table.pfrt_anchor, ioe->anchor,
4465 				    sizeof(table.pfrt_anchor));
4466 				if ((error = pfr_ina_rollback(&table,
4467 				    ioe->ticket, NULL, 0))) {
4468 					PF_RULES_WUNLOCK();
4469 					free(ioes, M_TEMP);
4470 					goto fail; /* really bad */
4471 				}
4472 				break;
4473 			    }
4474 			default:
4475 				if ((error = pf_rollback_rules(ioe->ticket,
4476 				    ioe->rs_num, ioe->anchor))) {
4477 					PF_RULES_WUNLOCK();
4478 					free(ioes, M_TEMP);
4479 					goto fail; /* really bad */
4480 				}
4481 				break;
4482 			}
4483 		}
4484 		PF_RULES_WUNLOCK();
4485 		free(ioes, M_TEMP);
4486 		break;
4487 	}
4488 
4489 	case DIOCXCOMMIT: {
4490 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
4491 		struct pfioc_trans_e	*ioe, *ioes;
4492 		struct pf_kruleset	*rs;
4493 		size_t			 totlen;
4494 		int			 i;
4495 
4496 		if (io->esize != sizeof(*ioe)) {
4497 			error = ENODEV;
4498 			break;
4499 		}
4500 
4501 		if (io->size < 0 ||
4502 		    io->size > pf_ioctl_maxcount ||
4503 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
4504 			error = EINVAL;
4505 			break;
4506 		}
4507 
4508 		totlen = sizeof(struct pfioc_trans_e) * io->size;
4509 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
4510 		    M_TEMP, M_WAITOK);
4511 		error = copyin(io->array, ioes, totlen);
4512 		if (error) {
4513 			free(ioes, M_TEMP);
4514 			break;
4515 		}
4516 		PF_RULES_WLOCK();
4517 		/* First makes sure everything will succeed. */
4518 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
4519 			ioe->anchor[sizeof(ioe->anchor) - 1] = 0;
4520 			switch (ioe->rs_num) {
4521 #ifdef ALTQ
4522 			case PF_RULESET_ALTQ:
4523 				if (ioe->anchor[0]) {
4524 					PF_RULES_WUNLOCK();
4525 					free(ioes, M_TEMP);
4526 					error = EINVAL;
4527 					goto fail;
4528 				}
4529 				if (!V_altqs_inactive_open || ioe->ticket !=
4530 				    V_ticket_altqs_inactive) {
4531 					PF_RULES_WUNLOCK();
4532 					free(ioes, M_TEMP);
4533 					error = EBUSY;
4534 					goto fail;
4535 				}
4536 				break;
4537 #endif /* ALTQ */
4538 			case PF_RULESET_TABLE:
4539 				rs = pf_find_kruleset(ioe->anchor);
4540 				if (rs == NULL || !rs->topen || ioe->ticket !=
4541 				    rs->tticket) {
4542 					PF_RULES_WUNLOCK();
4543 					free(ioes, M_TEMP);
4544 					error = EBUSY;
4545 					goto fail;
4546 				}
4547 				break;
4548 			default:
4549 				if (ioe->rs_num < 0 || ioe->rs_num >=
4550 				    PF_RULESET_MAX) {
4551 					PF_RULES_WUNLOCK();
4552 					free(ioes, M_TEMP);
4553 					error = EINVAL;
4554 					goto fail;
4555 				}
4556 				rs = pf_find_kruleset(ioe->anchor);
4557 				if (rs == NULL ||
4558 				    !rs->rules[ioe->rs_num].inactive.open ||
4559 				    rs->rules[ioe->rs_num].inactive.ticket !=
4560 				    ioe->ticket) {
4561 					PF_RULES_WUNLOCK();
4562 					free(ioes, M_TEMP);
4563 					error = EBUSY;
4564 					goto fail;
4565 				}
4566 				break;
4567 			}
4568 		}
4569 		/* Now do the commit - no errors should happen here. */
4570 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
4571 			switch (ioe->rs_num) {
4572 #ifdef ALTQ
4573 			case PF_RULESET_ALTQ:
4574 				if ((error = pf_commit_altq(ioe->ticket))) {
4575 					PF_RULES_WUNLOCK();
4576 					free(ioes, M_TEMP);
4577 					goto fail; /* really bad */
4578 				}
4579 				break;
4580 #endif /* ALTQ */
4581 			case PF_RULESET_TABLE:
4582 			    {
4583 				struct pfr_table table;
4584 
4585 				bzero(&table, sizeof(table));
4586 				(void)strlcpy(table.pfrt_anchor, ioe->anchor,
4587 				    sizeof(table.pfrt_anchor));
4588 				if ((error = pfr_ina_commit(&table,
4589 				    ioe->ticket, NULL, NULL, 0))) {
4590 					PF_RULES_WUNLOCK();
4591 					free(ioes, M_TEMP);
4592 					goto fail; /* really bad */
4593 				}
4594 				break;
4595 			    }
4596 			default:
4597 				if ((error = pf_commit_rules(ioe->ticket,
4598 				    ioe->rs_num, ioe->anchor))) {
4599 					PF_RULES_WUNLOCK();
4600 					free(ioes, M_TEMP);
4601 					goto fail; /* really bad */
4602 				}
4603 				break;
4604 			}
4605 		}
4606 		PF_RULES_WUNLOCK();
4607 		free(ioes, M_TEMP);
4608 		break;
4609 	}
4610 
4611 	case DIOCGETSRCNODES: {
4612 		struct pfioc_src_nodes	*psn = (struct pfioc_src_nodes *)addr;
4613 		struct pf_srchash	*sh;
4614 		struct pf_ksrc_node	*n;
4615 		struct pf_src_node	*p, *pstore;
4616 		uint32_t		 i, nr = 0;
4617 
4618 		for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
4619 				i++, sh++) {
4620 			PF_HASHROW_LOCK(sh);
4621 			LIST_FOREACH(n, &sh->nodes, entry)
4622 				nr++;
4623 			PF_HASHROW_UNLOCK(sh);
4624 		}
4625 
4626 		psn->psn_len = min(psn->psn_len,
4627 		    sizeof(struct pf_src_node) * nr);
4628 
4629 		if (psn->psn_len == 0) {
4630 			psn->psn_len = sizeof(struct pf_src_node) * nr;
4631 			break;
4632 		}
4633 
4634 		nr = 0;
4635 
4636 		p = pstore = malloc(psn->psn_len, M_TEMP, M_WAITOK | M_ZERO);
4637 		for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
4638 		    i++, sh++) {
4639 		    PF_HASHROW_LOCK(sh);
4640 		    LIST_FOREACH(n, &sh->nodes, entry) {
4641 
4642 			if ((nr + 1) * sizeof(*p) > (unsigned)psn->psn_len)
4643 				break;
4644 
4645 			pf_src_node_copy(n, p);
4646 
4647 			p++;
4648 			nr++;
4649 		    }
4650 		    PF_HASHROW_UNLOCK(sh);
4651 		}
4652 		error = copyout(pstore, psn->psn_src_nodes,
4653 		    sizeof(struct pf_src_node) * nr);
4654 		if (error) {
4655 			free(pstore, M_TEMP);
4656 			break;
4657 		}
4658 		psn->psn_len = sizeof(struct pf_src_node) * nr;
4659 		free(pstore, M_TEMP);
4660 		break;
4661 	}
4662 
4663 	case DIOCCLRSRCNODES: {
4664 		pf_clear_srcnodes(NULL);
4665 		pf_purge_expired_src_nodes();
4666 		break;
4667 	}
4668 
4669 	case DIOCKILLSRCNODES:
4670 		pf_kill_srcnodes((struct pfioc_src_node_kill *)addr);
4671 		break;
4672 
4673 #ifdef COMPAT_FREEBSD13
4674 	case DIOCKEEPCOUNTERS_FREEBSD13:
4675 #endif
4676 	case DIOCKEEPCOUNTERS:
4677 		error = pf_keepcounters((struct pfioc_nv *)addr);
4678 		break;
4679 
4680 	case DIOCGETSYNCOOKIES:
4681 		error = pf_get_syncookies((struct pfioc_nv *)addr);
4682 		break;
4683 
4684 	case DIOCSETSYNCOOKIES:
4685 		error = pf_set_syncookies((struct pfioc_nv *)addr);
4686 		break;
4687 
4688 	case DIOCSETHOSTID: {
4689 		u_int32_t	*hostid = (u_int32_t *)addr;
4690 
4691 		PF_RULES_WLOCK();
4692 		if (*hostid == 0)
4693 			V_pf_status.hostid = arc4random();
4694 		else
4695 			V_pf_status.hostid = *hostid;
4696 		PF_RULES_WUNLOCK();
4697 		break;
4698 	}
4699 
4700 	case DIOCOSFPFLUSH:
4701 		PF_RULES_WLOCK();
4702 		pf_osfp_flush();
4703 		PF_RULES_WUNLOCK();
4704 		break;
4705 
4706 	case DIOCIGETIFACES: {
4707 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
4708 		struct pfi_kif *ifstore;
4709 		size_t bufsiz;
4710 
4711 		if (io->pfiio_esize != sizeof(struct pfi_kif)) {
4712 			error = ENODEV;
4713 			break;
4714 		}
4715 
4716 		if (io->pfiio_size < 0 ||
4717 		    io->pfiio_size > pf_ioctl_maxcount ||
4718 		    WOULD_OVERFLOW(io->pfiio_size, sizeof(struct pfi_kif))) {
4719 			error = EINVAL;
4720 			break;
4721 		}
4722 
4723 		bufsiz = io->pfiio_size * sizeof(struct pfi_kif);
4724 		ifstore = mallocarray(io->pfiio_size, sizeof(struct pfi_kif),
4725 		    M_TEMP, M_WAITOK | M_ZERO);
4726 
4727 		PF_RULES_RLOCK();
4728 		pfi_get_ifaces(io->pfiio_name, ifstore, &io->pfiio_size);
4729 		PF_RULES_RUNLOCK();
4730 		error = copyout(ifstore, io->pfiio_buffer, bufsiz);
4731 		free(ifstore, M_TEMP);
4732 		break;
4733 	}
4734 
4735 	case DIOCSETIFFLAG: {
4736 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
4737 
4738 		PF_RULES_WLOCK();
4739 		error = pfi_set_flags(io->pfiio_name, io->pfiio_flags);
4740 		PF_RULES_WUNLOCK();
4741 		break;
4742 	}
4743 
4744 	case DIOCCLRIFFLAG: {
4745 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
4746 
4747 		PF_RULES_WLOCK();
4748 		error = pfi_clear_flags(io->pfiio_name, io->pfiio_flags);
4749 		PF_RULES_WUNLOCK();
4750 		break;
4751 	}
4752 
4753 	default:
4754 		error = ENODEV;
4755 		break;
4756 	}
4757 fail:
4758 	if (sx_xlocked(&pf_ioctl_lock))
4759 		sx_xunlock(&pf_ioctl_lock);
4760 	CURVNET_RESTORE();
4761 
4762 #undef ERROUT_IOCTL
4763 
4764 	return (error);
4765 }
4766 
4767 void
4768 pfsync_state_export(struct pfsync_state *sp, struct pf_kstate *st)
4769 {
4770 	bzero(sp, sizeof(struct pfsync_state));
4771 
4772 	/* copy from state key */
4773 	sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
4774 	sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
4775 	sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
4776 	sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
4777 	sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
4778 	sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
4779 	sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
4780 	sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
4781 	sp->proto = st->key[PF_SK_WIRE]->proto;
4782 	sp->af = st->key[PF_SK_WIRE]->af;
4783 
4784 	/* copy from state */
4785 	strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
4786 	bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));
4787 	sp->creation = htonl(time_uptime - st->creation);
4788 	sp->expire = pf_state_expires(st);
4789 	if (sp->expire <= time_uptime)
4790 		sp->expire = htonl(0);
4791 	else
4792 		sp->expire = htonl(sp->expire - time_uptime);
4793 
4794 	sp->direction = st->direction;
4795 	sp->log = st->log;
4796 	sp->timeout = st->timeout;
4797 	sp->state_flags = st->state_flags;
4798 	if (st->src_node)
4799 		sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
4800 	if (st->nat_src_node)
4801 		sp->sync_flags |= PFSYNC_FLAG_NATSRCNODE;
4802 
4803 	sp->id = st->id;
4804 	sp->creatorid = st->creatorid;
4805 	pf_state_peer_hton(&st->src, &sp->src);
4806 	pf_state_peer_hton(&st->dst, &sp->dst);
4807 
4808 	if (st->rule.ptr == NULL)
4809 		sp->rule = htonl(-1);
4810 	else
4811 		sp->rule = htonl(st->rule.ptr->nr);
4812 	if (st->anchor.ptr == NULL)
4813 		sp->anchor = htonl(-1);
4814 	else
4815 		sp->anchor = htonl(st->anchor.ptr->nr);
4816 	if (st->nat_rule.ptr == NULL)
4817 		sp->nat_rule = htonl(-1);
4818 	else
4819 		sp->nat_rule = htonl(st->nat_rule.ptr->nr);
4820 
4821 	pf_state_counter_hton(st->packets[0], sp->packets[0]);
4822 	pf_state_counter_hton(st->packets[1], sp->packets[1]);
4823 	pf_state_counter_hton(st->bytes[0], sp->bytes[0]);
4824 	pf_state_counter_hton(st->bytes[1], sp->bytes[1]);
4825 }
4826 
4827 void
4828 pf_state_export(struct pf_state_export *sp, struct pf_kstate *st)
4829 {
4830 	bzero(sp, sizeof(*sp));
4831 
4832 	sp->version = PF_STATE_VERSION;
4833 
4834 	/* copy from state key */
4835 	sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
4836 	sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
4837 	sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
4838 	sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
4839 	sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
4840 	sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
4841 	sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
4842 	sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
4843 	sp->proto = st->key[PF_SK_WIRE]->proto;
4844 	sp->af = st->key[PF_SK_WIRE]->af;
4845 
4846 	/* copy from state */
4847 	strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
4848 	strlcpy(sp->orig_ifname, st->orig_kif->pfik_name,
4849 	    sizeof(sp->orig_ifname));
4850 	bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));
4851 	sp->creation = htonl(time_uptime - st->creation);
4852 	sp->expire = pf_state_expires(st);
4853 	if (sp->expire <= time_uptime)
4854 		sp->expire = htonl(0);
4855 	else
4856 		sp->expire = htonl(sp->expire - time_uptime);
4857 
4858 	sp->direction = st->direction;
4859 	sp->log = st->log;
4860 	sp->timeout = st->timeout;
4861 	sp->state_flags = st->state_flags;
4862 	if (st->src_node)
4863 		sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
4864 	if (st->nat_src_node)
4865 		sp->sync_flags |= PFSYNC_FLAG_NATSRCNODE;
4866 
4867 	sp->id = st->id;
4868 	sp->creatorid = st->creatorid;
4869 	pf_state_peer_hton(&st->src, &sp->src);
4870 	pf_state_peer_hton(&st->dst, &sp->dst);
4871 
4872 	if (st->rule.ptr == NULL)
4873 		sp->rule = htonl(-1);
4874 	else
4875 		sp->rule = htonl(st->rule.ptr->nr);
4876 	if (st->anchor.ptr == NULL)
4877 		sp->anchor = htonl(-1);
4878 	else
4879 		sp->anchor = htonl(st->anchor.ptr->nr);
4880 	if (st->nat_rule.ptr == NULL)
4881 		sp->nat_rule = htonl(-1);
4882 	else
4883 		sp->nat_rule = htonl(st->nat_rule.ptr->nr);
4884 
4885 	sp->packets[0] = st->packets[0];
4886 	sp->packets[1] = st->packets[1];
4887 	sp->bytes[0] = st->bytes[0];
4888 	sp->bytes[1] = st->bytes[1];
4889 }
4890 
4891 static void
4892 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
4893 {
4894 	struct pfr_ktable *kt;
4895 
4896 	KASSERT(aw->type == PF_ADDR_TABLE, ("%s: type %u", __func__, aw->type));
4897 
4898 	kt = aw->p.tbl;
4899 	if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
4900 		kt = kt->pfrkt_root;
4901 	aw->p.tbl = NULL;
4902 	aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
4903 		kt->pfrkt_cnt : -1;
4904 }
4905 
4906 static int
4907 pf_add_status_counters(nvlist_t *nvl, const char *name, counter_u64_t *counters,
4908     size_t number, char **names)
4909 {
4910 	nvlist_t        *nvc;
4911 
4912 	nvc = nvlist_create(0);
4913 	if (nvc == NULL)
4914 		return (ENOMEM);
4915 
4916 	for (int i = 0; i < number; i++) {
4917 		nvlist_append_number_array(nvc, "counters",
4918 		    counter_u64_fetch(counters[i]));
4919 		nvlist_append_string_array(nvc, "names",
4920 		    names[i]);
4921 		nvlist_append_number_array(nvc, "ids",
4922 		    i);
4923 	}
4924 	nvlist_add_nvlist(nvl, name, nvc);
4925 	nvlist_destroy(nvc);
4926 
4927 	return (0);
4928 }
4929 
4930 static int
4931 pf_getstatus(struct pfioc_nv *nv)
4932 {
4933 	nvlist_t        *nvl = NULL, *nvc = NULL;
4934 	void            *nvlpacked = NULL;
4935 	int              error;
4936 	struct pf_status s;
4937 	char *pf_reasons[PFRES_MAX+1] = PFRES_NAMES;
4938 	char *pf_lcounter[KLCNT_MAX+1] = KLCNT_NAMES;
4939 	char *pf_fcounter[FCNT_MAX+1] = FCNT_NAMES;
4940 	PF_RULES_RLOCK_TRACKER;
4941 
4942 #define ERROUT(x)      ERROUT_FUNCTION(errout, x)
4943 
4944 	PF_RULES_RLOCK();
4945 
4946 	nvl = nvlist_create(0);
4947 	if (nvl == NULL)
4948 		ERROUT(ENOMEM);
4949 
4950 	nvlist_add_bool(nvl, "running", V_pf_status.running);
4951 	nvlist_add_number(nvl, "since", V_pf_status.since);
4952 	nvlist_add_number(nvl, "debug", V_pf_status.debug);
4953 	nvlist_add_number(nvl, "hostid", V_pf_status.hostid);
4954 	nvlist_add_number(nvl, "states", V_pf_status.states);
4955 	nvlist_add_number(nvl, "src_nodes", V_pf_status.src_nodes);
4956 
4957 	/* counters */
4958 	error = pf_add_status_counters(nvl, "counters", V_pf_status.counters,
4959 	    PFRES_MAX, pf_reasons);
4960 	if (error != 0)
4961 		ERROUT(error);
4962 
4963 	/* lcounters */
4964 	error = pf_add_status_counters(nvl, "lcounters", V_pf_status.lcounters,
4965 	    KLCNT_MAX, pf_lcounter);
4966 	if (error != 0)
4967 		ERROUT(error);
4968 
4969 	/* fcounters */
4970 	nvc = nvlist_create(0);
4971 	if (nvc == NULL)
4972 		ERROUT(ENOMEM);
4973 
4974 	for (int i = 0; i < FCNT_MAX; i++) {
4975 		nvlist_append_number_array(nvc, "counters",
4976 		    pf_counter_u64_fetch(&V_pf_status.fcounters[i]));
4977 		nvlist_append_string_array(nvc, "names",
4978 		    pf_fcounter[i]);
4979 		nvlist_append_number_array(nvc, "ids",
4980 		    i);
4981 	}
4982 	nvlist_add_nvlist(nvl, "fcounters", nvc);
4983 	nvlist_destroy(nvc);
4984 	nvc = NULL;
4985 
4986 	/* scounters */
4987 	error = pf_add_status_counters(nvl, "scounters", V_pf_status.scounters,
4988 	    SCNT_MAX, pf_fcounter);
4989 	if (error != 0)
4990 		ERROUT(error);
4991 
4992 	nvlist_add_string(nvl, "ifname", V_pf_status.ifname);
4993 	nvlist_add_binary(nvl, "chksum", V_pf_status.pf_chksum,
4994 	    PF_MD5_DIGEST_LENGTH);
4995 
4996 	pfi_update_status(V_pf_status.ifname, &s);
4997 
4998 	/* pcounters / bcounters */
4999 	for (int i = 0; i < 2; i++) {
5000 		for (int j = 0; j < 2; j++) {
5001 			for (int k = 0; k < 2; k++) {
5002 				nvlist_append_number_array(nvl, "pcounters",
5003 				    s.pcounters[i][j][k]);
5004 			}
5005 			nvlist_append_number_array(nvl, "bcounters",
5006 			    s.bcounters[i][j]);
5007 		}
5008 	}
5009 
5010 	nvlpacked = nvlist_pack(nvl, &nv->len);
5011 	if (nvlpacked == NULL)
5012 		ERROUT(ENOMEM);
5013 
5014 	if (nv->size == 0)
5015 		ERROUT(0);
5016 	else if (nv->size < nv->len)
5017 		ERROUT(ENOSPC);
5018 
5019 	PF_RULES_RUNLOCK();
5020 	error = copyout(nvlpacked, nv->data, nv->len);
5021 	goto done;
5022 
5023 #undef ERROUT
5024 errout:
5025 	PF_RULES_RUNLOCK();
5026 done:
5027 	free(nvlpacked, M_NVLIST);
5028 	nvlist_destroy(nvc);
5029 	nvlist_destroy(nvl);
5030 
5031 	return (error);
5032 }
5033 
5034 /*
5035  * XXX - Check for version missmatch!!!
5036  */
5037 static void
5038 pf_clear_all_states(void)
5039 {
5040 	struct pf_kstate	*s;
5041 	u_int i;
5042 
5043 	for (i = 0; i <= pf_hashmask; i++) {
5044 		struct pf_idhash *ih = &V_pf_idhash[i];
5045 relock:
5046 		PF_HASHROW_LOCK(ih);
5047 		LIST_FOREACH(s, &ih->states, entry) {
5048 			s->timeout = PFTM_PURGE;
5049 			/* Don't send out individual delete messages. */
5050 			s->state_flags |= PFSTATE_NOSYNC;
5051 			pf_unlink_state(s);
5052 			goto relock;
5053 		}
5054 		PF_HASHROW_UNLOCK(ih);
5055 	}
5056 }
5057 
5058 static int
5059 pf_clear_tables(void)
5060 {
5061 	struct pfioc_table io;
5062 	int error;
5063 
5064 	bzero(&io, sizeof(io));
5065 
5066 	error = pfr_clr_tables(&io.pfrio_table, &io.pfrio_ndel,
5067 	    io.pfrio_flags);
5068 
5069 	return (error);
5070 }
5071 
5072 static void
5073 pf_clear_srcnodes(struct pf_ksrc_node *n)
5074 {
5075 	struct pf_kstate *s;
5076 	int i;
5077 
5078 	for (i = 0; i <= pf_hashmask; i++) {
5079 		struct pf_idhash *ih = &V_pf_idhash[i];
5080 
5081 		PF_HASHROW_LOCK(ih);
5082 		LIST_FOREACH(s, &ih->states, entry) {
5083 			if (n == NULL || n == s->src_node)
5084 				s->src_node = NULL;
5085 			if (n == NULL || n == s->nat_src_node)
5086 				s->nat_src_node = NULL;
5087 		}
5088 		PF_HASHROW_UNLOCK(ih);
5089 	}
5090 
5091 	if (n == NULL) {
5092 		struct pf_srchash *sh;
5093 
5094 		for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
5095 		    i++, sh++) {
5096 			PF_HASHROW_LOCK(sh);
5097 			LIST_FOREACH(n, &sh->nodes, entry) {
5098 				n->expire = 1;
5099 				n->states = 0;
5100 			}
5101 			PF_HASHROW_UNLOCK(sh);
5102 		}
5103 	} else {
5104 		/* XXX: hash slot should already be locked here. */
5105 		n->expire = 1;
5106 		n->states = 0;
5107 	}
5108 }
5109 
5110 static void
5111 pf_kill_srcnodes(struct pfioc_src_node_kill *psnk)
5112 {
5113 	struct pf_ksrc_node_list	 kill;
5114 
5115 	LIST_INIT(&kill);
5116 	for (int i = 0; i <= pf_srchashmask; i++) {
5117 		struct pf_srchash *sh = &V_pf_srchash[i];
5118 		struct pf_ksrc_node *sn, *tmp;
5119 
5120 		PF_HASHROW_LOCK(sh);
5121 		LIST_FOREACH_SAFE(sn, &sh->nodes, entry, tmp)
5122 			if (PF_MATCHA(psnk->psnk_src.neg,
5123 			      &psnk->psnk_src.addr.v.a.addr,
5124 			      &psnk->psnk_src.addr.v.a.mask,
5125 			      &sn->addr, sn->af) &&
5126 			    PF_MATCHA(psnk->psnk_dst.neg,
5127 			      &psnk->psnk_dst.addr.v.a.addr,
5128 			      &psnk->psnk_dst.addr.v.a.mask,
5129 			      &sn->raddr, sn->af)) {
5130 				pf_unlink_src_node(sn);
5131 				LIST_INSERT_HEAD(&kill, sn, entry);
5132 				sn->expire = 1;
5133 			}
5134 		PF_HASHROW_UNLOCK(sh);
5135 	}
5136 
5137 	for (int i = 0; i <= pf_hashmask; i++) {
5138 		struct pf_idhash *ih = &V_pf_idhash[i];
5139 		struct pf_kstate *s;
5140 
5141 		PF_HASHROW_LOCK(ih);
5142 		LIST_FOREACH(s, &ih->states, entry) {
5143 			if (s->src_node && s->src_node->expire == 1)
5144 				s->src_node = NULL;
5145 			if (s->nat_src_node && s->nat_src_node->expire == 1)
5146 				s->nat_src_node = NULL;
5147 		}
5148 		PF_HASHROW_UNLOCK(ih);
5149 	}
5150 
5151 	psnk->psnk_killed = pf_free_src_nodes(&kill);
5152 }
5153 
5154 static int
5155 pf_keepcounters(struct pfioc_nv *nv)
5156 {
5157 	nvlist_t	*nvl = NULL;
5158 	void		*nvlpacked = NULL;
5159 	int		 error = 0;
5160 
5161 #define	ERROUT(x)	ERROUT_FUNCTION(on_error, x)
5162 
5163 	if (nv->len > pf_ioctl_maxcount)
5164 		ERROUT(ENOMEM);
5165 
5166 	nvlpacked = malloc(nv->len, M_TEMP, M_WAITOK);
5167 	if (nvlpacked == NULL)
5168 		ERROUT(ENOMEM);
5169 
5170 	error = copyin(nv->data, nvlpacked, nv->len);
5171 	if (error)
5172 		ERROUT(error);
5173 
5174 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
5175 	if (nvl == NULL)
5176 		ERROUT(EBADMSG);
5177 
5178 	if (! nvlist_exists_bool(nvl, "keep_counters"))
5179 		ERROUT(EBADMSG);
5180 
5181 	V_pf_status.keep_counters = nvlist_get_bool(nvl, "keep_counters");
5182 
5183 on_error:
5184 	nvlist_destroy(nvl);
5185 	free(nvlpacked, M_TEMP);
5186 	return (error);
5187 }
5188 
5189 static unsigned int
5190 pf_clear_states(const struct pf_kstate_kill *kill)
5191 {
5192 	struct pf_state_key_cmp	 match_key;
5193 	struct pf_kstate	*s;
5194 	struct pfi_kkif	*kif;
5195 	int		 idx;
5196 	unsigned int	 killed = 0, dir;
5197 
5198 	for (unsigned int i = 0; i <= pf_hashmask; i++) {
5199 		struct pf_idhash *ih = &V_pf_idhash[i];
5200 
5201 relock_DIOCCLRSTATES:
5202 		PF_HASHROW_LOCK(ih);
5203 		LIST_FOREACH(s, &ih->states, entry) {
5204 			/* For floating states look at the original kif. */
5205 			kif = s->kif == V_pfi_all ? s->orig_kif : s->kif;
5206 
5207 			if (kill->psk_ifname[0] &&
5208 			    strcmp(kill->psk_ifname,
5209 			    kif->pfik_name))
5210 				continue;
5211 
5212 			if (kill->psk_kill_match) {
5213 				bzero(&match_key, sizeof(match_key));
5214 
5215 				if (s->direction == PF_OUT) {
5216 					dir = PF_IN;
5217 					idx = PF_SK_STACK;
5218 				} else {
5219 					dir = PF_OUT;
5220 					idx = PF_SK_WIRE;
5221 				}
5222 
5223 				match_key.af = s->key[idx]->af;
5224 				match_key.proto = s->key[idx]->proto;
5225 				PF_ACPY(&match_key.addr[0],
5226 				    &s->key[idx]->addr[1], match_key.af);
5227 				match_key.port[0] = s->key[idx]->port[1];
5228 				PF_ACPY(&match_key.addr[1],
5229 				    &s->key[idx]->addr[0], match_key.af);
5230 				match_key.port[1] = s->key[idx]->port[0];
5231 			}
5232 
5233 			/*
5234 			 * Don't send out individual
5235 			 * delete messages.
5236 			 */
5237 			s->state_flags |= PFSTATE_NOSYNC;
5238 			pf_unlink_state(s);
5239 			killed++;
5240 
5241 			if (kill->psk_kill_match)
5242 				killed += pf_kill_matching_state(&match_key,
5243 				    dir);
5244 
5245 			goto relock_DIOCCLRSTATES;
5246 		}
5247 		PF_HASHROW_UNLOCK(ih);
5248 	}
5249 
5250 	if (V_pfsync_clear_states_ptr != NULL)
5251 		V_pfsync_clear_states_ptr(V_pf_status.hostid, kill->psk_ifname);
5252 
5253 	return (killed);
5254 }
5255 
5256 static void
5257 pf_killstates(struct pf_kstate_kill *kill, unsigned int *killed)
5258 {
5259 	struct pf_kstate	*s;
5260 
5261 	if (kill->psk_pfcmp.id) {
5262 		if (kill->psk_pfcmp.creatorid == 0)
5263 			kill->psk_pfcmp.creatorid = V_pf_status.hostid;
5264 		if ((s = pf_find_state_byid(kill->psk_pfcmp.id,
5265 		    kill->psk_pfcmp.creatorid))) {
5266 			pf_unlink_state(s);
5267 			*killed = 1;
5268 		}
5269 		return;
5270 	}
5271 
5272 	for (unsigned int i = 0; i <= pf_hashmask; i++)
5273 		*killed += pf_killstates_row(kill, &V_pf_idhash[i]);
5274 
5275 	return;
5276 }
5277 
5278 static int
5279 pf_killstates_nv(struct pfioc_nv *nv)
5280 {
5281 	struct pf_kstate_kill	 kill;
5282 	nvlist_t		*nvl = NULL;
5283 	void			*nvlpacked = NULL;
5284 	int			 error = 0;
5285 	unsigned int		 killed = 0;
5286 
5287 #define ERROUT(x)	ERROUT_FUNCTION(on_error, x)
5288 
5289 	if (nv->len > pf_ioctl_maxcount)
5290 		ERROUT(ENOMEM);
5291 
5292 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
5293 	if (nvlpacked == NULL)
5294 		ERROUT(ENOMEM);
5295 
5296 	error = copyin(nv->data, nvlpacked, nv->len);
5297 	if (error)
5298 		ERROUT(error);
5299 
5300 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
5301 	if (nvl == NULL)
5302 		ERROUT(EBADMSG);
5303 
5304 	error = pf_nvstate_kill_to_kstate_kill(nvl, &kill);
5305 	if (error)
5306 		ERROUT(error);
5307 
5308 	pf_killstates(&kill, &killed);
5309 
5310 	free(nvlpacked, M_NVLIST);
5311 	nvlpacked = NULL;
5312 	nvlist_destroy(nvl);
5313 	nvl = nvlist_create(0);
5314 	if (nvl == NULL)
5315 		ERROUT(ENOMEM);
5316 
5317 	nvlist_add_number(nvl, "killed", killed);
5318 
5319 	nvlpacked = nvlist_pack(nvl, &nv->len);
5320 	if (nvlpacked == NULL)
5321 		ERROUT(ENOMEM);
5322 
5323 	if (nv->size == 0)
5324 		ERROUT(0);
5325 	else if (nv->size < nv->len)
5326 		ERROUT(ENOSPC);
5327 
5328 	error = copyout(nvlpacked, nv->data, nv->len);
5329 
5330 on_error:
5331 	nvlist_destroy(nvl);
5332 	free(nvlpacked, M_NVLIST);
5333 	return (error);
5334 }
5335 
5336 static int
5337 pf_clearstates_nv(struct pfioc_nv *nv)
5338 {
5339 	struct pf_kstate_kill	 kill;
5340 	nvlist_t		*nvl = NULL;
5341 	void			*nvlpacked = NULL;
5342 	int			 error = 0;
5343 	unsigned int		 killed;
5344 
5345 #define ERROUT(x)	ERROUT_FUNCTION(on_error, x)
5346 
5347 	if (nv->len > pf_ioctl_maxcount)
5348 		ERROUT(ENOMEM);
5349 
5350 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
5351 	if (nvlpacked == NULL)
5352 		ERROUT(ENOMEM);
5353 
5354 	error = copyin(nv->data, nvlpacked, nv->len);
5355 	if (error)
5356 		ERROUT(error);
5357 
5358 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
5359 	if (nvl == NULL)
5360 		ERROUT(EBADMSG);
5361 
5362 	error = pf_nvstate_kill_to_kstate_kill(nvl, &kill);
5363 	if (error)
5364 		ERROUT(error);
5365 
5366 	killed = pf_clear_states(&kill);
5367 
5368 	free(nvlpacked, M_NVLIST);
5369 	nvlpacked = NULL;
5370 	nvlist_destroy(nvl);
5371 	nvl = nvlist_create(0);
5372 	if (nvl == NULL)
5373 		ERROUT(ENOMEM);
5374 
5375 	nvlist_add_number(nvl, "killed", killed);
5376 
5377 	nvlpacked = nvlist_pack(nvl, &nv->len);
5378 	if (nvlpacked == NULL)
5379 		ERROUT(ENOMEM);
5380 
5381 	if (nv->size == 0)
5382 		ERROUT(0);
5383 	else if (nv->size < nv->len)
5384 		ERROUT(ENOSPC);
5385 
5386 	error = copyout(nvlpacked, nv->data, nv->len);
5387 
5388 #undef ERROUT
5389 on_error:
5390 	nvlist_destroy(nvl);
5391 	free(nvlpacked, M_NVLIST);
5392 	return (error);
5393 }
5394 
5395 static int
5396 pf_getstate(struct pfioc_nv *nv)
5397 {
5398 	nvlist_t		*nvl = NULL, *nvls;
5399 	void			*nvlpacked = NULL;
5400 	struct pf_kstate	*s = NULL;
5401 	int			 error = 0;
5402 	uint64_t		 id, creatorid;
5403 
5404 #define ERROUT(x)	ERROUT_FUNCTION(errout, x)
5405 
5406 	if (nv->len > pf_ioctl_maxcount)
5407 		ERROUT(ENOMEM);
5408 
5409 	nvlpacked = malloc(nv->len, M_NVLIST, M_WAITOK);
5410 	if (nvlpacked == NULL)
5411 		ERROUT(ENOMEM);
5412 
5413 	error = copyin(nv->data, nvlpacked, nv->len);
5414 	if (error)
5415 		ERROUT(error);
5416 
5417 	nvl = nvlist_unpack(nvlpacked, nv->len, 0);
5418 	if (nvl == NULL)
5419 		ERROUT(EBADMSG);
5420 
5421 	PFNV_CHK(pf_nvuint64(nvl, "id", &id));
5422 	PFNV_CHK(pf_nvuint64(nvl, "creatorid", &creatorid));
5423 
5424 	s = pf_find_state_byid(id, creatorid);
5425 	if (s == NULL)
5426 		ERROUT(ENOENT);
5427 
5428 	free(nvlpacked, M_NVLIST);
5429 	nvlpacked = NULL;
5430 	nvlist_destroy(nvl);
5431 	nvl = nvlist_create(0);
5432 	if (nvl == NULL)
5433 		ERROUT(ENOMEM);
5434 
5435 	nvls = pf_state_to_nvstate(s);
5436 	if (nvls == NULL)
5437 		ERROUT(ENOMEM);
5438 
5439 	nvlist_add_nvlist(nvl, "state", nvls);
5440 	nvlist_destroy(nvls);
5441 
5442 	nvlpacked = nvlist_pack(nvl, &nv->len);
5443 	if (nvlpacked == NULL)
5444 		ERROUT(ENOMEM);
5445 
5446 	if (nv->size == 0)
5447 		ERROUT(0);
5448 	else if (nv->size < nv->len)
5449 		ERROUT(ENOSPC);
5450 
5451 	error = copyout(nvlpacked, nv->data, nv->len);
5452 
5453 #undef ERROUT
5454 errout:
5455 	if (s != NULL)
5456 		PF_STATE_UNLOCK(s);
5457 	free(nvlpacked, M_NVLIST);
5458 	nvlist_destroy(nvl);
5459 	return (error);
5460 }
5461 
5462 /*
5463  * XXX - Check for version missmatch!!!
5464  */
5465 
5466 /*
5467  * Duplicate pfctl -Fa operation to get rid of as much as we can.
5468  */
5469 static int
5470 shutdown_pf(void)
5471 {
5472 	int error = 0;
5473 	u_int32_t t[5];
5474 	char nn = '\0';
5475 
5476 	do {
5477 		if ((error = pf_begin_rules(&t[0], PF_RULESET_SCRUB, &nn))
5478 		    != 0) {
5479 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: SCRUB\n"));
5480 			break;
5481 		}
5482 		if ((error = pf_begin_rules(&t[1], PF_RULESET_FILTER, &nn))
5483 		    != 0) {
5484 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: FILTER\n"));
5485 			break;		/* XXX: rollback? */
5486 		}
5487 		if ((error = pf_begin_rules(&t[2], PF_RULESET_NAT, &nn))
5488 		    != 0) {
5489 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: NAT\n"));
5490 			break;		/* XXX: rollback? */
5491 		}
5492 		if ((error = pf_begin_rules(&t[3], PF_RULESET_BINAT, &nn))
5493 		    != 0) {
5494 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: BINAT\n"));
5495 			break;		/* XXX: rollback? */
5496 		}
5497 		if ((error = pf_begin_rules(&t[4], PF_RULESET_RDR, &nn))
5498 		    != 0) {
5499 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: RDR\n"));
5500 			break;		/* XXX: rollback? */
5501 		}
5502 
5503 		/* XXX: these should always succeed here */
5504 		pf_commit_rules(t[0], PF_RULESET_SCRUB, &nn);
5505 		pf_commit_rules(t[1], PF_RULESET_FILTER, &nn);
5506 		pf_commit_rules(t[2], PF_RULESET_NAT, &nn);
5507 		pf_commit_rules(t[3], PF_RULESET_BINAT, &nn);
5508 		pf_commit_rules(t[4], PF_RULESET_RDR, &nn);
5509 
5510 		if ((error = pf_clear_tables()) != 0)
5511 			break;
5512 
5513 #ifdef ALTQ
5514 		if ((error = pf_begin_altq(&t[0])) != 0) {
5515 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: ALTQ\n"));
5516 			break;
5517 		}
5518 		pf_commit_altq(t[0]);
5519 #endif
5520 
5521 		pf_clear_all_states();
5522 
5523 		pf_clear_srcnodes(NULL);
5524 
5525 		/* status does not use malloced mem so no need to cleanup */
5526 		/* fingerprints and interfaces have their own cleanup code */
5527 	} while(0);
5528 
5529 	return (error);
5530 }
5531 
5532 static pfil_return_t
5533 pf_check_return(int chk, struct mbuf **m)
5534 {
5535 
5536 	switch (chk) {
5537 	case PF_PASS:
5538 		if (*m == NULL)
5539 			return (PFIL_CONSUMED);
5540 		else
5541 			return (PFIL_PASS);
5542 		break;
5543 	default:
5544 		if (*m != NULL) {
5545 			m_freem(*m);
5546 			*m = NULL;
5547 		}
5548 		return (PFIL_DROPPED);
5549 	}
5550 }
5551 
5552 #ifdef INET
5553 static pfil_return_t
5554 pf_check_in(struct mbuf **m, struct ifnet *ifp, int flags,
5555     void *ruleset __unused, struct inpcb *inp)
5556 {
5557 	int chk;
5558 
5559 	chk = pf_test(PF_IN, flags, ifp, m, inp);
5560 
5561 	return (pf_check_return(chk, m));
5562 }
5563 
5564 static pfil_return_t
5565 pf_check_out(struct mbuf **m, struct ifnet *ifp, int flags,
5566     void *ruleset __unused,  struct inpcb *inp)
5567 {
5568 	int chk;
5569 
5570 	chk = pf_test(PF_OUT, flags, ifp, m, inp);
5571 
5572 	return (pf_check_return(chk, m));
5573 }
5574 #endif
5575 
5576 #ifdef INET6
5577 static pfil_return_t
5578 pf_check6_in(struct mbuf **m, struct ifnet *ifp, int flags,
5579     void *ruleset __unused,  struct inpcb *inp)
5580 {
5581 	int chk;
5582 
5583 	/*
5584 	 * In case of loopback traffic IPv6 uses the real interface in
5585 	 * order to support scoped addresses. In order to support stateful
5586 	 * filtering we have change this to lo0 as it is the case in IPv4.
5587 	 */
5588 	CURVNET_SET(ifp->if_vnet);
5589 	chk = pf_test6(PF_IN, flags, (*m)->m_flags & M_LOOP ? V_loif : ifp, m, inp);
5590 	CURVNET_RESTORE();
5591 
5592 	return (pf_check_return(chk, m));
5593 }
5594 
5595 static pfil_return_t
5596 pf_check6_out(struct mbuf **m, struct ifnet *ifp, int flags,
5597     void *ruleset __unused,  struct inpcb *inp)
5598 {
5599 	int chk;
5600 
5601 	CURVNET_SET(ifp->if_vnet);
5602 	chk = pf_test6(PF_OUT, flags, ifp, m, inp);
5603 	CURVNET_RESTORE();
5604 
5605 	return (pf_check_return(chk, m));
5606 }
5607 #endif /* INET6 */
5608 
5609 #ifdef INET
5610 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip4_in_hook);
5611 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip4_out_hook);
5612 #define	V_pf_ip4_in_hook	VNET(pf_ip4_in_hook)
5613 #define	V_pf_ip4_out_hook	VNET(pf_ip4_out_hook)
5614 #endif
5615 #ifdef INET6
5616 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip6_in_hook);
5617 VNET_DEFINE_STATIC(pfil_hook_t, pf_ip6_out_hook);
5618 #define	V_pf_ip6_in_hook	VNET(pf_ip6_in_hook)
5619 #define	V_pf_ip6_out_hook	VNET(pf_ip6_out_hook)
5620 #endif
5621 
5622 static void
5623 hook_pf(void)
5624 {
5625 	struct pfil_hook_args pha;
5626 	struct pfil_link_args pla;
5627 	int ret __diagused;
5628 
5629 	if (V_pf_pfil_hooked)
5630 		return;
5631 
5632 	pha.pa_version = PFIL_VERSION;
5633 	pha.pa_modname = "pf";
5634 	pha.pa_ruleset = NULL;
5635 
5636 	pla.pa_version = PFIL_VERSION;
5637 
5638 #ifdef INET
5639 	pha.pa_type = PFIL_TYPE_IP4;
5640 	pha.pa_func = pf_check_in;
5641 	pha.pa_flags = PFIL_IN;
5642 	pha.pa_rulname = "default-in";
5643 	V_pf_ip4_in_hook = pfil_add_hook(&pha);
5644 	pla.pa_flags = PFIL_IN | PFIL_HEADPTR | PFIL_HOOKPTR;
5645 	pla.pa_head = V_inet_pfil_head;
5646 	pla.pa_hook = V_pf_ip4_in_hook;
5647 	ret = pfil_link(&pla);
5648 	MPASS(ret == 0);
5649 	pha.pa_func = pf_check_out;
5650 	pha.pa_flags = PFIL_OUT;
5651 	pha.pa_rulname = "default-out";
5652 	V_pf_ip4_out_hook = pfil_add_hook(&pha);
5653 	pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
5654 	pla.pa_head = V_inet_pfil_head;
5655 	pla.pa_hook = V_pf_ip4_out_hook;
5656 	ret = pfil_link(&pla);
5657 	MPASS(ret == 0);
5658 #endif
5659 #ifdef INET6
5660 	pha.pa_type = PFIL_TYPE_IP6;
5661 	pha.pa_func = pf_check6_in;
5662 	pha.pa_flags = PFIL_IN;
5663 	pha.pa_rulname = "default-in6";
5664 	V_pf_ip6_in_hook = pfil_add_hook(&pha);
5665 	pla.pa_flags = PFIL_IN | PFIL_HEADPTR | PFIL_HOOKPTR;
5666 	pla.pa_head = V_inet6_pfil_head;
5667 	pla.pa_hook = V_pf_ip6_in_hook;
5668 	ret = pfil_link(&pla);
5669 	MPASS(ret == 0);
5670 	pha.pa_func = pf_check6_out;
5671 	pha.pa_rulname = "default-out6";
5672 	pha.pa_flags = PFIL_OUT;
5673 	V_pf_ip6_out_hook = pfil_add_hook(&pha);
5674 	pla.pa_flags = PFIL_OUT | PFIL_HEADPTR | PFIL_HOOKPTR;
5675 	pla.pa_head = V_inet6_pfil_head;
5676 	pla.pa_hook = V_pf_ip6_out_hook;
5677 	ret = pfil_link(&pla);
5678 	MPASS(ret == 0);
5679 #endif
5680 
5681 	V_pf_pfil_hooked = 1;
5682 }
5683 
5684 static void
5685 dehook_pf(void)
5686 {
5687 
5688 	if (V_pf_pfil_hooked == 0)
5689 		return;
5690 
5691 #ifdef INET
5692 	pfil_remove_hook(V_pf_ip4_in_hook);
5693 	pfil_remove_hook(V_pf_ip4_out_hook);
5694 #endif
5695 #ifdef INET6
5696 	pfil_remove_hook(V_pf_ip6_in_hook);
5697 	pfil_remove_hook(V_pf_ip6_out_hook);
5698 #endif
5699 
5700 	V_pf_pfil_hooked = 0;
5701 }
5702 
5703 static void
5704 pf_load_vnet(void)
5705 {
5706 	V_pf_tag_z = uma_zcreate("pf tags", sizeof(struct pf_tagname),
5707 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
5708 
5709 	pf_init_tagset(&V_pf_tags, &pf_rule_tag_hashsize,
5710 	    PF_RULE_TAG_HASH_SIZE_DEFAULT);
5711 #ifdef ALTQ
5712 	pf_init_tagset(&V_pf_qids, &pf_queue_tag_hashsize,
5713 	    PF_QUEUE_TAG_HASH_SIZE_DEFAULT);
5714 #endif
5715 
5716 	pfattach_vnet();
5717 	V_pf_vnet_active = 1;
5718 }
5719 
5720 static int
5721 pf_load(void)
5722 {
5723 	int error;
5724 
5725 	rm_init_flags(&pf_rules_lock, "pf rulesets", RM_RECURSE);
5726 	sx_init(&pf_ioctl_lock, "pf ioctl");
5727 	sx_init(&pf_end_lock, "pf end thread");
5728 
5729 	pf_mtag_initialize();
5730 
5731 	pf_dev = make_dev(&pf_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600, PF_NAME);
5732 	if (pf_dev == NULL)
5733 		return (ENOMEM);
5734 
5735 	pf_end_threads = 0;
5736 	error = kproc_create(pf_purge_thread, NULL, &pf_purge_proc, 0, 0, "pf purge");
5737 	if (error != 0)
5738 		return (error);
5739 
5740 	pfi_initialize();
5741 
5742 	return (0);
5743 }
5744 
5745 static void
5746 pf_unload_vnet(void)
5747 {
5748 	int ret;
5749 
5750 	V_pf_vnet_active = 0;
5751 	V_pf_status.running = 0;
5752 	dehook_pf();
5753 
5754 	PF_RULES_WLOCK();
5755 	pf_syncookies_cleanup();
5756 	shutdown_pf();
5757 	PF_RULES_WUNLOCK();
5758 
5759 	ret = swi_remove(V_pf_swi_cookie);
5760 	MPASS(ret == 0);
5761 	ret = intr_event_destroy(V_pf_swi_ie);
5762 	MPASS(ret == 0);
5763 
5764 	pf_unload_vnet_purge();
5765 
5766 	pf_normalize_cleanup();
5767 	PF_RULES_WLOCK();
5768 	pfi_cleanup_vnet();
5769 	PF_RULES_WUNLOCK();
5770 	pfr_cleanup();
5771 	pf_osfp_flush();
5772 	pf_cleanup();
5773 	if (IS_DEFAULT_VNET(curvnet))
5774 		pf_mtag_cleanup();
5775 
5776 	pf_cleanup_tagset(&V_pf_tags);
5777 #ifdef ALTQ
5778 	pf_cleanup_tagset(&V_pf_qids);
5779 #endif
5780 	uma_zdestroy(V_pf_tag_z);
5781 
5782 #ifdef PF_WANT_32_TO_64_COUNTER
5783 	PF_RULES_WLOCK();
5784 	LIST_REMOVE(V_pf_kifmarker, pfik_allkiflist);
5785 
5786 	MPASS(LIST_EMPTY(&V_pf_allkiflist));
5787 	MPASS(V_pf_allkifcount == 0);
5788 
5789 	LIST_REMOVE(&V_pf_default_rule, allrulelist);
5790 	V_pf_allrulecount--;
5791 	LIST_REMOVE(V_pf_rulemarker, allrulelist);
5792 
5793 	/*
5794 	 * There are known pf rule leaks when running the test suite.
5795 	 */
5796 #ifdef notyet
5797 	MPASS(LIST_EMPTY(&V_pf_allrulelist));
5798 	MPASS(V_pf_allrulecount == 0);
5799 #endif
5800 
5801 	PF_RULES_WUNLOCK();
5802 
5803 	free(V_pf_kifmarker, PFI_MTYPE);
5804 	free(V_pf_rulemarker, M_PFRULE);
5805 #endif
5806 
5807 	/* Free counters last as we updated them during shutdown. */
5808 	pf_counter_u64_deinit(&V_pf_default_rule.evaluations);
5809 	for (int i = 0; i < 2; i++) {
5810 		pf_counter_u64_deinit(&V_pf_default_rule.packets[i]);
5811 		pf_counter_u64_deinit(&V_pf_default_rule.bytes[i]);
5812 	}
5813 	counter_u64_free(V_pf_default_rule.states_cur);
5814 	counter_u64_free(V_pf_default_rule.states_tot);
5815 	counter_u64_free(V_pf_default_rule.src_nodes);
5816 
5817 	for (int i = 0; i < PFRES_MAX; i++)
5818 		counter_u64_free(V_pf_status.counters[i]);
5819 	for (int i = 0; i < KLCNT_MAX; i++)
5820 		counter_u64_free(V_pf_status.lcounters[i]);
5821 	for (int i = 0; i < FCNT_MAX; i++)
5822 		pf_counter_u64_deinit(&V_pf_status.fcounters[i]);
5823 	for (int i = 0; i < SCNT_MAX; i++)
5824 		counter_u64_free(V_pf_status.scounters[i]);
5825 }
5826 
5827 static void
5828 pf_unload(void)
5829 {
5830 
5831 	sx_xlock(&pf_end_lock);
5832 	pf_end_threads = 1;
5833 	while (pf_end_threads < 2) {
5834 		wakeup_one(pf_purge_thread);
5835 		sx_sleep(pf_purge_proc, &pf_end_lock, 0, "pftmo", 0);
5836 	}
5837 	sx_xunlock(&pf_end_lock);
5838 
5839 	if (pf_dev != NULL)
5840 		destroy_dev(pf_dev);
5841 
5842 	pfi_cleanup();
5843 
5844 	rm_destroy(&pf_rules_lock);
5845 	sx_destroy(&pf_ioctl_lock);
5846 	sx_destroy(&pf_end_lock);
5847 }
5848 
5849 static void
5850 vnet_pf_init(void *unused __unused)
5851 {
5852 
5853 	pf_load_vnet();
5854 }
5855 VNET_SYSINIT(vnet_pf_init, SI_SUB_PROTO_FIREWALL, SI_ORDER_THIRD,
5856     vnet_pf_init, NULL);
5857 
5858 static void
5859 vnet_pf_uninit(const void *unused __unused)
5860 {
5861 
5862 	pf_unload_vnet();
5863 }
5864 SYSUNINIT(pf_unload, SI_SUB_PROTO_FIREWALL, SI_ORDER_SECOND, pf_unload, NULL);
5865 VNET_SYSUNINIT(vnet_pf_uninit, SI_SUB_PROTO_FIREWALL, SI_ORDER_THIRD,
5866     vnet_pf_uninit, NULL);
5867 
5868 static int
5869 pf_modevent(module_t mod, int type, void *data)
5870 {
5871 	int error = 0;
5872 
5873 	switch(type) {
5874 	case MOD_LOAD:
5875 		error = pf_load();
5876 		break;
5877 	case MOD_UNLOAD:
5878 		/* Handled in SYSUNINIT(pf_unload) to ensure it's done after
5879 		 * the vnet_pf_uninit()s */
5880 		break;
5881 	default:
5882 		error = EINVAL;
5883 		break;
5884 	}
5885 
5886 	return (error);
5887 }
5888 
5889 static moduledata_t pf_mod = {
5890 	"pf",
5891 	pf_modevent,
5892 	0
5893 };
5894 
5895 DECLARE_MODULE(pf, pf_mod, SI_SUB_PROTO_FIREWALL, SI_ORDER_SECOND);
5896 MODULE_VERSION(pf, PF_MODVER);
5897