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