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