xref: /freebsd/sys/netpfil/pf/pf_ioctl.c (revision 2da0fcde21e0b90384f61fd50b87ea7dbd820233)
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/bus.h>
50 #include <sys/conf.h>
51 #include <sys/endian.h>
52 #include <sys/fcntl.h>
53 #include <sys/filio.h>
54 #include <sys/interrupt.h>
55 #include <sys/jail.h>
56 #include <sys/kernel.h>
57 #include <sys/kthread.h>
58 #include <sys/lock.h>
59 #include <sys/mbuf.h>
60 #include <sys/module.h>
61 #include <sys/proc.h>
62 #include <sys/smp.h>
63 #include <sys/socket.h>
64 #include <sys/sysctl.h>
65 #include <sys/md5.h>
66 #include <sys/ucred.h>
67 
68 #include <net/if.h>
69 #include <net/if_var.h>
70 #include <net/vnet.h>
71 #include <net/route.h>
72 #include <net/pfil.h>
73 #include <net/pfvar.h>
74 #include <net/if_pfsync.h>
75 #include <net/if_pflog.h>
76 
77 #include <netinet/in.h>
78 #include <netinet/ip.h>
79 #include <netinet/ip_var.h>
80 #include <netinet6/ip6_var.h>
81 #include <netinet/ip_icmp.h>
82 
83 #ifdef INET6
84 #include <netinet/ip6.h>
85 #endif /* INET6 */
86 
87 #ifdef ALTQ
88 #include <net/altq/altq.h>
89 #endif
90 
91 static struct pf_pool	*pf_get_pool(char *, u_int32_t, u_int8_t, u_int32_t,
92 			    u_int8_t, u_int8_t, u_int8_t);
93 
94 static void		 pf_mv_pool(struct pf_palist *, struct pf_palist *);
95 static void		 pf_empty_pool(struct pf_palist *);
96 static int		 pfioctl(struct cdev *, u_long, caddr_t, int,
97 			    struct thread *);
98 #ifdef ALTQ
99 static int		 pf_begin_altq(u_int32_t *);
100 static int		 pf_rollback_altq(u_int32_t);
101 static int		 pf_commit_altq(u_int32_t);
102 static int		 pf_enable_altq(struct pf_altq *);
103 static int		 pf_disable_altq(struct pf_altq *);
104 static u_int32_t	 pf_qname2qid(char *);
105 static void		 pf_qid_unref(u_int32_t);
106 #endif /* ALTQ */
107 static int		 pf_begin_rules(u_int32_t *, int, const char *);
108 static int		 pf_rollback_rules(u_int32_t, int, char *);
109 static int		 pf_setup_pfsync_matching(struct pf_ruleset *);
110 static void		 pf_hash_rule(MD5_CTX *, struct pf_rule *);
111 static void		 pf_hash_rule_addr(MD5_CTX *, struct pf_rule_addr *);
112 static int		 pf_commit_rules(u_int32_t, int, char *);
113 static int		 pf_addr_setup(struct pf_ruleset *,
114 			    struct pf_addr_wrap *, sa_family_t);
115 static void		 pf_addr_copyout(struct pf_addr_wrap *);
116 
117 VNET_DEFINE(struct pf_rule,	pf_default_rule);
118 
119 #ifdef ALTQ
120 static VNET_DEFINE(int,		pf_altq_running);
121 #define	V_pf_altq_running	VNET(pf_altq_running)
122 #endif
123 
124 #define	TAGID_MAX	 50000
125 struct pf_tagname {
126 	TAILQ_ENTRY(pf_tagname)	entries;
127 	char			name[PF_TAG_NAME_SIZE];
128 	uint16_t		tag;
129 	int			ref;
130 };
131 
132 TAILQ_HEAD(pf_tags, pf_tagname);
133 #define	V_pf_tags		VNET(pf_tags)
134 VNET_DEFINE(struct pf_tags, pf_tags);
135 #define	V_pf_qids		VNET(pf_qids)
136 VNET_DEFINE(struct pf_tags, pf_qids);
137 static MALLOC_DEFINE(M_PFTAG, "pf_tag", "pf(4) tag names");
138 static MALLOC_DEFINE(M_PFALTQ, "pf_altq", "pf(4) altq configuration db");
139 static MALLOC_DEFINE(M_PFRULE, "pf_rule", "pf(4) rules");
140 
141 #if (PF_QNAME_SIZE != PF_TAG_NAME_SIZE)
142 #error PF_QNAME_SIZE must be equal to PF_TAG_NAME_SIZE
143 #endif
144 
145 static u_int16_t	 tagname2tag(struct pf_tags *, char *);
146 static u_int16_t	 pf_tagname2tag(char *);
147 static void		 tag_unref(struct pf_tags *, u_int16_t);
148 
149 #define DPFPRINTF(n, x) if (V_pf_status.debug >= (n)) printf x
150 
151 struct cdev *pf_dev;
152 
153 /*
154  * XXX - These are new and need to be checked when moveing to a new version
155  */
156 static void		 pf_clear_states(void);
157 static int		 pf_clear_tables(void);
158 static void		 pf_clear_srcnodes(struct pf_src_node *);
159 static void		 pf_kill_srcnodes(struct pfioc_src_node_kill *);
160 static void		 pf_tbladdr_copyout(struct pf_addr_wrap *);
161 
162 /*
163  * Wrapper functions for pfil(9) hooks
164  */
165 #ifdef INET
166 static int pf_check_in(void *arg, struct mbuf **m, struct ifnet *ifp,
167     int dir, int flags, struct inpcb *inp);
168 static int pf_check_out(void *arg, struct mbuf **m, struct ifnet *ifp,
169     int dir, int flags, struct inpcb *inp);
170 #endif
171 #ifdef INET6
172 static int pf_check6_in(void *arg, struct mbuf **m, struct ifnet *ifp,
173     int dir, int flags, struct inpcb *inp);
174 static int pf_check6_out(void *arg, struct mbuf **m, struct ifnet *ifp,
175     int dir, int flags, struct inpcb *inp);
176 #endif
177 
178 static int		hook_pf(void);
179 static int		dehook_pf(void);
180 static int		shutdown_pf(void);
181 static int		pf_load(void);
182 static void		pf_unload(void);
183 
184 static struct cdevsw pf_cdevsw = {
185 	.d_ioctl =	pfioctl,
186 	.d_name =	PF_NAME,
187 	.d_version =	D_VERSION,
188 };
189 
190 static volatile VNET_DEFINE(int, pf_pfil_hooked);
191 #define V_pf_pfil_hooked	VNET(pf_pfil_hooked)
192 
193 /*
194  * We need a flag that is neither hooked nor running to know when
195  * the VNET is "valid".  We primarily need this to control (global)
196  * external event, e.g., eventhandlers.
197  */
198 VNET_DEFINE(int, pf_vnet_active);
199 #define V_pf_vnet_active	VNET(pf_vnet_active)
200 
201 int pf_end_threads;
202 struct proc *pf_purge_proc;
203 
204 struct rmlock			pf_rules_lock;
205 struct sx			pf_ioctl_lock;
206 struct sx			pf_end_lock;
207 
208 /* pfsync */
209 pfsync_state_import_t 		*pfsync_state_import_ptr = NULL;
210 pfsync_insert_state_t		*pfsync_insert_state_ptr = NULL;
211 pfsync_update_state_t		*pfsync_update_state_ptr = NULL;
212 pfsync_delete_state_t		*pfsync_delete_state_ptr = NULL;
213 pfsync_clear_states_t		*pfsync_clear_states_ptr = NULL;
214 pfsync_defer_t			*pfsync_defer_ptr = NULL;
215 /* pflog */
216 pflog_packet_t			*pflog_packet_ptr = NULL;
217 
218 extern u_long	pf_ioctl_maxcount;
219 
220 static void
221 pfattach_vnet(void)
222 {
223 	u_int32_t *my_timeout = V_pf_default_rule.timeout;
224 
225 	pf_initialize();
226 	pfr_initialize();
227 	pfi_initialize_vnet();
228 	pf_normalize_init();
229 
230 	V_pf_limits[PF_LIMIT_STATES].limit = PFSTATE_HIWAT;
231 	V_pf_limits[PF_LIMIT_SRC_NODES].limit = PFSNODE_HIWAT;
232 
233 	RB_INIT(&V_pf_anchors);
234 	pf_init_ruleset(&pf_main_ruleset);
235 
236 	/* default rule should never be garbage collected */
237 	V_pf_default_rule.entries.tqe_prev = &V_pf_default_rule.entries.tqe_next;
238 #ifdef PF_DEFAULT_TO_DROP
239 	V_pf_default_rule.action = PF_DROP;
240 #else
241 	V_pf_default_rule.action = PF_PASS;
242 #endif
243 	V_pf_default_rule.nr = -1;
244 	V_pf_default_rule.rtableid = -1;
245 
246 	V_pf_default_rule.states_cur = counter_u64_alloc(M_WAITOK);
247 	V_pf_default_rule.states_tot = counter_u64_alloc(M_WAITOK);
248 	V_pf_default_rule.src_nodes = counter_u64_alloc(M_WAITOK);
249 
250 	/* initialize default timeouts */
251 	my_timeout[PFTM_TCP_FIRST_PACKET] = PFTM_TCP_FIRST_PACKET_VAL;
252 	my_timeout[PFTM_TCP_OPENING] = PFTM_TCP_OPENING_VAL;
253 	my_timeout[PFTM_TCP_ESTABLISHED] = PFTM_TCP_ESTABLISHED_VAL;
254 	my_timeout[PFTM_TCP_CLOSING] = PFTM_TCP_CLOSING_VAL;
255 	my_timeout[PFTM_TCP_FIN_WAIT] = PFTM_TCP_FIN_WAIT_VAL;
256 	my_timeout[PFTM_TCP_CLOSED] = PFTM_TCP_CLOSED_VAL;
257 	my_timeout[PFTM_UDP_FIRST_PACKET] = PFTM_UDP_FIRST_PACKET_VAL;
258 	my_timeout[PFTM_UDP_SINGLE] = PFTM_UDP_SINGLE_VAL;
259 	my_timeout[PFTM_UDP_MULTIPLE] = PFTM_UDP_MULTIPLE_VAL;
260 	my_timeout[PFTM_ICMP_FIRST_PACKET] = PFTM_ICMP_FIRST_PACKET_VAL;
261 	my_timeout[PFTM_ICMP_ERROR_REPLY] = PFTM_ICMP_ERROR_REPLY_VAL;
262 	my_timeout[PFTM_OTHER_FIRST_PACKET] = PFTM_OTHER_FIRST_PACKET_VAL;
263 	my_timeout[PFTM_OTHER_SINGLE] = PFTM_OTHER_SINGLE_VAL;
264 	my_timeout[PFTM_OTHER_MULTIPLE] = PFTM_OTHER_MULTIPLE_VAL;
265 	my_timeout[PFTM_FRAG] = PFTM_FRAG_VAL;
266 	my_timeout[PFTM_INTERVAL] = PFTM_INTERVAL_VAL;
267 	my_timeout[PFTM_SRC_NODE] = PFTM_SRC_NODE_VAL;
268 	my_timeout[PFTM_TS_DIFF] = PFTM_TS_DIFF_VAL;
269 	my_timeout[PFTM_ADAPTIVE_START] = PFSTATE_ADAPT_START;
270 	my_timeout[PFTM_ADAPTIVE_END] = PFSTATE_ADAPT_END;
271 
272 	bzero(&V_pf_status, sizeof(V_pf_status));
273 	V_pf_status.debug = PF_DEBUG_URGENT;
274 
275 	V_pf_pfil_hooked = 0;
276 
277 	/* XXX do our best to avoid a conflict */
278 	V_pf_status.hostid = arc4random();
279 
280 	for (int i = 0; i < PFRES_MAX; i++)
281 		V_pf_status.counters[i] = counter_u64_alloc(M_WAITOK);
282 	for (int i = 0; i < LCNT_MAX; i++)
283 		V_pf_status.lcounters[i] = counter_u64_alloc(M_WAITOK);
284 	for (int i = 0; i < FCNT_MAX; i++)
285 		V_pf_status.fcounters[i] = counter_u64_alloc(M_WAITOK);
286 	for (int i = 0; i < SCNT_MAX; i++)
287 		V_pf_status.scounters[i] = counter_u64_alloc(M_WAITOK);
288 
289 	if (swi_add(NULL, "pf send", pf_intr, curvnet, SWI_NET,
290 	    INTR_MPSAFE, &V_pf_swi_cookie) != 0)
291 		/* XXXGL: leaked all above. */
292 		return;
293 }
294 
295 
296 static struct pf_pool *
297 pf_get_pool(char *anchor, u_int32_t ticket, u_int8_t rule_action,
298     u_int32_t rule_number, u_int8_t r_last, u_int8_t active,
299     u_int8_t check_ticket)
300 {
301 	struct pf_ruleset	*ruleset;
302 	struct pf_rule		*rule;
303 	int			 rs_num;
304 
305 	ruleset = pf_find_ruleset(anchor);
306 	if (ruleset == NULL)
307 		return (NULL);
308 	rs_num = pf_get_ruleset_number(rule_action);
309 	if (rs_num >= PF_RULESET_MAX)
310 		return (NULL);
311 	if (active) {
312 		if (check_ticket && ticket !=
313 		    ruleset->rules[rs_num].active.ticket)
314 			return (NULL);
315 		if (r_last)
316 			rule = TAILQ_LAST(ruleset->rules[rs_num].active.ptr,
317 			    pf_rulequeue);
318 		else
319 			rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
320 	} else {
321 		if (check_ticket && ticket !=
322 		    ruleset->rules[rs_num].inactive.ticket)
323 			return (NULL);
324 		if (r_last)
325 			rule = TAILQ_LAST(ruleset->rules[rs_num].inactive.ptr,
326 			    pf_rulequeue);
327 		else
328 			rule = TAILQ_FIRST(ruleset->rules[rs_num].inactive.ptr);
329 	}
330 	if (!r_last) {
331 		while ((rule != NULL) && (rule->nr != rule_number))
332 			rule = TAILQ_NEXT(rule, entries);
333 	}
334 	if (rule == NULL)
335 		return (NULL);
336 
337 	return (&rule->rpool);
338 }
339 
340 static void
341 pf_mv_pool(struct pf_palist *poola, struct pf_palist *poolb)
342 {
343 	struct pf_pooladdr	*mv_pool_pa;
344 
345 	while ((mv_pool_pa = TAILQ_FIRST(poola)) != NULL) {
346 		TAILQ_REMOVE(poola, mv_pool_pa, entries);
347 		TAILQ_INSERT_TAIL(poolb, mv_pool_pa, entries);
348 	}
349 }
350 
351 static void
352 pf_empty_pool(struct pf_palist *poola)
353 {
354 	struct pf_pooladdr *pa;
355 
356 	while ((pa = TAILQ_FIRST(poola)) != NULL) {
357 		switch (pa->addr.type) {
358 		case PF_ADDR_DYNIFTL:
359 			pfi_dynaddr_remove(pa->addr.p.dyn);
360 			break;
361 		case PF_ADDR_TABLE:
362 			/* XXX: this could be unfinished pooladdr on pabuf */
363 			if (pa->addr.p.tbl != NULL)
364 				pfr_detach_table(pa->addr.p.tbl);
365 			break;
366 		}
367 		if (pa->kif)
368 			pfi_kif_unref(pa->kif);
369 		TAILQ_REMOVE(poola, pa, entries);
370 		free(pa, M_PFRULE);
371 	}
372 }
373 
374 static void
375 pf_unlink_rule(struct pf_rulequeue *rulequeue, struct pf_rule *rule)
376 {
377 
378 	PF_RULES_WASSERT();
379 
380 	TAILQ_REMOVE(rulequeue, rule, entries);
381 
382 	PF_UNLNKDRULES_LOCK();
383 	rule->rule_flag |= PFRULE_REFS;
384 	TAILQ_INSERT_TAIL(&V_pf_unlinked_rules, rule, entries);
385 	PF_UNLNKDRULES_UNLOCK();
386 }
387 
388 void
389 pf_free_rule(struct pf_rule *rule)
390 {
391 
392 	PF_RULES_WASSERT();
393 
394 	if (rule->tag)
395 		tag_unref(&V_pf_tags, rule->tag);
396 	if (rule->match_tag)
397 		tag_unref(&V_pf_tags, rule->match_tag);
398 #ifdef ALTQ
399 	if (rule->pqid != rule->qid)
400 		pf_qid_unref(rule->pqid);
401 	pf_qid_unref(rule->qid);
402 #endif
403 	switch (rule->src.addr.type) {
404 	case PF_ADDR_DYNIFTL:
405 		pfi_dynaddr_remove(rule->src.addr.p.dyn);
406 		break;
407 	case PF_ADDR_TABLE:
408 		pfr_detach_table(rule->src.addr.p.tbl);
409 		break;
410 	}
411 	switch (rule->dst.addr.type) {
412 	case PF_ADDR_DYNIFTL:
413 		pfi_dynaddr_remove(rule->dst.addr.p.dyn);
414 		break;
415 	case PF_ADDR_TABLE:
416 		pfr_detach_table(rule->dst.addr.p.tbl);
417 		break;
418 	}
419 	if (rule->overload_tbl)
420 		pfr_detach_table(rule->overload_tbl);
421 	if (rule->kif)
422 		pfi_kif_unref(rule->kif);
423 	pf_anchor_remove(rule);
424 	pf_empty_pool(&rule->rpool.list);
425 	counter_u64_free(rule->states_cur);
426 	counter_u64_free(rule->states_tot);
427 	counter_u64_free(rule->src_nodes);
428 	free(rule, M_PFRULE);
429 }
430 
431 static u_int16_t
432 tagname2tag(struct pf_tags *head, char *tagname)
433 {
434 	struct pf_tagname	*tag, *p = NULL;
435 	u_int16_t		 new_tagid = 1;
436 
437 	PF_RULES_WASSERT();
438 
439 	TAILQ_FOREACH(tag, head, entries)
440 		if (strcmp(tagname, tag->name) == 0) {
441 			tag->ref++;
442 			return (tag->tag);
443 		}
444 
445 	/*
446 	 * to avoid fragmentation, we do a linear search from the beginning
447 	 * and take the first free slot we find. if there is none or the list
448 	 * is empty, append a new entry at the end.
449 	 */
450 
451 	/* new entry */
452 	if (!TAILQ_EMPTY(head))
453 		for (p = TAILQ_FIRST(head); p != NULL &&
454 		    p->tag == new_tagid; p = TAILQ_NEXT(p, entries))
455 			new_tagid = p->tag + 1;
456 
457 	if (new_tagid > TAGID_MAX)
458 		return (0);
459 
460 	/* allocate and fill new struct pf_tagname */
461 	tag = malloc(sizeof(*tag), M_PFTAG, M_NOWAIT|M_ZERO);
462 	if (tag == NULL)
463 		return (0);
464 	strlcpy(tag->name, tagname, sizeof(tag->name));
465 	tag->tag = new_tagid;
466 	tag->ref++;
467 
468 	if (p != NULL)	/* insert new entry before p */
469 		TAILQ_INSERT_BEFORE(p, tag, entries);
470 	else	/* either list empty or no free slot in between */
471 		TAILQ_INSERT_TAIL(head, tag, entries);
472 
473 	return (tag->tag);
474 }
475 
476 static void
477 tag_unref(struct pf_tags *head, u_int16_t tag)
478 {
479 	struct pf_tagname	*p, *next;
480 
481 	PF_RULES_WASSERT();
482 
483 	for (p = TAILQ_FIRST(head); p != NULL; p = next) {
484 		next = TAILQ_NEXT(p, entries);
485 		if (tag == p->tag) {
486 			if (--p->ref == 0) {
487 				TAILQ_REMOVE(head, p, entries);
488 				free(p, M_PFTAG);
489 			}
490 			break;
491 		}
492 	}
493 }
494 
495 static u_int16_t
496 pf_tagname2tag(char *tagname)
497 {
498 	return (tagname2tag(&V_pf_tags, tagname));
499 }
500 
501 #ifdef ALTQ
502 static u_int32_t
503 pf_qname2qid(char *qname)
504 {
505 	return ((u_int32_t)tagname2tag(&V_pf_qids, qname));
506 }
507 
508 static void
509 pf_qid_unref(u_int32_t qid)
510 {
511 	tag_unref(&V_pf_qids, (u_int16_t)qid);
512 }
513 
514 static int
515 pf_begin_altq(u_int32_t *ticket)
516 {
517 	struct pf_altq	*altq;
518 	int		 error = 0;
519 
520 	PF_RULES_WASSERT();
521 
522 	/* Purge the old altq list */
523 	while ((altq = TAILQ_FIRST(V_pf_altqs_inactive)) != NULL) {
524 		TAILQ_REMOVE(V_pf_altqs_inactive, altq, entries);
525 		if (altq->qname[0] == 0 &&
526 		    (altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
527 			/* detach and destroy the discipline */
528 			error = altq_remove(altq);
529 		} else
530 			pf_qid_unref(altq->qid);
531 		free(altq, M_PFALTQ);
532 	}
533 	if (error)
534 		return (error);
535 	*ticket = ++V_ticket_altqs_inactive;
536 	V_altqs_inactive_open = 1;
537 	return (0);
538 }
539 
540 static int
541 pf_rollback_altq(u_int32_t ticket)
542 {
543 	struct pf_altq	*altq;
544 	int		 error = 0;
545 
546 	PF_RULES_WASSERT();
547 
548 	if (!V_altqs_inactive_open || ticket != V_ticket_altqs_inactive)
549 		return (0);
550 	/* Purge the old altq list */
551 	while ((altq = TAILQ_FIRST(V_pf_altqs_inactive)) != NULL) {
552 		TAILQ_REMOVE(V_pf_altqs_inactive, altq, entries);
553 		if (altq->qname[0] == 0 &&
554 		   (altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
555 			/* detach and destroy the discipline */
556 			error = altq_remove(altq);
557 		} else
558 			pf_qid_unref(altq->qid);
559 		free(altq, M_PFALTQ);
560 	}
561 	V_altqs_inactive_open = 0;
562 	return (error);
563 }
564 
565 static int
566 pf_commit_altq(u_int32_t ticket)
567 {
568 	struct pf_altqqueue	*old_altqs;
569 	struct pf_altq		*altq;
570 	int			 err, error = 0;
571 
572 	PF_RULES_WASSERT();
573 
574 	if (!V_altqs_inactive_open || ticket != V_ticket_altqs_inactive)
575 		return (EBUSY);
576 
577 	/* swap altqs, keep the old. */
578 	old_altqs = V_pf_altqs_active;
579 	V_pf_altqs_active = V_pf_altqs_inactive;
580 	V_pf_altqs_inactive = old_altqs;
581 	V_ticket_altqs_active = V_ticket_altqs_inactive;
582 
583 	/* Attach new disciplines */
584 	TAILQ_FOREACH(altq, V_pf_altqs_active, entries) {
585 	if (altq->qname[0] == 0 &&
586 	   (altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
587 			/* attach the discipline */
588 			error = altq_pfattach(altq);
589 			if (error == 0 && V_pf_altq_running)
590 				error = pf_enable_altq(altq);
591 			if (error != 0)
592 				return (error);
593 		}
594 	}
595 
596 	/* Purge the old altq list */
597 	while ((altq = TAILQ_FIRST(V_pf_altqs_inactive)) != NULL) {
598 		TAILQ_REMOVE(V_pf_altqs_inactive, altq, entries);
599 		if (altq->qname[0] == 0 &&
600 		    (altq->local_flags & PFALTQ_FLAG_IF_REMOVED) == 0) {
601 			/* detach and destroy the discipline */
602 			if (V_pf_altq_running)
603 				error = pf_disable_altq(altq);
604 			err = altq_pfdetach(altq);
605 			if (err != 0 && error == 0)
606 				error = err;
607 			err = altq_remove(altq);
608 			if (err != 0 && error == 0)
609 				error = err;
610 		} else
611 			pf_qid_unref(altq->qid);
612 		free(altq, M_PFALTQ);
613 	}
614 
615 	V_altqs_inactive_open = 0;
616 	return (error);
617 }
618 
619 static int
620 pf_enable_altq(struct pf_altq *altq)
621 {
622 	struct ifnet		*ifp;
623 	struct tb_profile	 tb;
624 	int			 error = 0;
625 
626 	if ((ifp = ifunit(altq->ifname)) == NULL)
627 		return (EINVAL);
628 
629 	if (ifp->if_snd.altq_type != ALTQT_NONE)
630 		error = altq_enable(&ifp->if_snd);
631 
632 	/* set tokenbucket regulator */
633 	if (error == 0 && ifp != NULL && ALTQ_IS_ENABLED(&ifp->if_snd)) {
634 		tb.rate = altq->ifbandwidth;
635 		tb.depth = altq->tbrsize;
636 		error = tbr_set(&ifp->if_snd, &tb);
637 	}
638 
639 	return (error);
640 }
641 
642 static int
643 pf_disable_altq(struct pf_altq *altq)
644 {
645 	struct ifnet		*ifp;
646 	struct tb_profile	 tb;
647 	int			 error;
648 
649 	if ((ifp = ifunit(altq->ifname)) == NULL)
650 		return (EINVAL);
651 
652 	/*
653 	 * when the discipline is no longer referenced, it was overridden
654 	 * by a new one.  if so, just return.
655 	 */
656 	if (altq->altq_disc != ifp->if_snd.altq_disc)
657 		return (0);
658 
659 	error = altq_disable(&ifp->if_snd);
660 
661 	if (error == 0) {
662 		/* clear tokenbucket regulator */
663 		tb.rate = 0;
664 		error = tbr_set(&ifp->if_snd, &tb);
665 	}
666 
667 	return (error);
668 }
669 
670 void
671 pf_altq_ifnet_event(struct ifnet *ifp, int remove)
672 {
673 	struct ifnet	*ifp1;
674 	struct pf_altq	*a1, *a2, *a3;
675 	u_int32_t	 ticket;
676 	int		 error = 0;
677 
678 	/* Interrupt userland queue modifications */
679 	if (V_altqs_inactive_open)
680 		pf_rollback_altq(V_ticket_altqs_inactive);
681 
682 	/* Start new altq ruleset */
683 	if (pf_begin_altq(&ticket))
684 		return;
685 
686 	/* Copy the current active set */
687 	TAILQ_FOREACH(a1, V_pf_altqs_active, entries) {
688 		a2 = malloc(sizeof(*a2), M_PFALTQ, M_NOWAIT);
689 		if (a2 == NULL) {
690 			error = ENOMEM;
691 			break;
692 		}
693 		bcopy(a1, a2, sizeof(struct pf_altq));
694 
695 		if (a2->qname[0] != 0) {
696 			if ((a2->qid = pf_qname2qid(a2->qname)) == 0) {
697 				error = EBUSY;
698 				free(a2, M_PFALTQ);
699 				break;
700 			}
701 			a2->altq_disc = NULL;
702 			TAILQ_FOREACH(a3, V_pf_altqs_inactive, entries) {
703 				if (strncmp(a3->ifname, a2->ifname,
704 				    IFNAMSIZ) == 0 && a3->qname[0] == 0) {
705 					a2->altq_disc = a3->altq_disc;
706 					break;
707 				}
708 			}
709 		}
710 		/* Deactivate the interface in question */
711 		a2->local_flags &= ~PFALTQ_FLAG_IF_REMOVED;
712 		if ((ifp1 = ifunit(a2->ifname)) == NULL ||
713 		    (remove && ifp1 == ifp)) {
714 			a2->local_flags |= PFALTQ_FLAG_IF_REMOVED;
715 		} else {
716 			error = altq_add(a2);
717 
718 			if (ticket != V_ticket_altqs_inactive)
719 				error = EBUSY;
720 
721 			if (error) {
722 				free(a2, M_PFALTQ);
723 				break;
724 			}
725 		}
726 
727 		TAILQ_INSERT_TAIL(V_pf_altqs_inactive, a2, entries);
728 	}
729 
730 	if (error != 0)
731 		pf_rollback_altq(ticket);
732 	else
733 		pf_commit_altq(ticket);
734 }
735 #endif /* ALTQ */
736 
737 static int
738 pf_begin_rules(u_int32_t *ticket, int rs_num, const char *anchor)
739 {
740 	struct pf_ruleset	*rs;
741 	struct pf_rule		*rule;
742 
743 	PF_RULES_WASSERT();
744 
745 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
746 		return (EINVAL);
747 	rs = pf_find_or_create_ruleset(anchor);
748 	if (rs == NULL)
749 		return (EINVAL);
750 	while ((rule = TAILQ_FIRST(rs->rules[rs_num].inactive.ptr)) != NULL) {
751 		pf_unlink_rule(rs->rules[rs_num].inactive.ptr, rule);
752 		rs->rules[rs_num].inactive.rcount--;
753 	}
754 	*ticket = ++rs->rules[rs_num].inactive.ticket;
755 	rs->rules[rs_num].inactive.open = 1;
756 	return (0);
757 }
758 
759 static int
760 pf_rollback_rules(u_int32_t ticket, int rs_num, char *anchor)
761 {
762 	struct pf_ruleset	*rs;
763 	struct pf_rule		*rule;
764 
765 	PF_RULES_WASSERT();
766 
767 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
768 		return (EINVAL);
769 	rs = pf_find_ruleset(anchor);
770 	if (rs == NULL || !rs->rules[rs_num].inactive.open ||
771 	    rs->rules[rs_num].inactive.ticket != ticket)
772 		return (0);
773 	while ((rule = TAILQ_FIRST(rs->rules[rs_num].inactive.ptr)) != NULL) {
774 		pf_unlink_rule(rs->rules[rs_num].inactive.ptr, rule);
775 		rs->rules[rs_num].inactive.rcount--;
776 	}
777 	rs->rules[rs_num].inactive.open = 0;
778 	return (0);
779 }
780 
781 #define PF_MD5_UPD(st, elm)						\
782 		MD5Update(ctx, (u_int8_t *) &(st)->elm, sizeof((st)->elm))
783 
784 #define PF_MD5_UPD_STR(st, elm)						\
785 		MD5Update(ctx, (u_int8_t *) (st)->elm, strlen((st)->elm))
786 
787 #define PF_MD5_UPD_HTONL(st, elm, stor) do {				\
788 		(stor) = htonl((st)->elm);				\
789 		MD5Update(ctx, (u_int8_t *) &(stor), sizeof(u_int32_t));\
790 } while (0)
791 
792 #define PF_MD5_UPD_HTONS(st, elm, stor) do {				\
793 		(stor) = htons((st)->elm);				\
794 		MD5Update(ctx, (u_int8_t *) &(stor), sizeof(u_int16_t));\
795 } while (0)
796 
797 static void
798 pf_hash_rule_addr(MD5_CTX *ctx, struct pf_rule_addr *pfr)
799 {
800 	PF_MD5_UPD(pfr, addr.type);
801 	switch (pfr->addr.type) {
802 		case PF_ADDR_DYNIFTL:
803 			PF_MD5_UPD(pfr, addr.v.ifname);
804 			PF_MD5_UPD(pfr, addr.iflags);
805 			break;
806 		case PF_ADDR_TABLE:
807 			PF_MD5_UPD(pfr, addr.v.tblname);
808 			break;
809 		case PF_ADDR_ADDRMASK:
810 			/* XXX ignore af? */
811 			PF_MD5_UPD(pfr, addr.v.a.addr.addr32);
812 			PF_MD5_UPD(pfr, addr.v.a.mask.addr32);
813 			break;
814 	}
815 
816 	PF_MD5_UPD(pfr, port[0]);
817 	PF_MD5_UPD(pfr, port[1]);
818 	PF_MD5_UPD(pfr, neg);
819 	PF_MD5_UPD(pfr, port_op);
820 }
821 
822 static void
823 pf_hash_rule(MD5_CTX *ctx, struct pf_rule *rule)
824 {
825 	u_int16_t x;
826 	u_int32_t y;
827 
828 	pf_hash_rule_addr(ctx, &rule->src);
829 	pf_hash_rule_addr(ctx, &rule->dst);
830 	PF_MD5_UPD_STR(rule, label);
831 	PF_MD5_UPD_STR(rule, ifname);
832 	PF_MD5_UPD_STR(rule, match_tagname);
833 	PF_MD5_UPD_HTONS(rule, match_tag, x); /* dup? */
834 	PF_MD5_UPD_HTONL(rule, os_fingerprint, y);
835 	PF_MD5_UPD_HTONL(rule, prob, y);
836 	PF_MD5_UPD_HTONL(rule, uid.uid[0], y);
837 	PF_MD5_UPD_HTONL(rule, uid.uid[1], y);
838 	PF_MD5_UPD(rule, uid.op);
839 	PF_MD5_UPD_HTONL(rule, gid.gid[0], y);
840 	PF_MD5_UPD_HTONL(rule, gid.gid[1], y);
841 	PF_MD5_UPD(rule, gid.op);
842 	PF_MD5_UPD_HTONL(rule, rule_flag, y);
843 	PF_MD5_UPD(rule, action);
844 	PF_MD5_UPD(rule, direction);
845 	PF_MD5_UPD(rule, af);
846 	PF_MD5_UPD(rule, quick);
847 	PF_MD5_UPD(rule, ifnot);
848 	PF_MD5_UPD(rule, match_tag_not);
849 	PF_MD5_UPD(rule, natpass);
850 	PF_MD5_UPD(rule, keep_state);
851 	PF_MD5_UPD(rule, proto);
852 	PF_MD5_UPD(rule, type);
853 	PF_MD5_UPD(rule, code);
854 	PF_MD5_UPD(rule, flags);
855 	PF_MD5_UPD(rule, flagset);
856 	PF_MD5_UPD(rule, allow_opts);
857 	PF_MD5_UPD(rule, rt);
858 	PF_MD5_UPD(rule, tos);
859 }
860 
861 static int
862 pf_commit_rules(u_int32_t ticket, int rs_num, char *anchor)
863 {
864 	struct pf_ruleset	*rs;
865 	struct pf_rule		*rule, **old_array;
866 	struct pf_rulequeue	*old_rules;
867 	int			 error;
868 	u_int32_t		 old_rcount;
869 
870 	PF_RULES_WASSERT();
871 
872 	if (rs_num < 0 || rs_num >= PF_RULESET_MAX)
873 		return (EINVAL);
874 	rs = pf_find_ruleset(anchor);
875 	if (rs == NULL || !rs->rules[rs_num].inactive.open ||
876 	    ticket != rs->rules[rs_num].inactive.ticket)
877 		return (EBUSY);
878 
879 	/* Calculate checksum for the main ruleset */
880 	if (rs == &pf_main_ruleset) {
881 		error = pf_setup_pfsync_matching(rs);
882 		if (error != 0)
883 			return (error);
884 	}
885 
886 	/* Swap rules, keep the old. */
887 	old_rules = rs->rules[rs_num].active.ptr;
888 	old_rcount = rs->rules[rs_num].active.rcount;
889 	old_array = rs->rules[rs_num].active.ptr_array;
890 
891 	rs->rules[rs_num].active.ptr =
892 	    rs->rules[rs_num].inactive.ptr;
893 	rs->rules[rs_num].active.ptr_array =
894 	    rs->rules[rs_num].inactive.ptr_array;
895 	rs->rules[rs_num].active.rcount =
896 	    rs->rules[rs_num].inactive.rcount;
897 	rs->rules[rs_num].inactive.ptr = old_rules;
898 	rs->rules[rs_num].inactive.ptr_array = old_array;
899 	rs->rules[rs_num].inactive.rcount = old_rcount;
900 
901 	rs->rules[rs_num].active.ticket =
902 	    rs->rules[rs_num].inactive.ticket;
903 	pf_calc_skip_steps(rs->rules[rs_num].active.ptr);
904 
905 
906 	/* Purge the old rule list. */
907 	while ((rule = TAILQ_FIRST(old_rules)) != NULL)
908 		pf_unlink_rule(old_rules, rule);
909 	if (rs->rules[rs_num].inactive.ptr_array)
910 		free(rs->rules[rs_num].inactive.ptr_array, M_TEMP);
911 	rs->rules[rs_num].inactive.ptr_array = NULL;
912 	rs->rules[rs_num].inactive.rcount = 0;
913 	rs->rules[rs_num].inactive.open = 0;
914 	pf_remove_if_empty_ruleset(rs);
915 
916 	return (0);
917 }
918 
919 static int
920 pf_setup_pfsync_matching(struct pf_ruleset *rs)
921 {
922 	MD5_CTX			 ctx;
923 	struct pf_rule		*rule;
924 	int			 rs_cnt;
925 	u_int8_t		 digest[PF_MD5_DIGEST_LENGTH];
926 
927 	MD5Init(&ctx);
928 	for (rs_cnt = 0; rs_cnt < PF_RULESET_MAX; rs_cnt++) {
929 		/* XXX PF_RULESET_SCRUB as well? */
930 		if (rs_cnt == PF_RULESET_SCRUB)
931 			continue;
932 
933 		if (rs->rules[rs_cnt].inactive.ptr_array)
934 			free(rs->rules[rs_cnt].inactive.ptr_array, M_TEMP);
935 		rs->rules[rs_cnt].inactive.ptr_array = NULL;
936 
937 		if (rs->rules[rs_cnt].inactive.rcount) {
938 			rs->rules[rs_cnt].inactive.ptr_array =
939 			    malloc(sizeof(caddr_t) *
940 			    rs->rules[rs_cnt].inactive.rcount,
941 			    M_TEMP, M_NOWAIT);
942 
943 			if (!rs->rules[rs_cnt].inactive.ptr_array)
944 				return (ENOMEM);
945 		}
946 
947 		TAILQ_FOREACH(rule, rs->rules[rs_cnt].inactive.ptr,
948 		    entries) {
949 			pf_hash_rule(&ctx, rule);
950 			(rs->rules[rs_cnt].inactive.ptr_array)[rule->nr] = rule;
951 		}
952 	}
953 
954 	MD5Final(digest, &ctx);
955 	memcpy(V_pf_status.pf_chksum, digest, sizeof(V_pf_status.pf_chksum));
956 	return (0);
957 }
958 
959 static int
960 pf_addr_setup(struct pf_ruleset *ruleset, struct pf_addr_wrap *addr,
961     sa_family_t af)
962 {
963 	int error = 0;
964 
965 	switch (addr->type) {
966 	case PF_ADDR_TABLE:
967 		addr->p.tbl = pfr_attach_table(ruleset, addr->v.tblname);
968 		if (addr->p.tbl == NULL)
969 			error = ENOMEM;
970 		break;
971 	case PF_ADDR_DYNIFTL:
972 		error = pfi_dynaddr_setup(addr, af);
973 		break;
974 	}
975 
976 	return (error);
977 }
978 
979 static void
980 pf_addr_copyout(struct pf_addr_wrap *addr)
981 {
982 
983 	switch (addr->type) {
984 	case PF_ADDR_DYNIFTL:
985 		pfi_dynaddr_copyout(addr);
986 		break;
987 	case PF_ADDR_TABLE:
988 		pf_tbladdr_copyout(addr);
989 		break;
990 	}
991 }
992 
993 static int
994 pfioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
995 {
996 	int			 error = 0;
997 	PF_RULES_RLOCK_TRACKER;
998 
999 	/* XXX keep in sync with switch() below */
1000 	if (securelevel_gt(td->td_ucred, 2))
1001 		switch (cmd) {
1002 		case DIOCGETRULES:
1003 		case DIOCGETRULE:
1004 		case DIOCGETADDRS:
1005 		case DIOCGETADDR:
1006 		case DIOCSETSTATUSIF:
1007 		case DIOCGETSTATUS:
1008 		case DIOCCLRSTATUS:
1009 		case DIOCNATLOOK:
1010 		case DIOCSETDEBUG:
1011 		case DIOCGETSTATES:
1012 		case DIOCGETTIMEOUT:
1013 		case DIOCGETLIMIT:
1014 		case DIOCGETALTQS:
1015 		case DIOCGETALTQ:
1016 		case DIOCGETQSTATS:
1017 		case DIOCGETRULESETS:
1018 		case DIOCGETRULESET:
1019 		case DIOCRGETTABLES:
1020 		case DIOCRGETTSTATS:
1021 		case DIOCRCLRTSTATS:
1022 		case DIOCRCLRADDRS:
1023 		case DIOCRADDADDRS:
1024 		case DIOCRDELADDRS:
1025 		case DIOCRSETADDRS:
1026 		case DIOCRGETADDRS:
1027 		case DIOCRGETASTATS:
1028 		case DIOCRCLRASTATS:
1029 		case DIOCRTSTADDRS:
1030 		case DIOCOSFPGET:
1031 		case DIOCGETSRCNODES:
1032 		case DIOCCLRSRCNODES:
1033 		case DIOCIGETIFACES:
1034 		case DIOCGIFSPEED:
1035 		case DIOCSETIFFLAG:
1036 		case DIOCCLRIFFLAG:
1037 			break;
1038 		case DIOCRCLRTABLES:
1039 		case DIOCRADDTABLES:
1040 		case DIOCRDELTABLES:
1041 		case DIOCRSETTFLAGS:
1042 			if (((struct pfioc_table *)addr)->pfrio_flags &
1043 			    PFR_FLAG_DUMMY)
1044 				break; /* dummy operation ok */
1045 			return (EPERM);
1046 		default:
1047 			return (EPERM);
1048 		}
1049 
1050 	if (!(flags & FWRITE))
1051 		switch (cmd) {
1052 		case DIOCGETRULES:
1053 		case DIOCGETADDRS:
1054 		case DIOCGETADDR:
1055 		case DIOCGETSTATUS:
1056 		case DIOCGETSTATES:
1057 		case DIOCGETTIMEOUT:
1058 		case DIOCGETLIMIT:
1059 		case DIOCGETALTQS:
1060 		case DIOCGETALTQ:
1061 		case DIOCGETQSTATS:
1062 		case DIOCGETRULESETS:
1063 		case DIOCGETRULESET:
1064 		case DIOCNATLOOK:
1065 		case DIOCRGETTABLES:
1066 		case DIOCRGETTSTATS:
1067 		case DIOCRGETADDRS:
1068 		case DIOCRGETASTATS:
1069 		case DIOCRTSTADDRS:
1070 		case DIOCOSFPGET:
1071 		case DIOCGETSRCNODES:
1072 		case DIOCIGETIFACES:
1073 		case DIOCGIFSPEED:
1074 			break;
1075 		case DIOCRCLRTABLES:
1076 		case DIOCRADDTABLES:
1077 		case DIOCRDELTABLES:
1078 		case DIOCRCLRTSTATS:
1079 		case DIOCRCLRADDRS:
1080 		case DIOCRADDADDRS:
1081 		case DIOCRDELADDRS:
1082 		case DIOCRSETADDRS:
1083 		case DIOCRSETTFLAGS:
1084 			if (((struct pfioc_table *)addr)->pfrio_flags &
1085 			    PFR_FLAG_DUMMY) {
1086 				flags |= FWRITE; /* need write lock for dummy */
1087 				break; /* dummy operation ok */
1088 			}
1089 			return (EACCES);
1090 		case DIOCGETRULE:
1091 			if (((struct pfioc_rule *)addr)->action ==
1092 			    PF_GET_CLR_CNTR)
1093 				return (EACCES);
1094 			break;
1095 		default:
1096 			return (EACCES);
1097 		}
1098 
1099 	CURVNET_SET(TD_TO_VNET(td));
1100 
1101 	switch (cmd) {
1102 	case DIOCSTART:
1103 		sx_xlock(&pf_ioctl_lock);
1104 		if (V_pf_status.running)
1105 			error = EEXIST;
1106 		else {
1107 			int cpu;
1108 
1109 			error = hook_pf();
1110 			if (error) {
1111 				DPFPRINTF(PF_DEBUG_MISC,
1112 				    ("pf: pfil registration failed\n"));
1113 				break;
1114 			}
1115 			V_pf_status.running = 1;
1116 			V_pf_status.since = time_second;
1117 
1118 			CPU_FOREACH(cpu)
1119 				V_pf_stateid[cpu] = time_second;
1120 
1121 			DPFPRINTF(PF_DEBUG_MISC, ("pf: started\n"));
1122 		}
1123 		break;
1124 
1125 	case DIOCSTOP:
1126 		sx_xlock(&pf_ioctl_lock);
1127 		if (!V_pf_status.running)
1128 			error = ENOENT;
1129 		else {
1130 			V_pf_status.running = 0;
1131 			error = dehook_pf();
1132 			if (error) {
1133 				V_pf_status.running = 1;
1134 				DPFPRINTF(PF_DEBUG_MISC,
1135 				    ("pf: pfil unregistration failed\n"));
1136 			}
1137 			V_pf_status.since = time_second;
1138 			DPFPRINTF(PF_DEBUG_MISC, ("pf: stopped\n"));
1139 		}
1140 		break;
1141 
1142 	case DIOCADDRULE: {
1143 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
1144 		struct pf_ruleset	*ruleset;
1145 		struct pf_rule		*rule, *tail;
1146 		struct pf_pooladdr	*pa;
1147 		struct pfi_kif		*kif = NULL;
1148 		int			 rs_num;
1149 
1150 		if (pr->rule.return_icmp >> 8 > ICMP_MAXTYPE) {
1151 			error = EINVAL;
1152 			break;
1153 		}
1154 #ifndef INET
1155 		if (pr->rule.af == AF_INET) {
1156 			error = EAFNOSUPPORT;
1157 			break;
1158 		}
1159 #endif /* INET */
1160 #ifndef INET6
1161 		if (pr->rule.af == AF_INET6) {
1162 			error = EAFNOSUPPORT;
1163 			break;
1164 		}
1165 #endif /* INET6 */
1166 
1167 		rule = malloc(sizeof(*rule), M_PFRULE, M_WAITOK);
1168 		bcopy(&pr->rule, rule, sizeof(struct pf_rule));
1169 		if (rule->ifname[0])
1170 			kif = malloc(sizeof(*kif), PFI_MTYPE, M_WAITOK);
1171 		rule->states_cur = counter_u64_alloc(M_WAITOK);
1172 		rule->states_tot = counter_u64_alloc(M_WAITOK);
1173 		rule->src_nodes = counter_u64_alloc(M_WAITOK);
1174 		rule->cuid = td->td_ucred->cr_ruid;
1175 		rule->cpid = td->td_proc ? td->td_proc->p_pid : 0;
1176 		TAILQ_INIT(&rule->rpool.list);
1177 
1178 #define	ERROUT(x)	{ error = (x); goto DIOCADDRULE_error; }
1179 
1180 		PF_RULES_WLOCK();
1181 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
1182 		ruleset = pf_find_ruleset(pr->anchor);
1183 		if (ruleset == NULL)
1184 			ERROUT(EINVAL);
1185 		rs_num = pf_get_ruleset_number(pr->rule.action);
1186 		if (rs_num >= PF_RULESET_MAX)
1187 			ERROUT(EINVAL);
1188 		if (pr->ticket != ruleset->rules[rs_num].inactive.ticket) {
1189 			DPFPRINTF(PF_DEBUG_MISC,
1190 			    ("ticket: %d != [%d]%d\n", pr->ticket, rs_num,
1191 			    ruleset->rules[rs_num].inactive.ticket));
1192 			ERROUT(EBUSY);
1193 		}
1194 		if (pr->pool_ticket != V_ticket_pabuf) {
1195 			DPFPRINTF(PF_DEBUG_MISC,
1196 			    ("pool_ticket: %d != %d\n", pr->pool_ticket,
1197 			    V_ticket_pabuf));
1198 			ERROUT(EBUSY);
1199 		}
1200 
1201 		tail = TAILQ_LAST(ruleset->rules[rs_num].inactive.ptr,
1202 		    pf_rulequeue);
1203 		if (tail)
1204 			rule->nr = tail->nr + 1;
1205 		else
1206 			rule->nr = 0;
1207 		if (rule->ifname[0]) {
1208 			rule->kif = pfi_kif_attach(kif, rule->ifname);
1209 			pfi_kif_ref(rule->kif);
1210 		} else
1211 			rule->kif = NULL;
1212 
1213 		if (rule->rtableid > 0 && rule->rtableid >= rt_numfibs)
1214 			error = EBUSY;
1215 
1216 #ifdef ALTQ
1217 		/* set queue IDs */
1218 		if (rule->qname[0] != 0) {
1219 			if ((rule->qid = pf_qname2qid(rule->qname)) == 0)
1220 				error = EBUSY;
1221 			else if (rule->pqname[0] != 0) {
1222 				if ((rule->pqid =
1223 				    pf_qname2qid(rule->pqname)) == 0)
1224 					error = EBUSY;
1225 			} else
1226 				rule->pqid = rule->qid;
1227 		}
1228 #endif
1229 		if (rule->tagname[0])
1230 			if ((rule->tag = pf_tagname2tag(rule->tagname)) == 0)
1231 				error = EBUSY;
1232 		if (rule->match_tagname[0])
1233 			if ((rule->match_tag =
1234 			    pf_tagname2tag(rule->match_tagname)) == 0)
1235 				error = EBUSY;
1236 		if (rule->rt && !rule->direction)
1237 			error = EINVAL;
1238 		if (!rule->log)
1239 			rule->logif = 0;
1240 		if (rule->logif >= PFLOGIFS_MAX)
1241 			error = EINVAL;
1242 		if (pf_addr_setup(ruleset, &rule->src.addr, rule->af))
1243 			error = ENOMEM;
1244 		if (pf_addr_setup(ruleset, &rule->dst.addr, rule->af))
1245 			error = ENOMEM;
1246 		if (pf_anchor_setup(rule, ruleset, pr->anchor_call))
1247 			error = EINVAL;
1248 		if (rule->scrub_flags & PFSTATE_SETPRIO &&
1249 		    (rule->set_prio[0] > PF_PRIO_MAX ||
1250 		    rule->set_prio[1] > PF_PRIO_MAX))
1251 			error = EINVAL;
1252 		TAILQ_FOREACH(pa, &V_pf_pabuf, entries)
1253 			if (pa->addr.type == PF_ADDR_TABLE) {
1254 				pa->addr.p.tbl = pfr_attach_table(ruleset,
1255 				    pa->addr.v.tblname);
1256 				if (pa->addr.p.tbl == NULL)
1257 					error = ENOMEM;
1258 			}
1259 
1260 		rule->overload_tbl = NULL;
1261 		if (rule->overload_tblname[0]) {
1262 			if ((rule->overload_tbl = pfr_attach_table(ruleset,
1263 			    rule->overload_tblname)) == NULL)
1264 				error = EINVAL;
1265 			else
1266 				rule->overload_tbl->pfrkt_flags |=
1267 				    PFR_TFLAG_ACTIVE;
1268 		}
1269 
1270 		pf_mv_pool(&V_pf_pabuf, &rule->rpool.list);
1271 		if (((((rule->action == PF_NAT) || (rule->action == PF_RDR) ||
1272 		    (rule->action == PF_BINAT)) && rule->anchor == NULL) ||
1273 		    (rule->rt > PF_NOPFROUTE)) &&
1274 		    (TAILQ_FIRST(&rule->rpool.list) == NULL))
1275 			error = EINVAL;
1276 
1277 		if (error) {
1278 			pf_free_rule(rule);
1279 			PF_RULES_WUNLOCK();
1280 			break;
1281 		}
1282 
1283 		rule->rpool.cur = TAILQ_FIRST(&rule->rpool.list);
1284 		rule->evaluations = rule->packets[0] = rule->packets[1] =
1285 		    rule->bytes[0] = rule->bytes[1] = 0;
1286 		TAILQ_INSERT_TAIL(ruleset->rules[rs_num].inactive.ptr,
1287 		    rule, entries);
1288 		ruleset->rules[rs_num].inactive.rcount++;
1289 		PF_RULES_WUNLOCK();
1290 		break;
1291 
1292 #undef ERROUT
1293 DIOCADDRULE_error:
1294 		PF_RULES_WUNLOCK();
1295 		counter_u64_free(rule->states_cur);
1296 		counter_u64_free(rule->states_tot);
1297 		counter_u64_free(rule->src_nodes);
1298 		free(rule, M_PFRULE);
1299 		if (kif)
1300 			free(kif, PFI_MTYPE);
1301 		break;
1302 	}
1303 
1304 	case DIOCGETRULES: {
1305 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
1306 		struct pf_ruleset	*ruleset;
1307 		struct pf_rule		*tail;
1308 		int			 rs_num;
1309 
1310 		PF_RULES_WLOCK();
1311 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
1312 		ruleset = pf_find_ruleset(pr->anchor);
1313 		if (ruleset == NULL) {
1314 			PF_RULES_WUNLOCK();
1315 			error = EINVAL;
1316 			break;
1317 		}
1318 		rs_num = pf_get_ruleset_number(pr->rule.action);
1319 		if (rs_num >= PF_RULESET_MAX) {
1320 			PF_RULES_WUNLOCK();
1321 			error = EINVAL;
1322 			break;
1323 		}
1324 		tail = TAILQ_LAST(ruleset->rules[rs_num].active.ptr,
1325 		    pf_rulequeue);
1326 		if (tail)
1327 			pr->nr = tail->nr + 1;
1328 		else
1329 			pr->nr = 0;
1330 		pr->ticket = ruleset->rules[rs_num].active.ticket;
1331 		PF_RULES_WUNLOCK();
1332 		break;
1333 	}
1334 
1335 	case DIOCGETRULE: {
1336 		struct pfioc_rule	*pr = (struct pfioc_rule *)addr;
1337 		struct pf_ruleset	*ruleset;
1338 		struct pf_rule		*rule;
1339 		int			 rs_num, i;
1340 
1341 		PF_RULES_WLOCK();
1342 		pr->anchor[sizeof(pr->anchor) - 1] = 0;
1343 		ruleset = pf_find_ruleset(pr->anchor);
1344 		if (ruleset == NULL) {
1345 			PF_RULES_WUNLOCK();
1346 			error = EINVAL;
1347 			break;
1348 		}
1349 		rs_num = pf_get_ruleset_number(pr->rule.action);
1350 		if (rs_num >= PF_RULESET_MAX) {
1351 			PF_RULES_WUNLOCK();
1352 			error = EINVAL;
1353 			break;
1354 		}
1355 		if (pr->ticket != ruleset->rules[rs_num].active.ticket) {
1356 			PF_RULES_WUNLOCK();
1357 			error = EBUSY;
1358 			break;
1359 		}
1360 		rule = TAILQ_FIRST(ruleset->rules[rs_num].active.ptr);
1361 		while ((rule != NULL) && (rule->nr != pr->nr))
1362 			rule = TAILQ_NEXT(rule, entries);
1363 		if (rule == NULL) {
1364 			PF_RULES_WUNLOCK();
1365 			error = EBUSY;
1366 			break;
1367 		}
1368 		bcopy(rule, &pr->rule, sizeof(struct pf_rule));
1369 		pr->rule.u_states_cur = counter_u64_fetch(rule->states_cur);
1370 		pr->rule.u_states_tot = counter_u64_fetch(rule->states_tot);
1371 		pr->rule.u_src_nodes = counter_u64_fetch(rule->src_nodes);
1372 		if (pf_anchor_copyout(ruleset, rule, pr)) {
1373 			PF_RULES_WUNLOCK();
1374 			error = EBUSY;
1375 			break;
1376 		}
1377 		pf_addr_copyout(&pr->rule.src.addr);
1378 		pf_addr_copyout(&pr->rule.dst.addr);
1379 		for (i = 0; i < PF_SKIP_COUNT; ++i)
1380 			if (rule->skip[i].ptr == NULL)
1381 				pr->rule.skip[i].nr = -1;
1382 			else
1383 				pr->rule.skip[i].nr =
1384 				    rule->skip[i].ptr->nr;
1385 
1386 		if (pr->action == PF_GET_CLR_CNTR) {
1387 			rule->evaluations = 0;
1388 			rule->packets[0] = rule->packets[1] = 0;
1389 			rule->bytes[0] = rule->bytes[1] = 0;
1390 			counter_u64_zero(rule->states_tot);
1391 		}
1392 		PF_RULES_WUNLOCK();
1393 		break;
1394 	}
1395 
1396 	case DIOCCLRSTATES: {
1397 		struct pf_state		*s;
1398 		struct pfioc_state_kill *psk = (struct pfioc_state_kill *)addr;
1399 		u_int			 i, killed = 0;
1400 
1401 		for (i = 0; i <= pf_hashmask; i++) {
1402 			struct pf_idhash *ih = &V_pf_idhash[i];
1403 
1404 relock_DIOCCLRSTATES:
1405 			PF_HASHROW_LOCK(ih);
1406 			LIST_FOREACH(s, &ih->states, entry)
1407 				if (!psk->psk_ifname[0] ||
1408 				    !strcmp(psk->psk_ifname,
1409 				    s->kif->pfik_name)) {
1410 					/*
1411 					 * Don't send out individual
1412 					 * delete messages.
1413 					 */
1414 					s->state_flags |= PFSTATE_NOSYNC;
1415 					pf_unlink_state(s, PF_ENTER_LOCKED);
1416 					killed++;
1417 					goto relock_DIOCCLRSTATES;
1418 				}
1419 			PF_HASHROW_UNLOCK(ih);
1420 		}
1421 		psk->psk_killed = killed;
1422 		if (pfsync_clear_states_ptr != NULL)
1423 			pfsync_clear_states_ptr(V_pf_status.hostid, psk->psk_ifname);
1424 		break;
1425 	}
1426 
1427 	case DIOCKILLSTATES: {
1428 		struct pf_state		*s;
1429 		struct pf_state_key	*sk;
1430 		struct pf_addr		*srcaddr, *dstaddr;
1431 		u_int16_t		 srcport, dstport;
1432 		struct pfioc_state_kill	*psk = (struct pfioc_state_kill *)addr;
1433 		u_int			 i, killed = 0;
1434 
1435 		if (psk->psk_pfcmp.id) {
1436 			if (psk->psk_pfcmp.creatorid == 0)
1437 				psk->psk_pfcmp.creatorid = V_pf_status.hostid;
1438 			if ((s = pf_find_state_byid(psk->psk_pfcmp.id,
1439 			    psk->psk_pfcmp.creatorid))) {
1440 				pf_unlink_state(s, PF_ENTER_LOCKED);
1441 				psk->psk_killed = 1;
1442 			}
1443 			break;
1444 		}
1445 
1446 		for (i = 0; i <= pf_hashmask; i++) {
1447 			struct pf_idhash *ih = &V_pf_idhash[i];
1448 
1449 relock_DIOCKILLSTATES:
1450 			PF_HASHROW_LOCK(ih);
1451 			LIST_FOREACH(s, &ih->states, entry) {
1452 				sk = s->key[PF_SK_WIRE];
1453 				if (s->direction == PF_OUT) {
1454 					srcaddr = &sk->addr[1];
1455 					dstaddr = &sk->addr[0];
1456 					srcport = sk->port[1];
1457 					dstport = sk->port[0];
1458 				} else {
1459 					srcaddr = &sk->addr[0];
1460 					dstaddr = &sk->addr[1];
1461 					srcport = sk->port[0];
1462 					dstport = sk->port[1];
1463 				}
1464 
1465 				if ((!psk->psk_af || sk->af == psk->psk_af)
1466 				    && (!psk->psk_proto || psk->psk_proto ==
1467 				    sk->proto) &&
1468 				    PF_MATCHA(psk->psk_src.neg,
1469 				    &psk->psk_src.addr.v.a.addr,
1470 				    &psk->psk_src.addr.v.a.mask,
1471 				    srcaddr, sk->af) &&
1472 				    PF_MATCHA(psk->psk_dst.neg,
1473 				    &psk->psk_dst.addr.v.a.addr,
1474 				    &psk->psk_dst.addr.v.a.mask,
1475 				    dstaddr, sk->af) &&
1476 				    (psk->psk_src.port_op == 0 ||
1477 				    pf_match_port(psk->psk_src.port_op,
1478 				    psk->psk_src.port[0], psk->psk_src.port[1],
1479 				    srcport)) &&
1480 				    (psk->psk_dst.port_op == 0 ||
1481 				    pf_match_port(psk->psk_dst.port_op,
1482 				    psk->psk_dst.port[0], psk->psk_dst.port[1],
1483 				    dstport)) &&
1484 				    (!psk->psk_label[0] ||
1485 				    (s->rule.ptr->label[0] &&
1486 				    !strcmp(psk->psk_label,
1487 				    s->rule.ptr->label))) &&
1488 				    (!psk->psk_ifname[0] ||
1489 				    !strcmp(psk->psk_ifname,
1490 				    s->kif->pfik_name))) {
1491 					pf_unlink_state(s, PF_ENTER_LOCKED);
1492 					killed++;
1493 					goto relock_DIOCKILLSTATES;
1494 				}
1495 			}
1496 			PF_HASHROW_UNLOCK(ih);
1497 		}
1498 		psk->psk_killed = killed;
1499 		break;
1500 	}
1501 
1502 	case DIOCGETSTATES: {
1503 		struct pfioc_states	*ps = (struct pfioc_states *)addr;
1504 		struct pf_state		*s;
1505 		struct pfsync_state	*pstore, *p;
1506 		int i, nr;
1507 
1508 		if (ps->ps_len == 0) {
1509 			nr = uma_zone_get_cur(V_pf_state_z);
1510 			ps->ps_len = sizeof(struct pfsync_state) * nr;
1511 			break;
1512 		}
1513 
1514 		p = pstore = malloc(ps->ps_len, M_TEMP, M_WAITOK);
1515 		nr = 0;
1516 
1517 		for (i = 0; i <= pf_hashmask; i++) {
1518 			struct pf_idhash *ih = &V_pf_idhash[i];
1519 
1520 			PF_HASHROW_LOCK(ih);
1521 			LIST_FOREACH(s, &ih->states, entry) {
1522 
1523 				if (s->timeout == PFTM_UNLINKED)
1524 					continue;
1525 
1526 				if ((nr+1) * sizeof(*p) > ps->ps_len) {
1527 					PF_HASHROW_UNLOCK(ih);
1528 					goto DIOCGETSTATES_full;
1529 				}
1530 				pfsync_state_export(p, s);
1531 				p++;
1532 				nr++;
1533 			}
1534 			PF_HASHROW_UNLOCK(ih);
1535 		}
1536 DIOCGETSTATES_full:
1537 		error = copyout(pstore, ps->ps_states,
1538 		    sizeof(struct pfsync_state) * nr);
1539 		if (error) {
1540 			free(pstore, M_TEMP);
1541 			break;
1542 		}
1543 		ps->ps_len = sizeof(struct pfsync_state) * nr;
1544 		free(pstore, M_TEMP);
1545 
1546 		break;
1547 	}
1548 
1549 	case DIOCGETSTATUS: {
1550 		struct pf_status *s = (struct pf_status *)addr;
1551 
1552 		PF_RULES_RLOCK();
1553 		s->running = V_pf_status.running;
1554 		s->since   = V_pf_status.since;
1555 		s->debug   = V_pf_status.debug;
1556 		s->hostid  = V_pf_status.hostid;
1557 		s->states  = V_pf_status.states;
1558 		s->src_nodes = V_pf_status.src_nodes;
1559 
1560 		for (int i = 0; i < PFRES_MAX; i++)
1561 			s->counters[i] =
1562 			    counter_u64_fetch(V_pf_status.counters[i]);
1563 		for (int i = 0; i < LCNT_MAX; i++)
1564 			s->lcounters[i] =
1565 			    counter_u64_fetch(V_pf_status.lcounters[i]);
1566 		for (int i = 0; i < FCNT_MAX; i++)
1567 			s->fcounters[i] =
1568 			    counter_u64_fetch(V_pf_status.fcounters[i]);
1569 		for (int i = 0; i < SCNT_MAX; i++)
1570 			s->scounters[i] =
1571 			    counter_u64_fetch(V_pf_status.scounters[i]);
1572 
1573 		bcopy(V_pf_status.ifname, s->ifname, IFNAMSIZ);
1574 		bcopy(V_pf_status.pf_chksum, s->pf_chksum,
1575 		    PF_MD5_DIGEST_LENGTH);
1576 
1577 		pfi_update_status(s->ifname, s);
1578 		PF_RULES_RUNLOCK();
1579 		break;
1580 	}
1581 
1582 	case DIOCSETSTATUSIF: {
1583 		struct pfioc_if	*pi = (struct pfioc_if *)addr;
1584 
1585 		if (pi->ifname[0] == 0) {
1586 			bzero(V_pf_status.ifname, IFNAMSIZ);
1587 			break;
1588 		}
1589 		PF_RULES_WLOCK();
1590 		strlcpy(V_pf_status.ifname, pi->ifname, IFNAMSIZ);
1591 		PF_RULES_WUNLOCK();
1592 		break;
1593 	}
1594 
1595 	case DIOCCLRSTATUS: {
1596 		PF_RULES_WLOCK();
1597 		for (int i = 0; i < PFRES_MAX; i++)
1598 			counter_u64_zero(V_pf_status.counters[i]);
1599 		for (int i = 0; i < FCNT_MAX; i++)
1600 			counter_u64_zero(V_pf_status.fcounters[i]);
1601 		for (int i = 0; i < SCNT_MAX; i++)
1602 			counter_u64_zero(V_pf_status.scounters[i]);
1603 		for (int i = 0; i < LCNT_MAX; i++)
1604 			counter_u64_zero(V_pf_status.lcounters[i]);
1605 		V_pf_status.since = time_second;
1606 		if (*V_pf_status.ifname)
1607 			pfi_update_status(V_pf_status.ifname, NULL);
1608 		PF_RULES_WUNLOCK();
1609 		break;
1610 	}
1611 
1612 	case DIOCNATLOOK: {
1613 		struct pfioc_natlook	*pnl = (struct pfioc_natlook *)addr;
1614 		struct pf_state_key	*sk;
1615 		struct pf_state		*state;
1616 		struct pf_state_key_cmp	 key;
1617 		int			 m = 0, direction = pnl->direction;
1618 		int			 sidx, didx;
1619 
1620 		/* NATLOOK src and dst are reversed, so reverse sidx/didx */
1621 		sidx = (direction == PF_IN) ? 1 : 0;
1622 		didx = (direction == PF_IN) ? 0 : 1;
1623 
1624 		if (!pnl->proto ||
1625 		    PF_AZERO(&pnl->saddr, pnl->af) ||
1626 		    PF_AZERO(&pnl->daddr, pnl->af) ||
1627 		    ((pnl->proto == IPPROTO_TCP ||
1628 		    pnl->proto == IPPROTO_UDP) &&
1629 		    (!pnl->dport || !pnl->sport)))
1630 			error = EINVAL;
1631 		else {
1632 			bzero(&key, sizeof(key));
1633 			key.af = pnl->af;
1634 			key.proto = pnl->proto;
1635 			PF_ACPY(&key.addr[sidx], &pnl->saddr, pnl->af);
1636 			key.port[sidx] = pnl->sport;
1637 			PF_ACPY(&key.addr[didx], &pnl->daddr, pnl->af);
1638 			key.port[didx] = pnl->dport;
1639 
1640 			state = pf_find_state_all(&key, direction, &m);
1641 
1642 			if (m > 1)
1643 				error = E2BIG;	/* more than one state */
1644 			else if (state != NULL) {
1645 				/* XXXGL: not locked read */
1646 				sk = state->key[sidx];
1647 				PF_ACPY(&pnl->rsaddr, &sk->addr[sidx], sk->af);
1648 				pnl->rsport = sk->port[sidx];
1649 				PF_ACPY(&pnl->rdaddr, &sk->addr[didx], sk->af);
1650 				pnl->rdport = sk->port[didx];
1651 			} else
1652 				error = ENOENT;
1653 		}
1654 		break;
1655 	}
1656 
1657 	case DIOCSETTIMEOUT: {
1658 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
1659 		int		 old;
1660 
1661 		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX ||
1662 		    pt->seconds < 0) {
1663 			error = EINVAL;
1664 			break;
1665 		}
1666 		PF_RULES_WLOCK();
1667 		old = V_pf_default_rule.timeout[pt->timeout];
1668 		if (pt->timeout == PFTM_INTERVAL && pt->seconds == 0)
1669 			pt->seconds = 1;
1670 		V_pf_default_rule.timeout[pt->timeout] = pt->seconds;
1671 		if (pt->timeout == PFTM_INTERVAL && pt->seconds < old)
1672 			wakeup(pf_purge_thread);
1673 		pt->seconds = old;
1674 		PF_RULES_WUNLOCK();
1675 		break;
1676 	}
1677 
1678 	case DIOCGETTIMEOUT: {
1679 		struct pfioc_tm	*pt = (struct pfioc_tm *)addr;
1680 
1681 		if (pt->timeout < 0 || pt->timeout >= PFTM_MAX) {
1682 			error = EINVAL;
1683 			break;
1684 		}
1685 		PF_RULES_RLOCK();
1686 		pt->seconds = V_pf_default_rule.timeout[pt->timeout];
1687 		PF_RULES_RUNLOCK();
1688 		break;
1689 	}
1690 
1691 	case DIOCGETLIMIT: {
1692 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
1693 
1694 		if (pl->index < 0 || pl->index >= PF_LIMIT_MAX) {
1695 			error = EINVAL;
1696 			break;
1697 		}
1698 		PF_RULES_RLOCK();
1699 		pl->limit = V_pf_limits[pl->index].limit;
1700 		PF_RULES_RUNLOCK();
1701 		break;
1702 	}
1703 
1704 	case DIOCSETLIMIT: {
1705 		struct pfioc_limit	*pl = (struct pfioc_limit *)addr;
1706 		int			 old_limit;
1707 
1708 		PF_RULES_WLOCK();
1709 		if (pl->index < 0 || pl->index >= PF_LIMIT_MAX ||
1710 		    V_pf_limits[pl->index].zone == NULL) {
1711 			PF_RULES_WUNLOCK();
1712 			error = EINVAL;
1713 			break;
1714 		}
1715 		uma_zone_set_max(V_pf_limits[pl->index].zone, pl->limit);
1716 		old_limit = V_pf_limits[pl->index].limit;
1717 		V_pf_limits[pl->index].limit = pl->limit;
1718 		pl->limit = old_limit;
1719 		PF_RULES_WUNLOCK();
1720 		break;
1721 	}
1722 
1723 	case DIOCSETDEBUG: {
1724 		u_int32_t	*level = (u_int32_t *)addr;
1725 
1726 		PF_RULES_WLOCK();
1727 		V_pf_status.debug = *level;
1728 		PF_RULES_WUNLOCK();
1729 		break;
1730 	}
1731 
1732 	case DIOCGIFSPEED: {
1733 		struct pf_ifspeed	*psp = (struct pf_ifspeed *)addr;
1734 		struct pf_ifspeed	ps;
1735 		struct ifnet		*ifp;
1736 
1737 		if (psp->ifname[0] != 0) {
1738 			/* Can we completely trust user-land? */
1739 			strlcpy(ps.ifname, psp->ifname, IFNAMSIZ);
1740 			ifp = ifunit(ps.ifname);
1741 			if (ifp != NULL)
1742 				psp->baudrate = ifp->if_baudrate;
1743 			else
1744 				error = EINVAL;
1745 		} else
1746 			error = EINVAL;
1747 		break;
1748 	}
1749 
1750 #ifdef ALTQ
1751 	case DIOCSTARTALTQ: {
1752 		struct pf_altq		*altq;
1753 
1754 		PF_RULES_WLOCK();
1755 		/* enable all altq interfaces on active list */
1756 		TAILQ_FOREACH(altq, V_pf_altqs_active, entries) {
1757 			if (altq->qname[0] == 0 && (altq->local_flags &
1758 			    PFALTQ_FLAG_IF_REMOVED) == 0) {
1759 				error = pf_enable_altq(altq);
1760 				if (error != 0)
1761 					break;
1762 			}
1763 		}
1764 		if (error == 0)
1765 			V_pf_altq_running = 1;
1766 		PF_RULES_WUNLOCK();
1767 		DPFPRINTF(PF_DEBUG_MISC, ("altq: started\n"));
1768 		break;
1769 	}
1770 
1771 	case DIOCSTOPALTQ: {
1772 		struct pf_altq		*altq;
1773 
1774 		PF_RULES_WLOCK();
1775 		/* disable all altq interfaces on active list */
1776 		TAILQ_FOREACH(altq, V_pf_altqs_active, entries) {
1777 			if (altq->qname[0] == 0 && (altq->local_flags &
1778 			    PFALTQ_FLAG_IF_REMOVED) == 0) {
1779 				error = pf_disable_altq(altq);
1780 				if (error != 0)
1781 					break;
1782 			}
1783 		}
1784 		if (error == 0)
1785 			V_pf_altq_running = 0;
1786 		PF_RULES_WUNLOCK();
1787 		DPFPRINTF(PF_DEBUG_MISC, ("altq: stopped\n"));
1788 		break;
1789 	}
1790 
1791 	case DIOCADDALTQ: {
1792 		struct pfioc_altq	*pa = (struct pfioc_altq *)addr;
1793 		struct pf_altq		*altq, *a;
1794 		struct ifnet		*ifp;
1795 
1796 		altq = malloc(sizeof(*altq), M_PFALTQ, M_WAITOK);
1797 		bcopy(&pa->altq, altq, sizeof(struct pf_altq));
1798 		altq->local_flags = 0;
1799 
1800 		PF_RULES_WLOCK();
1801 		if (pa->ticket != V_ticket_altqs_inactive) {
1802 			PF_RULES_WUNLOCK();
1803 			free(altq, M_PFALTQ);
1804 			error = EBUSY;
1805 			break;
1806 		}
1807 
1808 		/*
1809 		 * if this is for a queue, find the discipline and
1810 		 * copy the necessary fields
1811 		 */
1812 		if (altq->qname[0] != 0) {
1813 			if ((altq->qid = pf_qname2qid(altq->qname)) == 0) {
1814 				PF_RULES_WUNLOCK();
1815 				error = EBUSY;
1816 				free(altq, M_PFALTQ);
1817 				break;
1818 			}
1819 			altq->altq_disc = NULL;
1820 			TAILQ_FOREACH(a, V_pf_altqs_inactive, entries) {
1821 				if (strncmp(a->ifname, altq->ifname,
1822 				    IFNAMSIZ) == 0 && a->qname[0] == 0) {
1823 					altq->altq_disc = a->altq_disc;
1824 					break;
1825 				}
1826 			}
1827 		}
1828 
1829 		if ((ifp = ifunit(altq->ifname)) == NULL)
1830 			altq->local_flags |= PFALTQ_FLAG_IF_REMOVED;
1831 		else
1832 			error = altq_add(altq);
1833 
1834 		if (error) {
1835 			PF_RULES_WUNLOCK();
1836 			free(altq, M_PFALTQ);
1837 			break;
1838 		}
1839 
1840 		TAILQ_INSERT_TAIL(V_pf_altqs_inactive, altq, entries);
1841 		bcopy(altq, &pa->altq, sizeof(struct pf_altq));
1842 		PF_RULES_WUNLOCK();
1843 		break;
1844 	}
1845 
1846 	case DIOCGETALTQS: {
1847 		struct pfioc_altq	*pa = (struct pfioc_altq *)addr;
1848 		struct pf_altq		*altq;
1849 
1850 		PF_RULES_RLOCK();
1851 		pa->nr = 0;
1852 		TAILQ_FOREACH(altq, V_pf_altqs_active, entries)
1853 			pa->nr++;
1854 		pa->ticket = V_ticket_altqs_active;
1855 		PF_RULES_RUNLOCK();
1856 		break;
1857 	}
1858 
1859 	case DIOCGETALTQ: {
1860 		struct pfioc_altq	*pa = (struct pfioc_altq *)addr;
1861 		struct pf_altq		*altq;
1862 		u_int32_t		 nr;
1863 
1864 		PF_RULES_RLOCK();
1865 		if (pa->ticket != V_ticket_altqs_active) {
1866 			PF_RULES_RUNLOCK();
1867 			error = EBUSY;
1868 			break;
1869 		}
1870 		nr = 0;
1871 		altq = TAILQ_FIRST(V_pf_altqs_active);
1872 		while ((altq != NULL) && (nr < pa->nr)) {
1873 			altq = TAILQ_NEXT(altq, entries);
1874 			nr++;
1875 		}
1876 		if (altq == NULL) {
1877 			PF_RULES_RUNLOCK();
1878 			error = EBUSY;
1879 			break;
1880 		}
1881 		bcopy(altq, &pa->altq, sizeof(struct pf_altq));
1882 		PF_RULES_RUNLOCK();
1883 		break;
1884 	}
1885 
1886 	case DIOCGETQSTATS: {
1887 		struct pfioc_qstats	*pq = (struct pfioc_qstats *)addr;
1888 		struct pf_altq		*altq;
1889 		u_int32_t		 nr;
1890 		int			 nbytes;
1891 
1892 		PF_RULES_RLOCK();
1893 		if (pq->ticket != V_ticket_altqs_active) {
1894 			PF_RULES_RUNLOCK();
1895 			error = EBUSY;
1896 			break;
1897 		}
1898 		nbytes = pq->nbytes;
1899 		nr = 0;
1900 		altq = TAILQ_FIRST(V_pf_altqs_active);
1901 		while ((altq != NULL) && (nr < pq->nr)) {
1902 			altq = TAILQ_NEXT(altq, entries);
1903 			nr++;
1904 		}
1905 		if (altq == NULL) {
1906 			PF_RULES_RUNLOCK();
1907 			error = EBUSY;
1908 			break;
1909 		}
1910 
1911 		if ((altq->local_flags & PFALTQ_FLAG_IF_REMOVED) != 0) {
1912 			PF_RULES_RUNLOCK();
1913 			error = ENXIO;
1914 			break;
1915 		}
1916 		PF_RULES_RUNLOCK();
1917 		error = altq_getqstats(altq, pq->buf, &nbytes);
1918 		if (error == 0) {
1919 			pq->scheduler = altq->scheduler;
1920 			pq->nbytes = nbytes;
1921 		}
1922 		break;
1923 	}
1924 #endif /* ALTQ */
1925 
1926 	case DIOCBEGINADDRS: {
1927 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
1928 
1929 		PF_RULES_WLOCK();
1930 		pf_empty_pool(&V_pf_pabuf);
1931 		pp->ticket = ++V_ticket_pabuf;
1932 		PF_RULES_WUNLOCK();
1933 		break;
1934 	}
1935 
1936 	case DIOCADDADDR: {
1937 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
1938 		struct pf_pooladdr	*pa;
1939 		struct pfi_kif		*kif = NULL;
1940 
1941 #ifndef INET
1942 		if (pp->af == AF_INET) {
1943 			error = EAFNOSUPPORT;
1944 			break;
1945 		}
1946 #endif /* INET */
1947 #ifndef INET6
1948 		if (pp->af == AF_INET6) {
1949 			error = EAFNOSUPPORT;
1950 			break;
1951 		}
1952 #endif /* INET6 */
1953 		if (pp->addr.addr.type != PF_ADDR_ADDRMASK &&
1954 		    pp->addr.addr.type != PF_ADDR_DYNIFTL &&
1955 		    pp->addr.addr.type != PF_ADDR_TABLE) {
1956 			error = EINVAL;
1957 			break;
1958 		}
1959 		pa = malloc(sizeof(*pa), M_PFRULE, M_WAITOK);
1960 		bcopy(&pp->addr, pa, sizeof(struct pf_pooladdr));
1961 		if (pa->ifname[0])
1962 			kif = malloc(sizeof(*kif), PFI_MTYPE, M_WAITOK);
1963 		PF_RULES_WLOCK();
1964 		if (pp->ticket != V_ticket_pabuf) {
1965 			PF_RULES_WUNLOCK();
1966 			if (pa->ifname[0])
1967 				free(kif, PFI_MTYPE);
1968 			free(pa, M_PFRULE);
1969 			error = EBUSY;
1970 			break;
1971 		}
1972 		if (pa->ifname[0]) {
1973 			pa->kif = pfi_kif_attach(kif, pa->ifname);
1974 			pfi_kif_ref(pa->kif);
1975 		} else
1976 			pa->kif = NULL;
1977 		if (pa->addr.type == PF_ADDR_DYNIFTL && ((error =
1978 		    pfi_dynaddr_setup(&pa->addr, pp->af)) != 0)) {
1979 			if (pa->ifname[0])
1980 				pfi_kif_unref(pa->kif);
1981 			PF_RULES_WUNLOCK();
1982 			free(pa, M_PFRULE);
1983 			break;
1984 		}
1985 		TAILQ_INSERT_TAIL(&V_pf_pabuf, pa, entries);
1986 		PF_RULES_WUNLOCK();
1987 		break;
1988 	}
1989 
1990 	case DIOCGETADDRS: {
1991 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
1992 		struct pf_pool		*pool;
1993 		struct pf_pooladdr	*pa;
1994 
1995 		PF_RULES_RLOCK();
1996 		pp->nr = 0;
1997 		pool = pf_get_pool(pp->anchor, pp->ticket, pp->r_action,
1998 		    pp->r_num, 0, 1, 0);
1999 		if (pool == NULL) {
2000 			PF_RULES_RUNLOCK();
2001 			error = EBUSY;
2002 			break;
2003 		}
2004 		TAILQ_FOREACH(pa, &pool->list, entries)
2005 			pp->nr++;
2006 		PF_RULES_RUNLOCK();
2007 		break;
2008 	}
2009 
2010 	case DIOCGETADDR: {
2011 		struct pfioc_pooladdr	*pp = (struct pfioc_pooladdr *)addr;
2012 		struct pf_pool		*pool;
2013 		struct pf_pooladdr	*pa;
2014 		u_int32_t		 nr = 0;
2015 
2016 		PF_RULES_RLOCK();
2017 		pool = pf_get_pool(pp->anchor, pp->ticket, pp->r_action,
2018 		    pp->r_num, 0, 1, 1);
2019 		if (pool == NULL) {
2020 			PF_RULES_RUNLOCK();
2021 			error = EBUSY;
2022 			break;
2023 		}
2024 		pa = TAILQ_FIRST(&pool->list);
2025 		while ((pa != NULL) && (nr < pp->nr)) {
2026 			pa = TAILQ_NEXT(pa, entries);
2027 			nr++;
2028 		}
2029 		if (pa == NULL) {
2030 			PF_RULES_RUNLOCK();
2031 			error = EBUSY;
2032 			break;
2033 		}
2034 		bcopy(pa, &pp->addr, sizeof(struct pf_pooladdr));
2035 		pf_addr_copyout(&pp->addr.addr);
2036 		PF_RULES_RUNLOCK();
2037 		break;
2038 	}
2039 
2040 	case DIOCGETRULESETS: {
2041 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
2042 		struct pf_ruleset	*ruleset;
2043 		struct pf_anchor	*anchor;
2044 
2045 		PF_RULES_RLOCK();
2046 		pr->path[sizeof(pr->path) - 1] = 0;
2047 		if ((ruleset = pf_find_ruleset(pr->path)) == NULL) {
2048 			PF_RULES_RUNLOCK();
2049 			error = ENOENT;
2050 			break;
2051 		}
2052 		pr->nr = 0;
2053 		if (ruleset->anchor == NULL) {
2054 			/* XXX kludge for pf_main_ruleset */
2055 			RB_FOREACH(anchor, pf_anchor_global, &V_pf_anchors)
2056 				if (anchor->parent == NULL)
2057 					pr->nr++;
2058 		} else {
2059 			RB_FOREACH(anchor, pf_anchor_node,
2060 			    &ruleset->anchor->children)
2061 				pr->nr++;
2062 		}
2063 		PF_RULES_RUNLOCK();
2064 		break;
2065 	}
2066 
2067 	case DIOCGETRULESET: {
2068 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
2069 		struct pf_ruleset	*ruleset;
2070 		struct pf_anchor	*anchor;
2071 		u_int32_t		 nr = 0;
2072 
2073 		PF_RULES_RLOCK();
2074 		pr->path[sizeof(pr->path) - 1] = 0;
2075 		if ((ruleset = pf_find_ruleset(pr->path)) == NULL) {
2076 			PF_RULES_RUNLOCK();
2077 			error = ENOENT;
2078 			break;
2079 		}
2080 		pr->name[0] = 0;
2081 		if (ruleset->anchor == NULL) {
2082 			/* XXX kludge for pf_main_ruleset */
2083 			RB_FOREACH(anchor, pf_anchor_global, &V_pf_anchors)
2084 				if (anchor->parent == NULL && nr++ == pr->nr) {
2085 					strlcpy(pr->name, anchor->name,
2086 					    sizeof(pr->name));
2087 					break;
2088 				}
2089 		} else {
2090 			RB_FOREACH(anchor, pf_anchor_node,
2091 			    &ruleset->anchor->children)
2092 				if (nr++ == pr->nr) {
2093 					strlcpy(pr->name, anchor->name,
2094 					    sizeof(pr->name));
2095 					break;
2096 				}
2097 		}
2098 		if (!pr->name[0])
2099 			error = EBUSY;
2100 		PF_RULES_RUNLOCK();
2101 		break;
2102 	}
2103 
2104 	case DIOCRCLRTABLES: {
2105 		struct pfioc_table *io = (struct pfioc_table *)addr;
2106 
2107 		if (io->pfrio_esize != 0) {
2108 			error = ENODEV;
2109 			break;
2110 		}
2111 		PF_RULES_WLOCK();
2112 		error = pfr_clr_tables(&io->pfrio_table, &io->pfrio_ndel,
2113 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
2114 		PF_RULES_WUNLOCK();
2115 		break;
2116 	}
2117 
2118 	case DIOCRADDTABLES: {
2119 		struct pfioc_table *io = (struct pfioc_table *)addr;
2120 		struct pfr_table *pfrts;
2121 		size_t totlen;
2122 
2123 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2124 			error = ENODEV;
2125 			break;
2126 		}
2127 
2128 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
2129 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
2130 			error = ENOMEM;
2131 			break;
2132 		}
2133 
2134 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2135 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
2136 		    M_TEMP, M_WAITOK);
2137 		error = copyin(io->pfrio_buffer, pfrts, totlen);
2138 		if (error) {
2139 			free(pfrts, M_TEMP);
2140 			break;
2141 		}
2142 		PF_RULES_WLOCK();
2143 		error = pfr_add_tables(pfrts, io->pfrio_size,
2144 		    &io->pfrio_nadd, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2145 		PF_RULES_WUNLOCK();
2146 		free(pfrts, M_TEMP);
2147 		break;
2148 	}
2149 
2150 	case DIOCRDELTABLES: {
2151 		struct pfioc_table *io = (struct pfioc_table *)addr;
2152 		struct pfr_table *pfrts;
2153 		size_t totlen;
2154 
2155 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2156 			error = ENODEV;
2157 			break;
2158 		}
2159 
2160 		if (io->pfrio_size < 0 || io->pfrio_size > pf_ioctl_maxcount ||
2161 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_table))) {
2162 			error = ENOMEM;
2163 			break;
2164 		}
2165 
2166 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2167 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
2168 		    M_TEMP, M_WAITOK);
2169 		error = copyin(io->pfrio_buffer, pfrts, totlen);
2170 		if (error) {
2171 			free(pfrts, M_TEMP);
2172 			break;
2173 		}
2174 		PF_RULES_WLOCK();
2175 		error = pfr_del_tables(pfrts, io->pfrio_size,
2176 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2177 		PF_RULES_WUNLOCK();
2178 		free(pfrts, M_TEMP);
2179 		break;
2180 	}
2181 
2182 	case DIOCRGETTABLES: {
2183 		struct pfioc_table *io = (struct pfioc_table *)addr;
2184 		struct pfr_table *pfrts;
2185 		size_t totlen, n;
2186 
2187 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2188 			error = ENODEV;
2189 			break;
2190 		}
2191 		PF_RULES_RLOCK();
2192 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
2193 		io->pfrio_size = min(io->pfrio_size, n);
2194 
2195 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2196 
2197 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
2198 		    M_TEMP, M_NOWAIT);
2199 		if (pfrts == NULL) {
2200 			error = ENOMEM;
2201 			PF_RULES_RUNLOCK();
2202 			break;
2203 		}
2204 		error = pfr_get_tables(&io->pfrio_table, pfrts,
2205 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2206 		PF_RULES_RUNLOCK();
2207 		if (error == 0)
2208 			error = copyout(pfrts, io->pfrio_buffer, totlen);
2209 		free(pfrts, M_TEMP);
2210 		break;
2211 	}
2212 
2213 	case DIOCRGETTSTATS: {
2214 		struct pfioc_table *io = (struct pfioc_table *)addr;
2215 		struct pfr_tstats *pfrtstats;
2216 		size_t totlen, n;
2217 
2218 		if (io->pfrio_esize != sizeof(struct pfr_tstats)) {
2219 			error = ENODEV;
2220 			break;
2221 		}
2222 		PF_RULES_WLOCK();
2223 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
2224 		io->pfrio_size = min(io->pfrio_size, n);
2225 
2226 		totlen = io->pfrio_size * sizeof(struct pfr_tstats);
2227 		pfrtstats = mallocarray(io->pfrio_size,
2228 		    sizeof(struct pfr_tstats), M_TEMP, M_NOWAIT);
2229 		if (pfrtstats == NULL) {
2230 			error = ENOMEM;
2231 			PF_RULES_WUNLOCK();
2232 			break;
2233 		}
2234 		error = pfr_get_tstats(&io->pfrio_table, pfrtstats,
2235 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2236 		PF_RULES_WUNLOCK();
2237 		if (error == 0)
2238 			error = copyout(pfrtstats, io->pfrio_buffer, totlen);
2239 		free(pfrtstats, M_TEMP);
2240 		break;
2241 	}
2242 
2243 	case DIOCRCLRTSTATS: {
2244 		struct pfioc_table *io = (struct pfioc_table *)addr;
2245 		struct pfr_table *pfrts;
2246 		size_t totlen, n;
2247 
2248 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2249 			error = ENODEV;
2250 			break;
2251 		}
2252 
2253 		PF_RULES_WLOCK();
2254 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
2255 		io->pfrio_size = min(io->pfrio_size, n);
2256 
2257 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2258 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
2259 		    M_TEMP, M_NOWAIT);
2260 		if (pfrts == NULL) {
2261 			error = ENOMEM;
2262 			PF_RULES_WUNLOCK();
2263 			break;
2264 		}
2265 		error = copyin(io->pfrio_buffer, pfrts, totlen);
2266 		if (error) {
2267 			free(pfrts, M_TEMP);
2268 			PF_RULES_WUNLOCK();
2269 			break;
2270 		}
2271 		error = pfr_clr_tstats(pfrts, io->pfrio_size,
2272 		    &io->pfrio_nzero, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2273 		PF_RULES_WUNLOCK();
2274 		free(pfrts, M_TEMP);
2275 		break;
2276 	}
2277 
2278 	case DIOCRSETTFLAGS: {
2279 		struct pfioc_table *io = (struct pfioc_table *)addr;
2280 		struct pfr_table *pfrts;
2281 		size_t totlen, n;
2282 
2283 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2284 			error = ENODEV;
2285 			break;
2286 		}
2287 
2288 		PF_RULES_WLOCK();
2289 		n = pfr_table_count(&io->pfrio_table, io->pfrio_flags);
2290 		io->pfrio_size = min(io->pfrio_size, n);
2291 
2292 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2293 		pfrts = mallocarray(io->pfrio_size, sizeof(struct pfr_table),
2294 		    M_TEMP, M_NOWAIT);
2295 		if (pfrts == NULL) {
2296 			error = ENOMEM;
2297 			PF_RULES_WUNLOCK();
2298 			break;
2299 		}
2300 		error = copyin(io->pfrio_buffer, pfrts, totlen);
2301 		if (error) {
2302 			free(pfrts, M_TEMP);
2303 			PF_RULES_WUNLOCK();
2304 			break;
2305 		}
2306 		error = pfr_set_tflags(pfrts, io->pfrio_size,
2307 		    io->pfrio_setflag, io->pfrio_clrflag, &io->pfrio_nchange,
2308 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2309 		PF_RULES_WUNLOCK();
2310 		free(pfrts, M_TEMP);
2311 		break;
2312 	}
2313 
2314 	case DIOCRCLRADDRS: {
2315 		struct pfioc_table *io = (struct pfioc_table *)addr;
2316 
2317 		if (io->pfrio_esize != 0) {
2318 			error = ENODEV;
2319 			break;
2320 		}
2321 		PF_RULES_WLOCK();
2322 		error = pfr_clr_addrs(&io->pfrio_table, &io->pfrio_ndel,
2323 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
2324 		PF_RULES_WUNLOCK();
2325 		break;
2326 	}
2327 
2328 	case DIOCRADDADDRS: {
2329 		struct pfioc_table *io = (struct pfioc_table *)addr;
2330 		struct pfr_addr *pfras;
2331 		size_t totlen;
2332 
2333 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2334 			error = ENODEV;
2335 			break;
2336 		}
2337 		if (io->pfrio_size < 0 ||
2338 		    io->pfrio_size > pf_ioctl_maxcount ||
2339 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
2340 			error = EINVAL;
2341 			break;
2342 		}
2343 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2344 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
2345 		    M_TEMP, M_NOWAIT);
2346 		if (! pfras) {
2347 			error = ENOMEM;
2348 			break;
2349 		}
2350 		error = copyin(io->pfrio_buffer, pfras, totlen);
2351 		if (error) {
2352 			free(pfras, M_TEMP);
2353 			break;
2354 		}
2355 		PF_RULES_WLOCK();
2356 		error = pfr_add_addrs(&io->pfrio_table, pfras,
2357 		    io->pfrio_size, &io->pfrio_nadd, io->pfrio_flags |
2358 		    PFR_FLAG_USERIOCTL);
2359 		PF_RULES_WUNLOCK();
2360 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
2361 			error = copyout(pfras, io->pfrio_buffer, totlen);
2362 		free(pfras, M_TEMP);
2363 		break;
2364 	}
2365 
2366 	case DIOCRDELADDRS: {
2367 		struct pfioc_table *io = (struct pfioc_table *)addr;
2368 		struct pfr_addr *pfras;
2369 		size_t totlen;
2370 
2371 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2372 			error = ENODEV;
2373 			break;
2374 		}
2375 		if (io->pfrio_size < 0 ||
2376 		    io->pfrio_size > pf_ioctl_maxcount ||
2377 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
2378 			error = EINVAL;
2379 			break;
2380 		}
2381 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2382 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
2383 		    M_TEMP, M_NOWAIT);
2384 		if (! pfras) {
2385 			error = ENOMEM;
2386 			break;
2387 		}
2388 		error = copyin(io->pfrio_buffer, pfras, totlen);
2389 		if (error) {
2390 			free(pfras, M_TEMP);
2391 			break;
2392 		}
2393 		PF_RULES_WLOCK();
2394 		error = pfr_del_addrs(&io->pfrio_table, pfras,
2395 		    io->pfrio_size, &io->pfrio_ndel, io->pfrio_flags |
2396 		    PFR_FLAG_USERIOCTL);
2397 		PF_RULES_WUNLOCK();
2398 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
2399 			error = copyout(pfras, io->pfrio_buffer, totlen);
2400 		free(pfras, M_TEMP);
2401 		break;
2402 	}
2403 
2404 	case DIOCRSETADDRS: {
2405 		struct pfioc_table *io = (struct pfioc_table *)addr;
2406 		struct pfr_addr *pfras;
2407 		size_t totlen, count;
2408 
2409 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2410 			error = ENODEV;
2411 			break;
2412 		}
2413 		if (io->pfrio_size < 0 || io->pfrio_size2 < 0) {
2414 			error = EINVAL;
2415 			break;
2416 		}
2417 		count = max(io->pfrio_size, io->pfrio_size2);
2418 		if (count > pf_ioctl_maxcount ||
2419 		    WOULD_OVERFLOW(count, sizeof(struct pfr_addr))) {
2420 			error = EINVAL;
2421 			break;
2422 		}
2423 		totlen = count * sizeof(struct pfr_addr);
2424 		pfras = mallocarray(count, sizeof(struct pfr_addr), M_TEMP,
2425 		    M_NOWAIT);
2426 		if (! pfras) {
2427 			error = ENOMEM;
2428 			break;
2429 		}
2430 		error = copyin(io->pfrio_buffer, pfras, totlen);
2431 		if (error) {
2432 			free(pfras, M_TEMP);
2433 			break;
2434 		}
2435 		PF_RULES_WLOCK();
2436 		error = pfr_set_addrs(&io->pfrio_table, pfras,
2437 		    io->pfrio_size, &io->pfrio_size2, &io->pfrio_nadd,
2438 		    &io->pfrio_ndel, &io->pfrio_nchange, io->pfrio_flags |
2439 		    PFR_FLAG_USERIOCTL, 0);
2440 		PF_RULES_WUNLOCK();
2441 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
2442 			error = copyout(pfras, io->pfrio_buffer, totlen);
2443 		free(pfras, M_TEMP);
2444 		break;
2445 	}
2446 
2447 	case DIOCRGETADDRS: {
2448 		struct pfioc_table *io = (struct pfioc_table *)addr;
2449 		struct pfr_addr *pfras;
2450 		size_t totlen;
2451 
2452 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2453 			error = ENODEV;
2454 			break;
2455 		}
2456 		if (io->pfrio_size < 0 ||
2457 		    io->pfrio_size > pf_ioctl_maxcount ||
2458 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
2459 			error = EINVAL;
2460 			break;
2461 		}
2462 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2463 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
2464 		    M_TEMP, M_NOWAIT);
2465 		if (! pfras) {
2466 			error = ENOMEM;
2467 			break;
2468 		}
2469 		PF_RULES_RLOCK();
2470 		error = pfr_get_addrs(&io->pfrio_table, pfras,
2471 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2472 		PF_RULES_RUNLOCK();
2473 		if (error == 0)
2474 			error = copyout(pfras, io->pfrio_buffer, totlen);
2475 		free(pfras, M_TEMP);
2476 		break;
2477 	}
2478 
2479 	case DIOCRGETASTATS: {
2480 		struct pfioc_table *io = (struct pfioc_table *)addr;
2481 		struct pfr_astats *pfrastats;
2482 		size_t totlen;
2483 
2484 		if (io->pfrio_esize != sizeof(struct pfr_astats)) {
2485 			error = ENODEV;
2486 			break;
2487 		}
2488 		if (io->pfrio_size < 0 ||
2489 		    io->pfrio_size > pf_ioctl_maxcount ||
2490 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_astats))) {
2491 			error = EINVAL;
2492 			break;
2493 		}
2494 		totlen = io->pfrio_size * sizeof(struct pfr_astats);
2495 		pfrastats = mallocarray(io->pfrio_size,
2496 		    sizeof(struct pfr_astats), M_TEMP, M_NOWAIT);
2497 		if (! pfrastats) {
2498 			error = ENOMEM;
2499 			break;
2500 		}
2501 		PF_RULES_RLOCK();
2502 		error = pfr_get_astats(&io->pfrio_table, pfrastats,
2503 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2504 		PF_RULES_RUNLOCK();
2505 		if (error == 0)
2506 			error = copyout(pfrastats, io->pfrio_buffer, totlen);
2507 		free(pfrastats, M_TEMP);
2508 		break;
2509 	}
2510 
2511 	case DIOCRCLRASTATS: {
2512 		struct pfioc_table *io = (struct pfioc_table *)addr;
2513 		struct pfr_addr *pfras;
2514 		size_t totlen;
2515 
2516 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2517 			error = ENODEV;
2518 			break;
2519 		}
2520 		if (io->pfrio_size < 0 ||
2521 		    io->pfrio_size > pf_ioctl_maxcount ||
2522 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
2523 			error = EINVAL;
2524 			break;
2525 		}
2526 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2527 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
2528 		    M_TEMP, M_NOWAIT);
2529 		if (! pfras) {
2530 			error = ENOMEM;
2531 			break;
2532 		}
2533 		error = copyin(io->pfrio_buffer, pfras, totlen);
2534 		if (error) {
2535 			free(pfras, M_TEMP);
2536 			break;
2537 		}
2538 		PF_RULES_WLOCK();
2539 		error = pfr_clr_astats(&io->pfrio_table, pfras,
2540 		    io->pfrio_size, &io->pfrio_nzero, io->pfrio_flags |
2541 		    PFR_FLAG_USERIOCTL);
2542 		PF_RULES_WUNLOCK();
2543 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
2544 			error = copyout(pfras, io->pfrio_buffer, totlen);
2545 		free(pfras, M_TEMP);
2546 		break;
2547 	}
2548 
2549 	case DIOCRTSTADDRS: {
2550 		struct pfioc_table *io = (struct pfioc_table *)addr;
2551 		struct pfr_addr *pfras;
2552 		size_t totlen;
2553 
2554 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2555 			error = ENODEV;
2556 			break;
2557 		}
2558 		if (io->pfrio_size < 0 ||
2559 		    io->pfrio_size > pf_ioctl_maxcount ||
2560 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
2561 			error = EINVAL;
2562 			break;
2563 		}
2564 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2565 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
2566 		    M_TEMP, M_NOWAIT);
2567 		if (! pfras) {
2568 			error = ENOMEM;
2569 			break;
2570 		}
2571 		error = copyin(io->pfrio_buffer, pfras, totlen);
2572 		if (error) {
2573 			free(pfras, M_TEMP);
2574 			break;
2575 		}
2576 		PF_RULES_RLOCK();
2577 		error = pfr_tst_addrs(&io->pfrio_table, pfras,
2578 		    io->pfrio_size, &io->pfrio_nmatch, io->pfrio_flags |
2579 		    PFR_FLAG_USERIOCTL);
2580 		PF_RULES_RUNLOCK();
2581 		if (error == 0)
2582 			error = copyout(pfras, io->pfrio_buffer, totlen);
2583 		free(pfras, M_TEMP);
2584 		break;
2585 	}
2586 
2587 	case DIOCRINADEFINE: {
2588 		struct pfioc_table *io = (struct pfioc_table *)addr;
2589 		struct pfr_addr *pfras;
2590 		size_t totlen;
2591 
2592 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2593 			error = ENODEV;
2594 			break;
2595 		}
2596 		if (io->pfrio_size < 0 ||
2597 		    io->pfrio_size > pf_ioctl_maxcount ||
2598 		    WOULD_OVERFLOW(io->pfrio_size, sizeof(struct pfr_addr))) {
2599 			error = EINVAL;
2600 			break;
2601 		}
2602 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2603 		pfras = mallocarray(io->pfrio_size, sizeof(struct pfr_addr),
2604 		    M_TEMP, M_NOWAIT);
2605 		if (! pfras) {
2606 			error = ENOMEM;
2607 			break;
2608 		}
2609 		error = copyin(io->pfrio_buffer, pfras, totlen);
2610 		if (error) {
2611 			free(pfras, M_TEMP);
2612 			break;
2613 		}
2614 		PF_RULES_WLOCK();
2615 		error = pfr_ina_define(&io->pfrio_table, pfras,
2616 		    io->pfrio_size, &io->pfrio_nadd, &io->pfrio_naddr,
2617 		    io->pfrio_ticket, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2618 		PF_RULES_WUNLOCK();
2619 		free(pfras, M_TEMP);
2620 		break;
2621 	}
2622 
2623 	case DIOCOSFPADD: {
2624 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
2625 		PF_RULES_WLOCK();
2626 		error = pf_osfp_add(io);
2627 		PF_RULES_WUNLOCK();
2628 		break;
2629 	}
2630 
2631 	case DIOCOSFPGET: {
2632 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
2633 		PF_RULES_RLOCK();
2634 		error = pf_osfp_get(io);
2635 		PF_RULES_RUNLOCK();
2636 		break;
2637 	}
2638 
2639 	case DIOCXBEGIN: {
2640 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2641 		struct pfioc_trans_e	*ioes, *ioe;
2642 		size_t			 totlen;
2643 		int			 i;
2644 
2645 		if (io->esize != sizeof(*ioe)) {
2646 			error = ENODEV;
2647 			break;
2648 		}
2649 		if (io->size < 0 ||
2650 		    io->size > pf_ioctl_maxcount ||
2651 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
2652 			error = EINVAL;
2653 			break;
2654 		}
2655 		totlen = sizeof(struct pfioc_trans_e) * io->size;
2656 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
2657 		    M_TEMP, M_NOWAIT);
2658 		if (! ioes) {
2659 			error = ENOMEM;
2660 			break;
2661 		}
2662 		error = copyin(io->array, ioes, totlen);
2663 		if (error) {
2664 			free(ioes, M_TEMP);
2665 			break;
2666 		}
2667 		PF_RULES_WLOCK();
2668 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
2669 			switch (ioe->rs_num) {
2670 #ifdef ALTQ
2671 			case PF_RULESET_ALTQ:
2672 				if (ioe->anchor[0]) {
2673 					PF_RULES_WUNLOCK();
2674 					free(ioes, M_TEMP);
2675 					error = EINVAL;
2676 					goto fail;
2677 				}
2678 				if ((error = pf_begin_altq(&ioe->ticket))) {
2679 					PF_RULES_WUNLOCK();
2680 					free(ioes, M_TEMP);
2681 					goto fail;
2682 				}
2683 				break;
2684 #endif /* ALTQ */
2685 			case PF_RULESET_TABLE:
2686 			    {
2687 				struct pfr_table table;
2688 
2689 				bzero(&table, sizeof(table));
2690 				strlcpy(table.pfrt_anchor, ioe->anchor,
2691 				    sizeof(table.pfrt_anchor));
2692 				if ((error = pfr_ina_begin(&table,
2693 				    &ioe->ticket, NULL, 0))) {
2694 					PF_RULES_WUNLOCK();
2695 					free(ioes, M_TEMP);
2696 					goto fail;
2697 				}
2698 				break;
2699 			    }
2700 			default:
2701 				if ((error = pf_begin_rules(&ioe->ticket,
2702 				    ioe->rs_num, ioe->anchor))) {
2703 					PF_RULES_WUNLOCK();
2704 					free(ioes, M_TEMP);
2705 					goto fail;
2706 				}
2707 				break;
2708 			}
2709 		}
2710 		PF_RULES_WUNLOCK();
2711 		error = copyout(ioes, io->array, totlen);
2712 		free(ioes, M_TEMP);
2713 		break;
2714 	}
2715 
2716 	case DIOCXROLLBACK: {
2717 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2718 		struct pfioc_trans_e	*ioe, *ioes;
2719 		size_t			 totlen;
2720 		int			 i;
2721 
2722 		if (io->esize != sizeof(*ioe)) {
2723 			error = ENODEV;
2724 			break;
2725 		}
2726 		if (io->size < 0 ||
2727 		    io->size > pf_ioctl_maxcount ||
2728 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
2729 			error = EINVAL;
2730 			break;
2731 		}
2732 		totlen = sizeof(struct pfioc_trans_e) * io->size;
2733 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
2734 		    M_TEMP, M_NOWAIT);
2735 		if (! ioes) {
2736 			error = ENOMEM;
2737 			break;
2738 		}
2739 		error = copyin(io->array, ioes, totlen);
2740 		if (error) {
2741 			free(ioes, M_TEMP);
2742 			break;
2743 		}
2744 		PF_RULES_WLOCK();
2745 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
2746 			switch (ioe->rs_num) {
2747 #ifdef ALTQ
2748 			case PF_RULESET_ALTQ:
2749 				if (ioe->anchor[0]) {
2750 					PF_RULES_WUNLOCK();
2751 					free(ioes, M_TEMP);
2752 					error = EINVAL;
2753 					goto fail;
2754 				}
2755 				if ((error = pf_rollback_altq(ioe->ticket))) {
2756 					PF_RULES_WUNLOCK();
2757 					free(ioes, M_TEMP);
2758 					goto fail; /* really bad */
2759 				}
2760 				break;
2761 #endif /* ALTQ */
2762 			case PF_RULESET_TABLE:
2763 			    {
2764 				struct pfr_table table;
2765 
2766 				bzero(&table, sizeof(table));
2767 				strlcpy(table.pfrt_anchor, ioe->anchor,
2768 				    sizeof(table.pfrt_anchor));
2769 				if ((error = pfr_ina_rollback(&table,
2770 				    ioe->ticket, NULL, 0))) {
2771 					PF_RULES_WUNLOCK();
2772 					free(ioes, M_TEMP);
2773 					goto fail; /* really bad */
2774 				}
2775 				break;
2776 			    }
2777 			default:
2778 				if ((error = pf_rollback_rules(ioe->ticket,
2779 				    ioe->rs_num, ioe->anchor))) {
2780 					PF_RULES_WUNLOCK();
2781 					free(ioes, M_TEMP);
2782 					goto fail; /* really bad */
2783 				}
2784 				break;
2785 			}
2786 		}
2787 		PF_RULES_WUNLOCK();
2788 		free(ioes, M_TEMP);
2789 		break;
2790 	}
2791 
2792 	case DIOCXCOMMIT: {
2793 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2794 		struct pfioc_trans_e	*ioe, *ioes;
2795 		struct pf_ruleset	*rs;
2796 		size_t			 totlen;
2797 		int			 i;
2798 
2799 		if (io->esize != sizeof(*ioe)) {
2800 			error = ENODEV;
2801 			break;
2802 		}
2803 
2804 		if (io->size < 0 ||
2805 		    io->size > pf_ioctl_maxcount ||
2806 		    WOULD_OVERFLOW(io->size, sizeof(struct pfioc_trans_e))) {
2807 			error = EINVAL;
2808 			break;
2809 		}
2810 
2811 		totlen = sizeof(struct pfioc_trans_e) * io->size;
2812 		ioes = mallocarray(io->size, sizeof(struct pfioc_trans_e),
2813 		    M_TEMP, M_NOWAIT);
2814 		if (ioes == NULL) {
2815 			error = ENOMEM;
2816 			break;
2817 		}
2818 		error = copyin(io->array, ioes, totlen);
2819 		if (error) {
2820 			free(ioes, M_TEMP);
2821 			break;
2822 		}
2823 		PF_RULES_WLOCK();
2824 		/* First makes sure everything will succeed. */
2825 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
2826 			switch (ioe->rs_num) {
2827 #ifdef ALTQ
2828 			case PF_RULESET_ALTQ:
2829 				if (ioe->anchor[0]) {
2830 					PF_RULES_WUNLOCK();
2831 					free(ioes, M_TEMP);
2832 					error = EINVAL;
2833 					goto fail;
2834 				}
2835 				if (!V_altqs_inactive_open || ioe->ticket !=
2836 				    V_ticket_altqs_inactive) {
2837 					PF_RULES_WUNLOCK();
2838 					free(ioes, M_TEMP);
2839 					error = EBUSY;
2840 					goto fail;
2841 				}
2842 				break;
2843 #endif /* ALTQ */
2844 			case PF_RULESET_TABLE:
2845 				rs = pf_find_ruleset(ioe->anchor);
2846 				if (rs == NULL || !rs->topen || ioe->ticket !=
2847 				    rs->tticket) {
2848 					PF_RULES_WUNLOCK();
2849 					free(ioes, M_TEMP);
2850 					error = EBUSY;
2851 					goto fail;
2852 				}
2853 				break;
2854 			default:
2855 				if (ioe->rs_num < 0 || ioe->rs_num >=
2856 				    PF_RULESET_MAX) {
2857 					PF_RULES_WUNLOCK();
2858 					free(ioes, M_TEMP);
2859 					error = EINVAL;
2860 					goto fail;
2861 				}
2862 				rs = pf_find_ruleset(ioe->anchor);
2863 				if (rs == NULL ||
2864 				    !rs->rules[ioe->rs_num].inactive.open ||
2865 				    rs->rules[ioe->rs_num].inactive.ticket !=
2866 				    ioe->ticket) {
2867 					PF_RULES_WUNLOCK();
2868 					free(ioes, M_TEMP);
2869 					error = EBUSY;
2870 					goto fail;
2871 				}
2872 				break;
2873 			}
2874 		}
2875 		/* Now do the commit - no errors should happen here. */
2876 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
2877 			switch (ioe->rs_num) {
2878 #ifdef ALTQ
2879 			case PF_RULESET_ALTQ:
2880 				if ((error = pf_commit_altq(ioe->ticket))) {
2881 					PF_RULES_WUNLOCK();
2882 					free(ioes, M_TEMP);
2883 					goto fail; /* really bad */
2884 				}
2885 				break;
2886 #endif /* ALTQ */
2887 			case PF_RULESET_TABLE:
2888 			    {
2889 				struct pfr_table table;
2890 
2891 				bzero(&table, sizeof(table));
2892 				strlcpy(table.pfrt_anchor, ioe->anchor,
2893 				    sizeof(table.pfrt_anchor));
2894 				if ((error = pfr_ina_commit(&table,
2895 				    ioe->ticket, NULL, NULL, 0))) {
2896 					PF_RULES_WUNLOCK();
2897 					free(ioes, M_TEMP);
2898 					goto fail; /* really bad */
2899 				}
2900 				break;
2901 			    }
2902 			default:
2903 				if ((error = pf_commit_rules(ioe->ticket,
2904 				    ioe->rs_num, ioe->anchor))) {
2905 					PF_RULES_WUNLOCK();
2906 					free(ioes, M_TEMP);
2907 					goto fail; /* really bad */
2908 				}
2909 				break;
2910 			}
2911 		}
2912 		PF_RULES_WUNLOCK();
2913 		free(ioes, M_TEMP);
2914 		break;
2915 	}
2916 
2917 	case DIOCGETSRCNODES: {
2918 		struct pfioc_src_nodes	*psn = (struct pfioc_src_nodes *)addr;
2919 		struct pf_srchash	*sh;
2920 		struct pf_src_node	*n, *p, *pstore;
2921 		uint32_t		 i, nr = 0;
2922 
2923 		if (psn->psn_len == 0) {
2924 			for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
2925 			    i++, sh++) {
2926 				PF_HASHROW_LOCK(sh);
2927 				LIST_FOREACH(n, &sh->nodes, entry)
2928 					nr++;
2929 				PF_HASHROW_UNLOCK(sh);
2930 			}
2931 			psn->psn_len = sizeof(struct pf_src_node) * nr;
2932 			break;
2933 		}
2934 
2935 		p = pstore = malloc(psn->psn_len, M_TEMP, M_WAITOK);
2936 		for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
2937 		    i++, sh++) {
2938 		    PF_HASHROW_LOCK(sh);
2939 		    LIST_FOREACH(n, &sh->nodes, entry) {
2940 			int	secs = time_uptime, diff;
2941 
2942 			if ((nr + 1) * sizeof(*p) > (unsigned)psn->psn_len)
2943 				break;
2944 
2945 			bcopy(n, p, sizeof(struct pf_src_node));
2946 			if (n->rule.ptr != NULL)
2947 				p->rule.nr = n->rule.ptr->nr;
2948 			p->creation = secs - p->creation;
2949 			if (p->expire > secs)
2950 				p->expire -= secs;
2951 			else
2952 				p->expire = 0;
2953 
2954 			/* Adjust the connection rate estimate. */
2955 			diff = secs - n->conn_rate.last;
2956 			if (diff >= n->conn_rate.seconds)
2957 				p->conn_rate.count = 0;
2958 			else
2959 				p->conn_rate.count -=
2960 				    n->conn_rate.count * diff /
2961 				    n->conn_rate.seconds;
2962 			p++;
2963 			nr++;
2964 		    }
2965 		    PF_HASHROW_UNLOCK(sh);
2966 		}
2967 		error = copyout(pstore, psn->psn_src_nodes,
2968 		    sizeof(struct pf_src_node) * nr);
2969 		if (error) {
2970 			free(pstore, M_TEMP);
2971 			break;
2972 		}
2973 		psn->psn_len = sizeof(struct pf_src_node) * nr;
2974 		free(pstore, M_TEMP);
2975 		break;
2976 	}
2977 
2978 	case DIOCCLRSRCNODES: {
2979 
2980 		pf_clear_srcnodes(NULL);
2981 		pf_purge_expired_src_nodes();
2982 		break;
2983 	}
2984 
2985 	case DIOCKILLSRCNODES:
2986 		pf_kill_srcnodes((struct pfioc_src_node_kill *)addr);
2987 		break;
2988 
2989 	case DIOCSETHOSTID: {
2990 		u_int32_t	*hostid = (u_int32_t *)addr;
2991 
2992 		PF_RULES_WLOCK();
2993 		if (*hostid == 0)
2994 			V_pf_status.hostid = arc4random();
2995 		else
2996 			V_pf_status.hostid = *hostid;
2997 		PF_RULES_WUNLOCK();
2998 		break;
2999 	}
3000 
3001 	case DIOCOSFPFLUSH:
3002 		PF_RULES_WLOCK();
3003 		pf_osfp_flush();
3004 		PF_RULES_WUNLOCK();
3005 		break;
3006 
3007 	case DIOCIGETIFACES: {
3008 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
3009 		struct pfi_kif *ifstore;
3010 		size_t bufsiz;
3011 
3012 		if (io->pfiio_esize != sizeof(struct pfi_kif)) {
3013 			error = ENODEV;
3014 			break;
3015 		}
3016 
3017 		if (io->pfiio_size < 0 ||
3018 		    io->pfiio_size > pf_ioctl_maxcount ||
3019 		    WOULD_OVERFLOW(io->pfiio_size, sizeof(struct pfi_kif))) {
3020 			error = EINVAL;
3021 			break;
3022 		}
3023 
3024 		bufsiz = io->pfiio_size * sizeof(struct pfi_kif);
3025 		ifstore = mallocarray(io->pfiio_size, sizeof(struct pfi_kif),
3026 		    M_TEMP, M_NOWAIT);
3027 		if (ifstore == NULL) {
3028 			error = ENOMEM;
3029 			break;
3030 		}
3031 
3032 		PF_RULES_RLOCK();
3033 		pfi_get_ifaces(io->pfiio_name, ifstore, &io->pfiio_size);
3034 		PF_RULES_RUNLOCK();
3035 		error = copyout(ifstore, io->pfiio_buffer, bufsiz);
3036 		free(ifstore, M_TEMP);
3037 		break;
3038 	}
3039 
3040 	case DIOCSETIFFLAG: {
3041 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
3042 
3043 		PF_RULES_WLOCK();
3044 		error = pfi_set_flags(io->pfiio_name, io->pfiio_flags);
3045 		PF_RULES_WUNLOCK();
3046 		break;
3047 	}
3048 
3049 	case DIOCCLRIFFLAG: {
3050 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
3051 
3052 		PF_RULES_WLOCK();
3053 		error = pfi_clear_flags(io->pfiio_name, io->pfiio_flags);
3054 		PF_RULES_WUNLOCK();
3055 		break;
3056 	}
3057 
3058 	default:
3059 		error = ENODEV;
3060 		break;
3061 	}
3062 fail:
3063 	if (sx_xlocked(&pf_ioctl_lock))
3064 		sx_xunlock(&pf_ioctl_lock);
3065 	CURVNET_RESTORE();
3066 
3067 	return (error);
3068 }
3069 
3070 void
3071 pfsync_state_export(struct pfsync_state *sp, struct pf_state *st)
3072 {
3073 	bzero(sp, sizeof(struct pfsync_state));
3074 
3075 	/* copy from state key */
3076 	sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
3077 	sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
3078 	sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
3079 	sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
3080 	sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
3081 	sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
3082 	sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
3083 	sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
3084 	sp->proto = st->key[PF_SK_WIRE]->proto;
3085 	sp->af = st->key[PF_SK_WIRE]->af;
3086 
3087 	/* copy from state */
3088 	strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
3089 	bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));
3090 	sp->creation = htonl(time_uptime - st->creation);
3091 	sp->expire = pf_state_expires(st);
3092 	if (sp->expire <= time_uptime)
3093 		sp->expire = htonl(0);
3094 	else
3095 		sp->expire = htonl(sp->expire - time_uptime);
3096 
3097 	sp->direction = st->direction;
3098 	sp->log = st->log;
3099 	sp->timeout = st->timeout;
3100 	sp->state_flags = st->state_flags;
3101 	if (st->src_node)
3102 		sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
3103 	if (st->nat_src_node)
3104 		sp->sync_flags |= PFSYNC_FLAG_NATSRCNODE;
3105 
3106 	sp->id = st->id;
3107 	sp->creatorid = st->creatorid;
3108 	pf_state_peer_hton(&st->src, &sp->src);
3109 	pf_state_peer_hton(&st->dst, &sp->dst);
3110 
3111 	if (st->rule.ptr == NULL)
3112 		sp->rule = htonl(-1);
3113 	else
3114 		sp->rule = htonl(st->rule.ptr->nr);
3115 	if (st->anchor.ptr == NULL)
3116 		sp->anchor = htonl(-1);
3117 	else
3118 		sp->anchor = htonl(st->anchor.ptr->nr);
3119 	if (st->nat_rule.ptr == NULL)
3120 		sp->nat_rule = htonl(-1);
3121 	else
3122 		sp->nat_rule = htonl(st->nat_rule.ptr->nr);
3123 
3124 	pf_state_counter_hton(st->packets[0], sp->packets[0]);
3125 	pf_state_counter_hton(st->packets[1], sp->packets[1]);
3126 	pf_state_counter_hton(st->bytes[0], sp->bytes[0]);
3127 	pf_state_counter_hton(st->bytes[1], sp->bytes[1]);
3128 
3129 }
3130 
3131 static void
3132 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
3133 {
3134 	struct pfr_ktable *kt;
3135 
3136 	KASSERT(aw->type == PF_ADDR_TABLE, ("%s: type %u", __func__, aw->type));
3137 
3138 	kt = aw->p.tbl;
3139 	if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
3140 		kt = kt->pfrkt_root;
3141 	aw->p.tbl = NULL;
3142 	aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
3143 		kt->pfrkt_cnt : -1;
3144 }
3145 
3146 /*
3147  * XXX - Check for version missmatch!!!
3148  */
3149 static void
3150 pf_clear_states(void)
3151 {
3152 	struct pf_state	*s;
3153 	u_int i;
3154 
3155 	for (i = 0; i <= pf_hashmask; i++) {
3156 		struct pf_idhash *ih = &V_pf_idhash[i];
3157 relock:
3158 		PF_HASHROW_LOCK(ih);
3159 		LIST_FOREACH(s, &ih->states, entry) {
3160 			s->timeout = PFTM_PURGE;
3161 			/* Don't send out individual delete messages. */
3162 			s->state_flags |= PFSTATE_NOSYNC;
3163 			pf_unlink_state(s, PF_ENTER_LOCKED);
3164 			goto relock;
3165 		}
3166 		PF_HASHROW_UNLOCK(ih);
3167 	}
3168 }
3169 
3170 static int
3171 pf_clear_tables(void)
3172 {
3173 	struct pfioc_table io;
3174 	int error;
3175 
3176 	bzero(&io, sizeof(io));
3177 
3178 	error = pfr_clr_tables(&io.pfrio_table, &io.pfrio_ndel,
3179 	    io.pfrio_flags);
3180 
3181 	return (error);
3182 }
3183 
3184 static void
3185 pf_clear_srcnodes(struct pf_src_node *n)
3186 {
3187 	struct pf_state *s;
3188 	int i;
3189 
3190 	for (i = 0; i <= pf_hashmask; i++) {
3191 		struct pf_idhash *ih = &V_pf_idhash[i];
3192 
3193 		PF_HASHROW_LOCK(ih);
3194 		LIST_FOREACH(s, &ih->states, entry) {
3195 			if (n == NULL || n == s->src_node)
3196 				s->src_node = NULL;
3197 			if (n == NULL || n == s->nat_src_node)
3198 				s->nat_src_node = NULL;
3199 		}
3200 		PF_HASHROW_UNLOCK(ih);
3201 	}
3202 
3203 	if (n == NULL) {
3204 		struct pf_srchash *sh;
3205 
3206 		for (i = 0, sh = V_pf_srchash; i <= pf_srchashmask;
3207 		    i++, sh++) {
3208 			PF_HASHROW_LOCK(sh);
3209 			LIST_FOREACH(n, &sh->nodes, entry) {
3210 				n->expire = 1;
3211 				n->states = 0;
3212 			}
3213 			PF_HASHROW_UNLOCK(sh);
3214 		}
3215 	} else {
3216 		/* XXX: hash slot should already be locked here. */
3217 		n->expire = 1;
3218 		n->states = 0;
3219 	}
3220 }
3221 
3222 static void
3223 pf_kill_srcnodes(struct pfioc_src_node_kill *psnk)
3224 {
3225 	struct pf_src_node_list	 kill;
3226 
3227 	LIST_INIT(&kill);
3228 	for (int i = 0; i <= pf_srchashmask; i++) {
3229 		struct pf_srchash *sh = &V_pf_srchash[i];
3230 		struct pf_src_node *sn, *tmp;
3231 
3232 		PF_HASHROW_LOCK(sh);
3233 		LIST_FOREACH_SAFE(sn, &sh->nodes, entry, tmp)
3234 			if (PF_MATCHA(psnk->psnk_src.neg,
3235 			      &psnk->psnk_src.addr.v.a.addr,
3236 			      &psnk->psnk_src.addr.v.a.mask,
3237 			      &sn->addr, sn->af) &&
3238 			    PF_MATCHA(psnk->psnk_dst.neg,
3239 			      &psnk->psnk_dst.addr.v.a.addr,
3240 			      &psnk->psnk_dst.addr.v.a.mask,
3241 			      &sn->raddr, sn->af)) {
3242 				pf_unlink_src_node(sn);
3243 				LIST_INSERT_HEAD(&kill, sn, entry);
3244 				sn->expire = 1;
3245 			}
3246 		PF_HASHROW_UNLOCK(sh);
3247 	}
3248 
3249 	for (int i = 0; i <= pf_hashmask; i++) {
3250 		struct pf_idhash *ih = &V_pf_idhash[i];
3251 		struct pf_state *s;
3252 
3253 		PF_HASHROW_LOCK(ih);
3254 		LIST_FOREACH(s, &ih->states, entry) {
3255 			if (s->src_node && s->src_node->expire == 1)
3256 				s->src_node = NULL;
3257 			if (s->nat_src_node && s->nat_src_node->expire == 1)
3258 				s->nat_src_node = NULL;
3259 		}
3260 		PF_HASHROW_UNLOCK(ih);
3261 	}
3262 
3263 	psnk->psnk_killed = pf_free_src_nodes(&kill);
3264 }
3265 
3266 /*
3267  * XXX - Check for version missmatch!!!
3268  */
3269 
3270 /*
3271  * Duplicate pfctl -Fa operation to get rid of as much as we can.
3272  */
3273 static int
3274 shutdown_pf(void)
3275 {
3276 	int error = 0;
3277 	u_int32_t t[5];
3278 	char nn = '\0';
3279 
3280 	do {
3281 		if ((error = pf_begin_rules(&t[0], PF_RULESET_SCRUB, &nn))
3282 		    != 0) {
3283 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: SCRUB\n"));
3284 			break;
3285 		}
3286 		if ((error = pf_begin_rules(&t[1], PF_RULESET_FILTER, &nn))
3287 		    != 0) {
3288 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: FILTER\n"));
3289 			break;		/* XXX: rollback? */
3290 		}
3291 		if ((error = pf_begin_rules(&t[2], PF_RULESET_NAT, &nn))
3292 		    != 0) {
3293 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: NAT\n"));
3294 			break;		/* XXX: rollback? */
3295 		}
3296 		if ((error = pf_begin_rules(&t[3], PF_RULESET_BINAT, &nn))
3297 		    != 0) {
3298 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: BINAT\n"));
3299 			break;		/* XXX: rollback? */
3300 		}
3301 		if ((error = pf_begin_rules(&t[4], PF_RULESET_RDR, &nn))
3302 		    != 0) {
3303 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: RDR\n"));
3304 			break;		/* XXX: rollback? */
3305 		}
3306 
3307 		/* XXX: these should always succeed here */
3308 		pf_commit_rules(t[0], PF_RULESET_SCRUB, &nn);
3309 		pf_commit_rules(t[1], PF_RULESET_FILTER, &nn);
3310 		pf_commit_rules(t[2], PF_RULESET_NAT, &nn);
3311 		pf_commit_rules(t[3], PF_RULESET_BINAT, &nn);
3312 		pf_commit_rules(t[4], PF_RULESET_RDR, &nn);
3313 
3314 		if ((error = pf_clear_tables()) != 0)
3315 			break;
3316 
3317 #ifdef ALTQ
3318 		if ((error = pf_begin_altq(&t[0])) != 0) {
3319 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: ALTQ\n"));
3320 			break;
3321 		}
3322 		pf_commit_altq(t[0]);
3323 #endif
3324 
3325 		pf_clear_states();
3326 
3327 		pf_clear_srcnodes(NULL);
3328 
3329 		/* status does not use malloced mem so no need to cleanup */
3330 		/* fingerprints and interfaces have their own cleanup code */
3331 
3332 		/* Free counters last as we updated them during shutdown. */
3333 		counter_u64_free(V_pf_default_rule.states_cur);
3334 		counter_u64_free(V_pf_default_rule.states_tot);
3335 		counter_u64_free(V_pf_default_rule.src_nodes);
3336 
3337 		for (int i = 0; i < PFRES_MAX; i++)
3338 			counter_u64_free(V_pf_status.counters[i]);
3339 		for (int i = 0; i < LCNT_MAX; i++)
3340 			counter_u64_free(V_pf_status.lcounters[i]);
3341 		for (int i = 0; i < FCNT_MAX; i++)
3342 			counter_u64_free(V_pf_status.fcounters[i]);
3343 		for (int i = 0; i < SCNT_MAX; i++)
3344 			counter_u64_free(V_pf_status.scounters[i]);
3345 	} while(0);
3346 
3347 	return (error);
3348 }
3349 
3350 #ifdef INET
3351 static int
3352 pf_check_in(void *arg, struct mbuf **m, struct ifnet *ifp, int dir, int flags,
3353     struct inpcb *inp)
3354 {
3355 	int chk;
3356 
3357 	chk = pf_test(PF_IN, flags, ifp, m, inp);
3358 	if (chk && *m) {
3359 		m_freem(*m);
3360 		*m = NULL;
3361 	}
3362 
3363 	if (chk != PF_PASS)
3364 		return (EACCES);
3365 	return (0);
3366 }
3367 
3368 static int
3369 pf_check_out(void *arg, struct mbuf **m, struct ifnet *ifp, int dir, int flags,
3370     struct inpcb *inp)
3371 {
3372 	int chk;
3373 
3374 	chk = pf_test(PF_OUT, flags, ifp, m, inp);
3375 	if (chk && *m) {
3376 		m_freem(*m);
3377 		*m = NULL;
3378 	}
3379 
3380 	if (chk != PF_PASS)
3381 		return (EACCES);
3382 	return (0);
3383 }
3384 #endif
3385 
3386 #ifdef INET6
3387 static int
3388 pf_check6_in(void *arg, struct mbuf **m, struct ifnet *ifp, int dir, int flags,
3389     struct inpcb *inp)
3390 {
3391 	int chk;
3392 
3393 	/*
3394 	 * In case of loopback traffic IPv6 uses the real interface in
3395 	 * order to support scoped addresses. In order to support stateful
3396 	 * filtering we have change this to lo0 as it is the case in IPv4.
3397 	 */
3398 	CURVNET_SET(ifp->if_vnet);
3399 	chk = pf_test6(PF_IN, flags, (*m)->m_flags & M_LOOP ? V_loif : ifp, m, inp);
3400 	CURVNET_RESTORE();
3401 	if (chk && *m) {
3402 		m_freem(*m);
3403 		*m = NULL;
3404 	}
3405 	if (chk != PF_PASS)
3406 		return (EACCES);
3407 	return (0);
3408 }
3409 
3410 static int
3411 pf_check6_out(void *arg, struct mbuf **m, struct ifnet *ifp, int dir, int flags,
3412     struct inpcb *inp)
3413 {
3414 	int chk;
3415 
3416 	CURVNET_SET(ifp->if_vnet);
3417 	chk = pf_test6(PF_OUT, flags, ifp, m, inp);
3418 	CURVNET_RESTORE();
3419 	if (chk && *m) {
3420 		m_freem(*m);
3421 		*m = NULL;
3422 	}
3423 	if (chk != PF_PASS)
3424 		return (EACCES);
3425 	return (0);
3426 }
3427 #endif /* INET6 */
3428 
3429 static int
3430 hook_pf(void)
3431 {
3432 #ifdef INET
3433 	struct pfil_head *pfh_inet;
3434 #endif
3435 #ifdef INET6
3436 	struct pfil_head *pfh_inet6;
3437 #endif
3438 
3439 	if (V_pf_pfil_hooked)
3440 		return (0);
3441 
3442 #ifdef INET
3443 	pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
3444 	if (pfh_inet == NULL)
3445 		return (ESRCH); /* XXX */
3446 	pfil_add_hook_flags(pf_check_in, NULL, PFIL_IN | PFIL_WAITOK, pfh_inet);
3447 	pfil_add_hook_flags(pf_check_out, NULL, PFIL_OUT | PFIL_WAITOK, pfh_inet);
3448 #endif
3449 #ifdef INET6
3450 	pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
3451 	if (pfh_inet6 == NULL) {
3452 #ifdef INET
3453 		pfil_remove_hook_flags(pf_check_in, NULL, PFIL_IN | PFIL_WAITOK,
3454 		    pfh_inet);
3455 		pfil_remove_hook_flags(pf_check_out, NULL, PFIL_OUT | PFIL_WAITOK,
3456 		    pfh_inet);
3457 #endif
3458 		return (ESRCH); /* XXX */
3459 	}
3460 	pfil_add_hook_flags(pf_check6_in, NULL, PFIL_IN | PFIL_WAITOK, pfh_inet6);
3461 	pfil_add_hook_flags(pf_check6_out, NULL, PFIL_OUT | PFIL_WAITOK, pfh_inet6);
3462 #endif
3463 
3464 	V_pf_pfil_hooked = 1;
3465 	return (0);
3466 }
3467 
3468 static int
3469 dehook_pf(void)
3470 {
3471 #ifdef INET
3472 	struct pfil_head *pfh_inet;
3473 #endif
3474 #ifdef INET6
3475 	struct pfil_head *pfh_inet6;
3476 #endif
3477 
3478 	if (V_pf_pfil_hooked == 0)
3479 		return (0);
3480 
3481 #ifdef INET
3482 	pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
3483 	if (pfh_inet == NULL)
3484 		return (ESRCH); /* XXX */
3485 	pfil_remove_hook_flags(pf_check_in, NULL, PFIL_IN | PFIL_WAITOK,
3486 	    pfh_inet);
3487 	pfil_remove_hook_flags(pf_check_out, NULL, PFIL_OUT | PFIL_WAITOK,
3488 	    pfh_inet);
3489 #endif
3490 #ifdef INET6
3491 	pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
3492 	if (pfh_inet6 == NULL)
3493 		return (ESRCH); /* XXX */
3494 	pfil_remove_hook_flags(pf_check6_in, NULL, PFIL_IN | PFIL_WAITOK,
3495 	    pfh_inet6);
3496 	pfil_remove_hook_flags(pf_check6_out, NULL, PFIL_OUT | PFIL_WAITOK,
3497 	    pfh_inet6);
3498 #endif
3499 
3500 	V_pf_pfil_hooked = 0;
3501 	return (0);
3502 }
3503 
3504 static void
3505 pf_load_vnet(void)
3506 {
3507 	TAILQ_INIT(&V_pf_tags);
3508 	TAILQ_INIT(&V_pf_qids);
3509 
3510 	pfattach_vnet();
3511 	V_pf_vnet_active = 1;
3512 }
3513 
3514 static int
3515 pf_load(void)
3516 {
3517 	int error;
3518 
3519 	rm_init(&pf_rules_lock, "pf rulesets");
3520 	sx_init(&pf_ioctl_lock, "pf ioctl");
3521 	sx_init(&pf_end_lock, "pf end thread");
3522 
3523 	pf_mtag_initialize();
3524 
3525 	pf_dev = make_dev(&pf_cdevsw, 0, 0, 0, 0600, PF_NAME);
3526 	if (pf_dev == NULL)
3527 		return (ENOMEM);
3528 
3529 	pf_end_threads = 0;
3530 	error = kproc_create(pf_purge_thread, NULL, &pf_purge_proc, 0, 0, "pf purge");
3531 	if (error != 0)
3532 		return (error);
3533 
3534 	pfi_initialize();
3535 
3536 	return (0);
3537 }
3538 
3539 static void
3540 pf_unload_vnet(void)
3541 {
3542 	int error;
3543 
3544 	V_pf_vnet_active = 0;
3545 	V_pf_status.running = 0;
3546 	swi_remove(V_pf_swi_cookie);
3547 	error = dehook_pf();
3548 	if (error) {
3549 		/*
3550 		 * Should not happen!
3551 		 * XXX Due to error code ESRCH, kldunload will show
3552 		 * a message like 'No such process'.
3553 		 */
3554 		printf("%s : pfil unregisteration fail\n", __FUNCTION__);
3555 		return;
3556 	}
3557 
3558 	PF_RULES_WLOCK();
3559 	shutdown_pf();
3560 	PF_RULES_WUNLOCK();
3561 
3562 	pf_unload_vnet_purge();
3563 
3564 	pf_normalize_cleanup();
3565 	PF_RULES_WLOCK();
3566 	pfi_cleanup_vnet();
3567 	PF_RULES_WUNLOCK();
3568 	pfr_cleanup();
3569 	pf_osfp_flush();
3570 	pf_cleanup();
3571 	if (IS_DEFAULT_VNET(curvnet))
3572 		pf_mtag_cleanup();
3573 }
3574 
3575 static void
3576 pf_unload(void)
3577 {
3578 
3579 	sx_xlock(&pf_end_lock);
3580 	pf_end_threads = 1;
3581 	while (pf_end_threads < 2) {
3582 		wakeup_one(pf_purge_thread);
3583 		sx_sleep(pf_purge_proc, &pf_end_lock, 0, "pftmo", 0);
3584 	}
3585 	sx_xunlock(&pf_end_lock);
3586 
3587 	if (pf_dev != NULL)
3588 		destroy_dev(pf_dev);
3589 
3590 	pfi_cleanup();
3591 
3592 	rm_destroy(&pf_rules_lock);
3593 	sx_destroy(&pf_ioctl_lock);
3594 	sx_destroy(&pf_end_lock);
3595 }
3596 
3597 static void
3598 vnet_pf_init(void *unused __unused)
3599 {
3600 
3601 	pf_load_vnet();
3602 }
3603 VNET_SYSINIT(vnet_pf_init, SI_SUB_PROTO_FIREWALL, SI_ORDER_THIRD,
3604     vnet_pf_init, NULL);
3605 
3606 static void
3607 vnet_pf_uninit(const void *unused __unused)
3608 {
3609 
3610 	pf_unload_vnet();
3611 }
3612 SYSUNINIT(pf_unload, SI_SUB_PROTO_FIREWALL, SI_ORDER_SECOND, pf_unload, NULL);
3613 VNET_SYSUNINIT(vnet_pf_uninit, SI_SUB_PROTO_FIREWALL, SI_ORDER_THIRD,
3614     vnet_pf_uninit, NULL);
3615 
3616 
3617 static int
3618 pf_modevent(module_t mod, int type, void *data)
3619 {
3620 	int error = 0;
3621 
3622 	switch(type) {
3623 	case MOD_LOAD:
3624 		error = pf_load();
3625 		break;
3626 	case MOD_UNLOAD:
3627 		/* Handled in SYSUNINIT(pf_unload) to ensure it's done after
3628 		 * the vnet_pf_uninit()s */
3629 		break;
3630 	default:
3631 		error = EINVAL;
3632 		break;
3633 	}
3634 
3635 	return (error);
3636 }
3637 
3638 static moduledata_t pf_mod = {
3639 	"pf",
3640 	pf_modevent,
3641 	0
3642 };
3643 
3644 DECLARE_MODULE(pf, pf_mod, SI_SUB_PROTO_FIREWALL, SI_ORDER_SECOND);
3645 MODULE_VERSION(pf, PF_MODVER);
3646