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