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