xref: /freebsd/sys/netpfil/pf/pf_ioctl.c (revision d8b88105c2ccf7686552516877f541efb54fb6c8)
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 			newpa->kif = NULL;
2285 		}
2286 
2287 #define	ERROUT(x)	{ error = (x); goto DIOCCHANGEADDR_error; }
2288 		PF_RULES_WLOCK();
2289 		ruleset = pf_find_ruleset(pca->anchor);
2290 		if (ruleset == NULL)
2291 			ERROUT(EBUSY);
2292 
2293 		pool = pf_get_pool(pca->anchor, pca->ticket, pca->r_action,
2294 		    pca->r_num, pca->r_last, 1, 1);
2295 		if (pool == NULL)
2296 			ERROUT(EBUSY);
2297 
2298 		if (pca->action != PF_CHANGE_REMOVE) {
2299 			if (newpa->ifname[0]) {
2300 				newpa->kif = pfi_kif_attach(kif, newpa->ifname);
2301 				pfi_kif_ref(newpa->kif);
2302 				kif = NULL;
2303 			}
2304 
2305 			switch (newpa->addr.type) {
2306 			case PF_ADDR_DYNIFTL:
2307 				error = pfi_dynaddr_setup(&newpa->addr,
2308 				    pca->af);
2309 				break;
2310 			case PF_ADDR_TABLE:
2311 				newpa->addr.p.tbl = pfr_attach_table(ruleset,
2312 				    newpa->addr.v.tblname);
2313 				if (newpa->addr.p.tbl == NULL)
2314 					error = ENOMEM;
2315 				break;
2316 			}
2317 			if (error)
2318 				goto DIOCCHANGEADDR_error;
2319 		}
2320 
2321 		switch (pca->action) {
2322 		case PF_CHANGE_ADD_HEAD:
2323 			oldpa = TAILQ_FIRST(&pool->list);
2324 			break;
2325 		case PF_CHANGE_ADD_TAIL:
2326 			oldpa = TAILQ_LAST(&pool->list, pf_palist);
2327 			break;
2328 		default:
2329 			oldpa = TAILQ_FIRST(&pool->list);
2330 			for (int i = 0; oldpa && i < pca->nr; i++)
2331 				oldpa = TAILQ_NEXT(oldpa, entries);
2332 
2333 			if (oldpa == NULL)
2334 				ERROUT(EINVAL);
2335 		}
2336 
2337 		if (pca->action == PF_CHANGE_REMOVE) {
2338 			TAILQ_REMOVE(&pool->list, oldpa, entries);
2339 			switch (oldpa->addr.type) {
2340 			case PF_ADDR_DYNIFTL:
2341 				pfi_dynaddr_remove(oldpa->addr.p.dyn);
2342 				break;
2343 			case PF_ADDR_TABLE:
2344 				pfr_detach_table(oldpa->addr.p.tbl);
2345 				break;
2346 			}
2347 			if (oldpa->kif)
2348 				pfi_kif_unref(oldpa->kif);
2349 			free(oldpa, M_PFRULE);
2350 		} else {
2351 			if (oldpa == NULL)
2352 				TAILQ_INSERT_TAIL(&pool->list, newpa, entries);
2353 			else if (pca->action == PF_CHANGE_ADD_HEAD ||
2354 			    pca->action == PF_CHANGE_ADD_BEFORE)
2355 				TAILQ_INSERT_BEFORE(oldpa, newpa, entries);
2356 			else
2357 				TAILQ_INSERT_AFTER(&pool->list, oldpa,
2358 				    newpa, entries);
2359 		}
2360 
2361 		pool->cur = TAILQ_FIRST(&pool->list);
2362 		PF_ACPY(&pool->counter, &pool->cur->addr.v.a.addr, pca->af);
2363 		PF_RULES_WUNLOCK();
2364 		break;
2365 
2366 #undef ERROUT
2367 DIOCCHANGEADDR_error:
2368 		if (newpa->kif)
2369 			pfi_kif_unref(newpa->kif);
2370 		PF_RULES_WUNLOCK();
2371 		if (newpa != NULL)
2372 			free(newpa, M_PFRULE);
2373 		if (kif != NULL)
2374 			free(kif, PFI_MTYPE);
2375 		break;
2376 	}
2377 
2378 	case DIOCGETRULESETS: {
2379 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
2380 		struct pf_ruleset	*ruleset;
2381 		struct pf_anchor	*anchor;
2382 
2383 		PF_RULES_RLOCK();
2384 		pr->path[sizeof(pr->path) - 1] = 0;
2385 		if ((ruleset = pf_find_ruleset(pr->path)) == NULL) {
2386 			PF_RULES_RUNLOCK();
2387 			error = ENOENT;
2388 			break;
2389 		}
2390 		pr->nr = 0;
2391 		if (ruleset->anchor == NULL) {
2392 			/* XXX kludge for pf_main_ruleset */
2393 			RB_FOREACH(anchor, pf_anchor_global, &V_pf_anchors)
2394 				if (anchor->parent == NULL)
2395 					pr->nr++;
2396 		} else {
2397 			RB_FOREACH(anchor, pf_anchor_node,
2398 			    &ruleset->anchor->children)
2399 				pr->nr++;
2400 		}
2401 		PF_RULES_RUNLOCK();
2402 		break;
2403 	}
2404 
2405 	case DIOCGETRULESET: {
2406 		struct pfioc_ruleset	*pr = (struct pfioc_ruleset *)addr;
2407 		struct pf_ruleset	*ruleset;
2408 		struct pf_anchor	*anchor;
2409 		u_int32_t		 nr = 0;
2410 
2411 		PF_RULES_RLOCK();
2412 		pr->path[sizeof(pr->path) - 1] = 0;
2413 		if ((ruleset = pf_find_ruleset(pr->path)) == NULL) {
2414 			PF_RULES_RUNLOCK();
2415 			error = ENOENT;
2416 			break;
2417 		}
2418 		pr->name[0] = 0;
2419 		if (ruleset->anchor == NULL) {
2420 			/* XXX kludge for pf_main_ruleset */
2421 			RB_FOREACH(anchor, pf_anchor_global, &V_pf_anchors)
2422 				if (anchor->parent == NULL && nr++ == pr->nr) {
2423 					strlcpy(pr->name, anchor->name,
2424 					    sizeof(pr->name));
2425 					break;
2426 				}
2427 		} else {
2428 			RB_FOREACH(anchor, pf_anchor_node,
2429 			    &ruleset->anchor->children)
2430 				if (nr++ == pr->nr) {
2431 					strlcpy(pr->name, anchor->name,
2432 					    sizeof(pr->name));
2433 					break;
2434 				}
2435 		}
2436 		if (!pr->name[0])
2437 			error = EBUSY;
2438 		PF_RULES_RUNLOCK();
2439 		break;
2440 	}
2441 
2442 	case DIOCRCLRTABLES: {
2443 		struct pfioc_table *io = (struct pfioc_table *)addr;
2444 
2445 		if (io->pfrio_esize != 0) {
2446 			error = ENODEV;
2447 			break;
2448 		}
2449 		PF_RULES_WLOCK();
2450 		error = pfr_clr_tables(&io->pfrio_table, &io->pfrio_ndel,
2451 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
2452 		PF_RULES_WUNLOCK();
2453 		break;
2454 	}
2455 
2456 	case DIOCRADDTABLES: {
2457 		struct pfioc_table *io = (struct pfioc_table *)addr;
2458 		struct pfr_table *pfrts;
2459 		size_t totlen;
2460 
2461 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2462 			error = ENODEV;
2463 			break;
2464 		}
2465 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2466 		pfrts = malloc(totlen, M_TEMP, M_WAITOK);
2467 		error = copyin(io->pfrio_buffer, pfrts, totlen);
2468 		if (error) {
2469 			free(pfrts, M_TEMP);
2470 			break;
2471 		}
2472 		PF_RULES_WLOCK();
2473 		error = pfr_add_tables(pfrts, io->pfrio_size,
2474 		    &io->pfrio_nadd, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2475 		PF_RULES_WUNLOCK();
2476 		free(pfrts, M_TEMP);
2477 		break;
2478 	}
2479 
2480 	case DIOCRDELTABLES: {
2481 		struct pfioc_table *io = (struct pfioc_table *)addr;
2482 		struct pfr_table *pfrts;
2483 		size_t totlen;
2484 
2485 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2486 			error = ENODEV;
2487 			break;
2488 		}
2489 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2490 		pfrts = malloc(totlen, M_TEMP, M_WAITOK);
2491 		error = copyin(io->pfrio_buffer, pfrts, totlen);
2492 		if (error) {
2493 			free(pfrts, M_TEMP);
2494 			break;
2495 		}
2496 		PF_RULES_WLOCK();
2497 		error = pfr_del_tables(pfrts, io->pfrio_size,
2498 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2499 		PF_RULES_WUNLOCK();
2500 		free(pfrts, M_TEMP);
2501 		break;
2502 	}
2503 
2504 	case DIOCRGETTABLES: {
2505 		struct pfioc_table *io = (struct pfioc_table *)addr;
2506 		struct pfr_table *pfrts;
2507 		size_t totlen;
2508 
2509 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2510 			error = ENODEV;
2511 			break;
2512 		}
2513 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2514 		pfrts = malloc(totlen, M_TEMP, M_WAITOK);
2515 		PF_RULES_RLOCK();
2516 		error = pfr_get_tables(&io->pfrio_table, pfrts,
2517 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2518 		PF_RULES_RUNLOCK();
2519 		if (error == 0)
2520 			error = copyout(pfrts, io->pfrio_buffer, totlen);
2521 		free(pfrts, M_TEMP);
2522 		break;
2523 	}
2524 
2525 	case DIOCRGETTSTATS: {
2526 		struct pfioc_table *io = (struct pfioc_table *)addr;
2527 		struct pfr_tstats *pfrtstats;
2528 		size_t totlen;
2529 
2530 		if (io->pfrio_esize != sizeof(struct pfr_tstats)) {
2531 			error = ENODEV;
2532 			break;
2533 		}
2534 		totlen = io->pfrio_size * sizeof(struct pfr_tstats);
2535 		pfrtstats = malloc(totlen, M_TEMP, M_WAITOK);
2536 		PF_RULES_WLOCK();
2537 		error = pfr_get_tstats(&io->pfrio_table, pfrtstats,
2538 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2539 		PF_RULES_WUNLOCK();
2540 		if (error == 0)
2541 			error = copyout(pfrtstats, io->pfrio_buffer, totlen);
2542 		free(pfrtstats, M_TEMP);
2543 		break;
2544 	}
2545 
2546 	case DIOCRCLRTSTATS: {
2547 		struct pfioc_table *io = (struct pfioc_table *)addr;
2548 		struct pfr_table *pfrts;
2549 		size_t totlen;
2550 
2551 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2552 			error = ENODEV;
2553 			break;
2554 		}
2555 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2556 		pfrts = malloc(totlen, M_TEMP, M_WAITOK);
2557 		error = copyin(io->pfrio_buffer, pfrts, totlen);
2558 		if (error) {
2559 			free(pfrts, M_TEMP);
2560 			break;
2561 		}
2562 		PF_RULES_WLOCK();
2563 		error = pfr_clr_tstats(pfrts, io->pfrio_size,
2564 		    &io->pfrio_nzero, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2565 		PF_RULES_WUNLOCK();
2566 		free(pfrts, M_TEMP);
2567 		break;
2568 	}
2569 
2570 	case DIOCRSETTFLAGS: {
2571 		struct pfioc_table *io = (struct pfioc_table *)addr;
2572 		struct pfr_table *pfrts;
2573 		size_t totlen;
2574 
2575 		if (io->pfrio_esize != sizeof(struct pfr_table)) {
2576 			error = ENODEV;
2577 			break;
2578 		}
2579 		totlen = io->pfrio_size * sizeof(struct pfr_table);
2580 		pfrts = malloc(totlen, M_TEMP, M_WAITOK);
2581 		error = copyin(io->pfrio_buffer, pfrts, totlen);
2582 		if (error) {
2583 			free(pfrts, M_TEMP);
2584 			break;
2585 		}
2586 		PF_RULES_WLOCK();
2587 		error = pfr_set_tflags(pfrts, io->pfrio_size,
2588 		    io->pfrio_setflag, io->pfrio_clrflag, &io->pfrio_nchange,
2589 		    &io->pfrio_ndel, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2590 		PF_RULES_WUNLOCK();
2591 		free(pfrts, M_TEMP);
2592 		break;
2593 	}
2594 
2595 	case DIOCRCLRADDRS: {
2596 		struct pfioc_table *io = (struct pfioc_table *)addr;
2597 
2598 		if (io->pfrio_esize != 0) {
2599 			error = ENODEV;
2600 			break;
2601 		}
2602 		PF_RULES_WLOCK();
2603 		error = pfr_clr_addrs(&io->pfrio_table, &io->pfrio_ndel,
2604 		    io->pfrio_flags | PFR_FLAG_USERIOCTL);
2605 		PF_RULES_WUNLOCK();
2606 		break;
2607 	}
2608 
2609 	case DIOCRADDADDRS: {
2610 		struct pfioc_table *io = (struct pfioc_table *)addr;
2611 		struct pfr_addr *pfras;
2612 		size_t totlen;
2613 
2614 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2615 			error = ENODEV;
2616 			break;
2617 		}
2618 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2619 		pfras = malloc(totlen, M_TEMP, M_WAITOK);
2620 		error = copyin(io->pfrio_buffer, pfras, totlen);
2621 		if (error) {
2622 			free(pfras, M_TEMP);
2623 			break;
2624 		}
2625 		PF_RULES_WLOCK();
2626 		error = pfr_add_addrs(&io->pfrio_table, pfras,
2627 		    io->pfrio_size, &io->pfrio_nadd, io->pfrio_flags |
2628 		    PFR_FLAG_USERIOCTL);
2629 		PF_RULES_WUNLOCK();
2630 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
2631 			error = copyout(pfras, io->pfrio_buffer, totlen);
2632 		free(pfras, M_TEMP);
2633 		break;
2634 	}
2635 
2636 	case DIOCRDELADDRS: {
2637 		struct pfioc_table *io = (struct pfioc_table *)addr;
2638 		struct pfr_addr *pfras;
2639 		size_t totlen;
2640 
2641 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2642 			error = ENODEV;
2643 			break;
2644 		}
2645 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2646 		pfras = malloc(totlen, M_TEMP, M_WAITOK);
2647 		error = copyin(io->pfrio_buffer, pfras, totlen);
2648 		if (error) {
2649 			free(pfras, M_TEMP);
2650 			break;
2651 		}
2652 		PF_RULES_WLOCK();
2653 		error = pfr_del_addrs(&io->pfrio_table, pfras,
2654 		    io->pfrio_size, &io->pfrio_ndel, io->pfrio_flags |
2655 		    PFR_FLAG_USERIOCTL);
2656 		PF_RULES_WUNLOCK();
2657 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
2658 			error = copyout(pfras, io->pfrio_buffer, totlen);
2659 		free(pfras, M_TEMP);
2660 		break;
2661 	}
2662 
2663 	case DIOCRSETADDRS: {
2664 		struct pfioc_table *io = (struct pfioc_table *)addr;
2665 		struct pfr_addr *pfras;
2666 		size_t totlen;
2667 
2668 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2669 			error = ENODEV;
2670 			break;
2671 		}
2672 		totlen = (io->pfrio_size + io->pfrio_size2) *
2673 		    sizeof(struct pfr_addr);
2674 		pfras = malloc(totlen, M_TEMP, M_WAITOK);
2675 		error = copyin(io->pfrio_buffer, pfras, totlen);
2676 		if (error) {
2677 			free(pfras, M_TEMP);
2678 			break;
2679 		}
2680 		PF_RULES_WLOCK();
2681 		error = pfr_set_addrs(&io->pfrio_table, pfras,
2682 		    io->pfrio_size, &io->pfrio_size2, &io->pfrio_nadd,
2683 		    &io->pfrio_ndel, &io->pfrio_nchange, io->pfrio_flags |
2684 		    PFR_FLAG_USERIOCTL, 0);
2685 		PF_RULES_WUNLOCK();
2686 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
2687 			error = copyout(pfras, io->pfrio_buffer, totlen);
2688 		free(pfras, M_TEMP);
2689 		break;
2690 	}
2691 
2692 	case DIOCRGETADDRS: {
2693 		struct pfioc_table *io = (struct pfioc_table *)addr;
2694 		struct pfr_addr *pfras;
2695 		size_t totlen;
2696 
2697 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2698 			error = ENODEV;
2699 			break;
2700 		}
2701 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2702 		pfras = malloc(totlen, M_TEMP, M_WAITOK);
2703 		PF_RULES_RLOCK();
2704 		error = pfr_get_addrs(&io->pfrio_table, pfras,
2705 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2706 		PF_RULES_RUNLOCK();
2707 		if (error == 0)
2708 			error = copyout(pfras, io->pfrio_buffer, totlen);
2709 		free(pfras, M_TEMP);
2710 		break;
2711 	}
2712 
2713 	case DIOCRGETASTATS: {
2714 		struct pfioc_table *io = (struct pfioc_table *)addr;
2715 		struct pfr_astats *pfrastats;
2716 		size_t totlen;
2717 
2718 		if (io->pfrio_esize != sizeof(struct pfr_astats)) {
2719 			error = ENODEV;
2720 			break;
2721 		}
2722 		totlen = io->pfrio_size * sizeof(struct pfr_astats);
2723 		pfrastats = malloc(totlen, M_TEMP, M_WAITOK);
2724 		PF_RULES_RLOCK();
2725 		error = pfr_get_astats(&io->pfrio_table, pfrastats,
2726 		    &io->pfrio_size, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2727 		PF_RULES_RUNLOCK();
2728 		if (error == 0)
2729 			error = copyout(pfrastats, io->pfrio_buffer, totlen);
2730 		free(pfrastats, M_TEMP);
2731 		break;
2732 	}
2733 
2734 	case DIOCRCLRASTATS: {
2735 		struct pfioc_table *io = (struct pfioc_table *)addr;
2736 		struct pfr_addr *pfras;
2737 		size_t totlen;
2738 
2739 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2740 			error = ENODEV;
2741 			break;
2742 		}
2743 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2744 		pfras = malloc(totlen, M_TEMP, M_WAITOK);
2745 		error = copyin(io->pfrio_buffer, pfras, totlen);
2746 		if (error) {
2747 			free(pfras, M_TEMP);
2748 			break;
2749 		}
2750 		PF_RULES_WLOCK();
2751 		error = pfr_clr_astats(&io->pfrio_table, pfras,
2752 		    io->pfrio_size, &io->pfrio_nzero, io->pfrio_flags |
2753 		    PFR_FLAG_USERIOCTL);
2754 		PF_RULES_WUNLOCK();
2755 		if (error == 0 && io->pfrio_flags & PFR_FLAG_FEEDBACK)
2756 			error = copyout(pfras, io->pfrio_buffer, totlen);
2757 		free(pfras, M_TEMP);
2758 		break;
2759 	}
2760 
2761 	case DIOCRTSTADDRS: {
2762 		struct pfioc_table *io = (struct pfioc_table *)addr;
2763 		struct pfr_addr *pfras;
2764 		size_t totlen;
2765 
2766 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2767 			error = ENODEV;
2768 			break;
2769 		}
2770 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2771 		pfras = malloc(totlen, M_TEMP, M_WAITOK);
2772 		error = copyin(io->pfrio_buffer, pfras, totlen);
2773 		if (error) {
2774 			free(pfras, M_TEMP);
2775 			break;
2776 		}
2777 		PF_RULES_RLOCK();
2778 		error = pfr_tst_addrs(&io->pfrio_table, pfras,
2779 		    io->pfrio_size, &io->pfrio_nmatch, io->pfrio_flags |
2780 		    PFR_FLAG_USERIOCTL);
2781 		PF_RULES_RUNLOCK();
2782 		if (error == 0)
2783 			error = copyout(pfras, io->pfrio_buffer, totlen);
2784 		free(pfras, M_TEMP);
2785 		break;
2786 	}
2787 
2788 	case DIOCRINADEFINE: {
2789 		struct pfioc_table *io = (struct pfioc_table *)addr;
2790 		struct pfr_addr *pfras;
2791 		size_t totlen;
2792 
2793 		if (io->pfrio_esize != sizeof(struct pfr_addr)) {
2794 			error = ENODEV;
2795 			break;
2796 		}
2797 		totlen = io->pfrio_size * sizeof(struct pfr_addr);
2798 		pfras = malloc(totlen, M_TEMP, M_WAITOK);
2799 		error = copyin(io->pfrio_buffer, pfras, totlen);
2800 		if (error) {
2801 			free(pfras, M_TEMP);
2802 			break;
2803 		}
2804 		PF_RULES_WLOCK();
2805 		error = pfr_ina_define(&io->pfrio_table, pfras,
2806 		    io->pfrio_size, &io->pfrio_nadd, &io->pfrio_naddr,
2807 		    io->pfrio_ticket, io->pfrio_flags | PFR_FLAG_USERIOCTL);
2808 		PF_RULES_WUNLOCK();
2809 		free(pfras, M_TEMP);
2810 		break;
2811 	}
2812 
2813 	case DIOCOSFPADD: {
2814 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
2815 		PF_RULES_WLOCK();
2816 		error = pf_osfp_add(io);
2817 		PF_RULES_WUNLOCK();
2818 		break;
2819 	}
2820 
2821 	case DIOCOSFPGET: {
2822 		struct pf_osfp_ioctl *io = (struct pf_osfp_ioctl *)addr;
2823 		PF_RULES_RLOCK();
2824 		error = pf_osfp_get(io);
2825 		PF_RULES_RUNLOCK();
2826 		break;
2827 	}
2828 
2829 	case DIOCXBEGIN: {
2830 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2831 		struct pfioc_trans_e	*ioes, *ioe;
2832 		size_t			 totlen;
2833 		int			 i;
2834 
2835 		if (io->esize != sizeof(*ioe)) {
2836 			error = ENODEV;
2837 			break;
2838 		}
2839 		totlen = sizeof(struct pfioc_trans_e) * io->size;
2840 		ioes = malloc(totlen, M_TEMP, M_WAITOK);
2841 		error = copyin(io->array, ioes, totlen);
2842 		if (error) {
2843 			free(ioes, M_TEMP);
2844 			break;
2845 		}
2846 		PF_RULES_WLOCK();
2847 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
2848 			switch (ioe->rs_num) {
2849 #ifdef ALTQ
2850 			case PF_RULESET_ALTQ:
2851 				if (ioe->anchor[0]) {
2852 					PF_RULES_WUNLOCK();
2853 					free(ioes, M_TEMP);
2854 					error = EINVAL;
2855 					goto fail;
2856 				}
2857 				if ((error = pf_begin_altq(&ioe->ticket))) {
2858 					PF_RULES_WUNLOCK();
2859 					free(ioes, M_TEMP);
2860 					goto fail;
2861 				}
2862 				break;
2863 #endif /* ALTQ */
2864 			case PF_RULESET_TABLE:
2865 			    {
2866 				struct pfr_table table;
2867 
2868 				bzero(&table, sizeof(table));
2869 				strlcpy(table.pfrt_anchor, ioe->anchor,
2870 				    sizeof(table.pfrt_anchor));
2871 				if ((error = pfr_ina_begin(&table,
2872 				    &ioe->ticket, NULL, 0))) {
2873 					PF_RULES_WUNLOCK();
2874 					free(ioes, M_TEMP);
2875 					goto fail;
2876 				}
2877 				break;
2878 			    }
2879 			default:
2880 				if ((error = pf_begin_rules(&ioe->ticket,
2881 				    ioe->rs_num, ioe->anchor))) {
2882 					PF_RULES_WUNLOCK();
2883 					free(ioes, M_TEMP);
2884 					goto fail;
2885 				}
2886 				break;
2887 			}
2888 		}
2889 		PF_RULES_WUNLOCK();
2890 		error = copyout(ioes, io->array, totlen);
2891 		free(ioes, M_TEMP);
2892 		break;
2893 	}
2894 
2895 	case DIOCXROLLBACK: {
2896 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2897 		struct pfioc_trans_e	*ioe, *ioes;
2898 		size_t			 totlen;
2899 		int			 i;
2900 
2901 		if (io->esize != sizeof(*ioe)) {
2902 			error = ENODEV;
2903 			break;
2904 		}
2905 		totlen = sizeof(struct pfioc_trans_e) * io->size;
2906 		ioes = malloc(totlen, M_TEMP, M_WAITOK);
2907 		error = copyin(io->array, ioes, totlen);
2908 		if (error) {
2909 			free(ioes, M_TEMP);
2910 			break;
2911 		}
2912 		PF_RULES_WLOCK();
2913 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
2914 			switch (ioe->rs_num) {
2915 #ifdef ALTQ
2916 			case PF_RULESET_ALTQ:
2917 				if (ioe->anchor[0]) {
2918 					PF_RULES_WUNLOCK();
2919 					free(ioes, M_TEMP);
2920 					error = EINVAL;
2921 					goto fail;
2922 				}
2923 				if ((error = pf_rollback_altq(ioe->ticket))) {
2924 					PF_RULES_WUNLOCK();
2925 					free(ioes, M_TEMP);
2926 					goto fail; /* really bad */
2927 				}
2928 				break;
2929 #endif /* ALTQ */
2930 			case PF_RULESET_TABLE:
2931 			    {
2932 				struct pfr_table table;
2933 
2934 				bzero(&table, sizeof(table));
2935 				strlcpy(table.pfrt_anchor, ioe->anchor,
2936 				    sizeof(table.pfrt_anchor));
2937 				if ((error = pfr_ina_rollback(&table,
2938 				    ioe->ticket, NULL, 0))) {
2939 					PF_RULES_WUNLOCK();
2940 					free(ioes, M_TEMP);
2941 					goto fail; /* really bad */
2942 				}
2943 				break;
2944 			    }
2945 			default:
2946 				if ((error = pf_rollback_rules(ioe->ticket,
2947 				    ioe->rs_num, ioe->anchor))) {
2948 					PF_RULES_WUNLOCK();
2949 					free(ioes, M_TEMP);
2950 					goto fail; /* really bad */
2951 				}
2952 				break;
2953 			}
2954 		}
2955 		PF_RULES_WUNLOCK();
2956 		free(ioes, M_TEMP);
2957 		break;
2958 	}
2959 
2960 	case DIOCXCOMMIT: {
2961 		struct pfioc_trans	*io = (struct pfioc_trans *)addr;
2962 		struct pfioc_trans_e	*ioe, *ioes;
2963 		struct pf_ruleset	*rs;
2964 		size_t			 totlen;
2965 		int			 i;
2966 
2967 		if (io->esize != sizeof(*ioe)) {
2968 			error = ENODEV;
2969 			break;
2970 		}
2971 		totlen = sizeof(struct pfioc_trans_e) * io->size;
2972 		ioes = malloc(totlen, M_TEMP, M_WAITOK);
2973 		error = copyin(io->array, ioes, totlen);
2974 		if (error) {
2975 			free(ioes, M_TEMP);
2976 			break;
2977 		}
2978 		PF_RULES_WLOCK();
2979 		/* First makes sure everything will succeed. */
2980 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
2981 			switch (ioe->rs_num) {
2982 #ifdef ALTQ
2983 			case PF_RULESET_ALTQ:
2984 				if (ioe->anchor[0]) {
2985 					PF_RULES_WUNLOCK();
2986 					free(ioes, M_TEMP);
2987 					error = EINVAL;
2988 					goto fail;
2989 				}
2990 				if (!V_altqs_inactive_open || ioe->ticket !=
2991 				    V_ticket_altqs_inactive) {
2992 					PF_RULES_WUNLOCK();
2993 					free(ioes, M_TEMP);
2994 					error = EBUSY;
2995 					goto fail;
2996 				}
2997 				break;
2998 #endif /* ALTQ */
2999 			case PF_RULESET_TABLE:
3000 				rs = pf_find_ruleset(ioe->anchor);
3001 				if (rs == NULL || !rs->topen || ioe->ticket !=
3002 				    rs->tticket) {
3003 					PF_RULES_WUNLOCK();
3004 					free(ioes, M_TEMP);
3005 					error = EBUSY;
3006 					goto fail;
3007 				}
3008 				break;
3009 			default:
3010 				if (ioe->rs_num < 0 || ioe->rs_num >=
3011 				    PF_RULESET_MAX) {
3012 					PF_RULES_WUNLOCK();
3013 					free(ioes, M_TEMP);
3014 					error = EINVAL;
3015 					goto fail;
3016 				}
3017 				rs = pf_find_ruleset(ioe->anchor);
3018 				if (rs == NULL ||
3019 				    !rs->rules[ioe->rs_num].inactive.open ||
3020 				    rs->rules[ioe->rs_num].inactive.ticket !=
3021 				    ioe->ticket) {
3022 					PF_RULES_WUNLOCK();
3023 					free(ioes, M_TEMP);
3024 					error = EBUSY;
3025 					goto fail;
3026 				}
3027 				break;
3028 			}
3029 		}
3030 		/* Now do the commit - no errors should happen here. */
3031 		for (i = 0, ioe = ioes; i < io->size; i++, ioe++) {
3032 			switch (ioe->rs_num) {
3033 #ifdef ALTQ
3034 			case PF_RULESET_ALTQ:
3035 				if ((error = pf_commit_altq(ioe->ticket))) {
3036 					PF_RULES_WUNLOCK();
3037 					free(ioes, M_TEMP);
3038 					goto fail; /* really bad */
3039 				}
3040 				break;
3041 #endif /* ALTQ */
3042 			case PF_RULESET_TABLE:
3043 			    {
3044 				struct pfr_table table;
3045 
3046 				bzero(&table, sizeof(table));
3047 				strlcpy(table.pfrt_anchor, ioe->anchor,
3048 				    sizeof(table.pfrt_anchor));
3049 				if ((error = pfr_ina_commit(&table,
3050 				    ioe->ticket, NULL, NULL, 0))) {
3051 					PF_RULES_WUNLOCK();
3052 					free(ioes, M_TEMP);
3053 					goto fail; /* really bad */
3054 				}
3055 				break;
3056 			    }
3057 			default:
3058 				if ((error = pf_commit_rules(ioe->ticket,
3059 				    ioe->rs_num, ioe->anchor))) {
3060 					PF_RULES_WUNLOCK();
3061 					free(ioes, M_TEMP);
3062 					goto fail; /* really bad */
3063 				}
3064 				break;
3065 			}
3066 		}
3067 		PF_RULES_WUNLOCK();
3068 		free(ioes, M_TEMP);
3069 		break;
3070 	}
3071 
3072 	case DIOCGETSRCNODES: {
3073 		struct pfioc_src_nodes	*psn = (struct pfioc_src_nodes *)addr;
3074 		struct pf_srchash	*sh;
3075 		struct pf_src_node	*n, *p, *pstore;
3076 		uint32_t		 i, nr = 0;
3077 
3078 		if (psn->psn_len == 0) {
3079 			for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask;
3080 			    i++, sh++) {
3081 				PF_HASHROW_LOCK(sh);
3082 				LIST_FOREACH(n, &sh->nodes, entry)
3083 					nr++;
3084 				PF_HASHROW_UNLOCK(sh);
3085 			}
3086 			psn->psn_len = sizeof(struct pf_src_node) * nr;
3087 			break;
3088 		}
3089 
3090 		p = pstore = malloc(psn->psn_len, M_TEMP, M_WAITOK);
3091 		for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask;
3092 		    i++, sh++) {
3093 		    PF_HASHROW_LOCK(sh);
3094 		    LIST_FOREACH(n, &sh->nodes, entry) {
3095 			int	secs = time_uptime, diff;
3096 
3097 			if ((nr + 1) * sizeof(*p) > (unsigned)psn->psn_len)
3098 				break;
3099 
3100 			bcopy(n, p, sizeof(struct pf_src_node));
3101 			if (n->rule.ptr != NULL)
3102 				p->rule.nr = n->rule.ptr->nr;
3103 			p->creation = secs - p->creation;
3104 			if (p->expire > secs)
3105 				p->expire -= secs;
3106 			else
3107 				p->expire = 0;
3108 
3109 			/* Adjust the connection rate estimate. */
3110 			diff = secs - n->conn_rate.last;
3111 			if (diff >= n->conn_rate.seconds)
3112 				p->conn_rate.count = 0;
3113 			else
3114 				p->conn_rate.count -=
3115 				    n->conn_rate.count * diff /
3116 				    n->conn_rate.seconds;
3117 			p++;
3118 			nr++;
3119 		    }
3120 		    PF_HASHROW_UNLOCK(sh);
3121 		}
3122 		error = copyout(pstore, psn->psn_src_nodes,
3123 		    sizeof(struct pf_src_node) * nr);
3124 		if (error) {
3125 			free(pstore, M_TEMP);
3126 			break;
3127 		}
3128 		psn->psn_len = sizeof(struct pf_src_node) * nr;
3129 		free(pstore, M_TEMP);
3130 		break;
3131 	}
3132 
3133 	case DIOCCLRSRCNODES: {
3134 
3135 		pf_clear_srcnodes(NULL);
3136 		pf_purge_expired_src_nodes();
3137 		V_pf_status.src_nodes = 0;
3138 		break;
3139 	}
3140 
3141 	case DIOCKILLSRCNODES:
3142 		pf_kill_srcnodes((struct pfioc_src_node_kill *)addr);
3143 		break;
3144 
3145 	case DIOCSETHOSTID: {
3146 		u_int32_t	*hostid = (u_int32_t *)addr;
3147 
3148 		PF_RULES_WLOCK();
3149 		if (*hostid == 0)
3150 			V_pf_status.hostid = arc4random();
3151 		else
3152 			V_pf_status.hostid = *hostid;
3153 		PF_RULES_WUNLOCK();
3154 		break;
3155 	}
3156 
3157 	case DIOCOSFPFLUSH:
3158 		PF_RULES_WLOCK();
3159 		pf_osfp_flush();
3160 		PF_RULES_WUNLOCK();
3161 		break;
3162 
3163 	case DIOCIGETIFACES: {
3164 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
3165 		struct pfi_kif *ifstore;
3166 		size_t bufsiz;
3167 
3168 		if (io->pfiio_esize != sizeof(struct pfi_kif)) {
3169 			error = ENODEV;
3170 			break;
3171 		}
3172 
3173 		bufsiz = io->pfiio_size * sizeof(struct pfi_kif);
3174 		ifstore = malloc(bufsiz, M_TEMP, M_WAITOK);
3175 		PF_RULES_RLOCK();
3176 		pfi_get_ifaces(io->pfiio_name, ifstore, &io->pfiio_size);
3177 		PF_RULES_RUNLOCK();
3178 		error = copyout(ifstore, io->pfiio_buffer, bufsiz);
3179 		free(ifstore, M_TEMP);
3180 		break;
3181 	}
3182 
3183 	case DIOCSETIFFLAG: {
3184 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
3185 
3186 		PF_RULES_WLOCK();
3187 		error = pfi_set_flags(io->pfiio_name, io->pfiio_flags);
3188 		PF_RULES_WUNLOCK();
3189 		break;
3190 	}
3191 
3192 	case DIOCCLRIFFLAG: {
3193 		struct pfioc_iface *io = (struct pfioc_iface *)addr;
3194 
3195 		PF_RULES_WLOCK();
3196 		error = pfi_clear_flags(io->pfiio_name, io->pfiio_flags);
3197 		PF_RULES_WUNLOCK();
3198 		break;
3199 	}
3200 
3201 	default:
3202 		error = ENODEV;
3203 		break;
3204 	}
3205 fail:
3206 	CURVNET_RESTORE();
3207 
3208 	return (error);
3209 }
3210 
3211 void
3212 pfsync_state_export(struct pfsync_state *sp, struct pf_state *st)
3213 {
3214 	bzero(sp, sizeof(struct pfsync_state));
3215 
3216 	/* copy from state key */
3217 	sp->key[PF_SK_WIRE].addr[0] = st->key[PF_SK_WIRE]->addr[0];
3218 	sp->key[PF_SK_WIRE].addr[1] = st->key[PF_SK_WIRE]->addr[1];
3219 	sp->key[PF_SK_WIRE].port[0] = st->key[PF_SK_WIRE]->port[0];
3220 	sp->key[PF_SK_WIRE].port[1] = st->key[PF_SK_WIRE]->port[1];
3221 	sp->key[PF_SK_STACK].addr[0] = st->key[PF_SK_STACK]->addr[0];
3222 	sp->key[PF_SK_STACK].addr[1] = st->key[PF_SK_STACK]->addr[1];
3223 	sp->key[PF_SK_STACK].port[0] = st->key[PF_SK_STACK]->port[0];
3224 	sp->key[PF_SK_STACK].port[1] = st->key[PF_SK_STACK]->port[1];
3225 	sp->proto = st->key[PF_SK_WIRE]->proto;
3226 	sp->af = st->key[PF_SK_WIRE]->af;
3227 
3228 	/* copy from state */
3229 	strlcpy(sp->ifname, st->kif->pfik_name, sizeof(sp->ifname));
3230 	bcopy(&st->rt_addr, &sp->rt_addr, sizeof(sp->rt_addr));
3231 	sp->creation = htonl(time_uptime - st->creation);
3232 	sp->expire = pf_state_expires(st);
3233 	if (sp->expire <= time_uptime)
3234 		sp->expire = htonl(0);
3235 	else
3236 		sp->expire = htonl(sp->expire - time_uptime);
3237 
3238 	sp->direction = st->direction;
3239 	sp->log = st->log;
3240 	sp->timeout = st->timeout;
3241 	sp->state_flags = st->state_flags;
3242 	if (st->src_node)
3243 		sp->sync_flags |= PFSYNC_FLAG_SRCNODE;
3244 	if (st->nat_src_node)
3245 		sp->sync_flags |= PFSYNC_FLAG_NATSRCNODE;
3246 
3247 	sp->id = st->id;
3248 	sp->creatorid = st->creatorid;
3249 	pf_state_peer_hton(&st->src, &sp->src);
3250 	pf_state_peer_hton(&st->dst, &sp->dst);
3251 
3252 	if (st->rule.ptr == NULL)
3253 		sp->rule = htonl(-1);
3254 	else
3255 		sp->rule = htonl(st->rule.ptr->nr);
3256 	if (st->anchor.ptr == NULL)
3257 		sp->anchor = htonl(-1);
3258 	else
3259 		sp->anchor = htonl(st->anchor.ptr->nr);
3260 	if (st->nat_rule.ptr == NULL)
3261 		sp->nat_rule = htonl(-1);
3262 	else
3263 		sp->nat_rule = htonl(st->nat_rule.ptr->nr);
3264 
3265 	pf_state_counter_hton(st->packets[0], sp->packets[0]);
3266 	pf_state_counter_hton(st->packets[1], sp->packets[1]);
3267 	pf_state_counter_hton(st->bytes[0], sp->bytes[0]);
3268 	pf_state_counter_hton(st->bytes[1], sp->bytes[1]);
3269 
3270 }
3271 
3272 static void
3273 pf_tbladdr_copyout(struct pf_addr_wrap *aw)
3274 {
3275 	struct pfr_ktable *kt;
3276 
3277 	KASSERT(aw->type == PF_ADDR_TABLE, ("%s: type %u", __func__, aw->type));
3278 
3279 	kt = aw->p.tbl;
3280 	if (!(kt->pfrkt_flags & PFR_TFLAG_ACTIVE) && kt->pfrkt_root != NULL)
3281 		kt = kt->pfrkt_root;
3282 	aw->p.tbl = NULL;
3283 	aw->p.tblcnt = (kt->pfrkt_flags & PFR_TFLAG_ACTIVE) ?
3284 		kt->pfrkt_cnt : -1;
3285 }
3286 
3287 /*
3288  * XXX - Check for version missmatch!!!
3289  */
3290 static void
3291 pf_clear_states(void)
3292 {
3293 	struct pf_state	*s;
3294 	u_int i;
3295 
3296 	for (i = 0; i <= V_pf_hashmask; i++) {
3297 		struct pf_idhash *ih = &V_pf_idhash[i];
3298 relock:
3299 		PF_HASHROW_LOCK(ih);
3300 		LIST_FOREACH(s, &ih->states, entry) {
3301 			s->timeout = PFTM_PURGE;
3302 			/* Don't send out individual delete messages. */
3303 			s->sync_state = PFSTATE_NOSYNC;
3304 			pf_unlink_state(s, PF_ENTER_LOCKED);
3305 			goto relock;
3306 		}
3307 		PF_HASHROW_UNLOCK(ih);
3308 	}
3309 }
3310 
3311 static int
3312 pf_clear_tables(void)
3313 {
3314 	struct pfioc_table io;
3315 	int error;
3316 
3317 	bzero(&io, sizeof(io));
3318 
3319 	error = pfr_clr_tables(&io.pfrio_table, &io.pfrio_ndel,
3320 	    io.pfrio_flags);
3321 
3322 	return (error);
3323 }
3324 
3325 static void
3326 pf_clear_srcnodes(struct pf_src_node *n)
3327 {
3328 	struct pf_state *s;
3329 	int i;
3330 
3331 	for (i = 0; i <= V_pf_hashmask; i++) {
3332 		struct pf_idhash *ih = &V_pf_idhash[i];
3333 
3334 		PF_HASHROW_LOCK(ih);
3335 		LIST_FOREACH(s, &ih->states, entry) {
3336 			if (n == NULL || n == s->src_node)
3337 				s->src_node = NULL;
3338 			if (n == NULL || n == s->nat_src_node)
3339 				s->nat_src_node = NULL;
3340 		}
3341 		PF_HASHROW_UNLOCK(ih);
3342 	}
3343 
3344 	if (n == NULL) {
3345 		struct pf_srchash *sh;
3346 
3347 		for (i = 0, sh = V_pf_srchash; i <= V_pf_srchashmask;
3348 		    i++, sh++) {
3349 			PF_HASHROW_LOCK(sh);
3350 			LIST_FOREACH(n, &sh->nodes, entry) {
3351 				n->expire = 1;
3352 				n->states = 0;
3353 			}
3354 			PF_HASHROW_UNLOCK(sh);
3355 		}
3356 	} else {
3357 		/* XXX: hash slot should already be locked here. */
3358 		n->expire = 1;
3359 		n->states = 0;
3360 	}
3361 }
3362 
3363 static void
3364 pf_kill_srcnodes(struct pfioc_src_node_kill *psnk)
3365 {
3366 	struct pf_src_node_list	 kill;
3367 
3368 	LIST_INIT(&kill);
3369 	for (int i = 0; i <= V_pf_srchashmask; i++) {
3370 		struct pf_srchash *sh = &V_pf_srchash[i];
3371 		struct pf_src_node *sn, *tmp;
3372 
3373 		PF_HASHROW_LOCK(sh);
3374 		LIST_FOREACH_SAFE(sn, &sh->nodes, entry, tmp)
3375 			if (PF_MATCHA(psnk->psnk_src.neg,
3376 			      &psnk->psnk_src.addr.v.a.addr,
3377 			      &psnk->psnk_src.addr.v.a.mask,
3378 			      &sn->addr, sn->af) &&
3379 			    PF_MATCHA(psnk->psnk_dst.neg,
3380 			      &psnk->psnk_dst.addr.v.a.addr,
3381 			      &psnk->psnk_dst.addr.v.a.mask,
3382 			      &sn->raddr, sn->af)) {
3383 				pf_unlink_src_node_locked(sn);
3384 				LIST_INSERT_HEAD(&kill, sn, entry);
3385 				sn->expire = 1;
3386 			}
3387 		PF_HASHROW_UNLOCK(sh);
3388 	}
3389 
3390 	for (int i = 0; i <= V_pf_hashmask; i++) {
3391 		struct pf_idhash *ih = &V_pf_idhash[i];
3392 		struct pf_state *s;
3393 
3394 		PF_HASHROW_LOCK(ih);
3395 		LIST_FOREACH(s, &ih->states, entry) {
3396 			if (s->src_node && s->src_node->expire == 1) {
3397 #ifdef INVARIANTS
3398 				s->src_node->states--;
3399 #endif
3400 				s->src_node = NULL;
3401 			}
3402 			if (s->nat_src_node && s->nat_src_node->expire == 1) {
3403 #ifdef INVARIANTS
3404 				s->nat_src_node->states--;
3405 #endif
3406 				s->nat_src_node = NULL;
3407 			}
3408 		}
3409 		PF_HASHROW_UNLOCK(ih);
3410 	}
3411 
3412 	psnk->psnk_killed = pf_free_src_nodes(&kill);
3413 }
3414 
3415 /*
3416  * XXX - Check for version missmatch!!!
3417  */
3418 
3419 /*
3420  * Duplicate pfctl -Fa operation to get rid of as much as we can.
3421  */
3422 static int
3423 shutdown_pf(void)
3424 {
3425 	int error = 0;
3426 	u_int32_t t[5];
3427 	char nn = '\0';
3428 
3429 	V_pf_status.running = 0;
3430 	do {
3431 		if ((error = pf_begin_rules(&t[0], PF_RULESET_SCRUB, &nn))
3432 		    != 0) {
3433 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: SCRUB\n"));
3434 			break;
3435 		}
3436 		if ((error = pf_begin_rules(&t[1], PF_RULESET_FILTER, &nn))
3437 		    != 0) {
3438 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: FILTER\n"));
3439 			break;		/* XXX: rollback? */
3440 		}
3441 		if ((error = pf_begin_rules(&t[2], PF_RULESET_NAT, &nn))
3442 		    != 0) {
3443 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: NAT\n"));
3444 			break;		/* XXX: rollback? */
3445 		}
3446 		if ((error = pf_begin_rules(&t[3], PF_RULESET_BINAT, &nn))
3447 		    != 0) {
3448 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: BINAT\n"));
3449 			break;		/* XXX: rollback? */
3450 		}
3451 		if ((error = pf_begin_rules(&t[4], PF_RULESET_RDR, &nn))
3452 		    != 0) {
3453 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: RDR\n"));
3454 			break;		/* XXX: rollback? */
3455 		}
3456 
3457 		/* XXX: these should always succeed here */
3458 		pf_commit_rules(t[0], PF_RULESET_SCRUB, &nn);
3459 		pf_commit_rules(t[1], PF_RULESET_FILTER, &nn);
3460 		pf_commit_rules(t[2], PF_RULESET_NAT, &nn);
3461 		pf_commit_rules(t[3], PF_RULESET_BINAT, &nn);
3462 		pf_commit_rules(t[4], PF_RULESET_RDR, &nn);
3463 
3464 		if ((error = pf_clear_tables()) != 0)
3465 			break;
3466 
3467 #ifdef ALTQ
3468 		if ((error = pf_begin_altq(&t[0])) != 0) {
3469 			DPFPRINTF(PF_DEBUG_MISC, ("shutdown_pf: ALTQ\n"));
3470 			break;
3471 		}
3472 		pf_commit_altq(t[0]);
3473 #endif
3474 
3475 		pf_clear_states();
3476 
3477 		pf_clear_srcnodes(NULL);
3478 
3479 		/* status does not use malloced mem so no need to cleanup */
3480 		/* fingerprints and interfaces have thier own cleanup code */
3481 	} while(0);
3482 
3483 	return (error);
3484 }
3485 
3486 #ifdef INET
3487 static int
3488 pf_check_in(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
3489     struct inpcb *inp)
3490 {
3491 	int chk;
3492 
3493 	chk = pf_test(PF_IN, ifp, m, inp);
3494 	if (chk && *m) {
3495 		m_freem(*m);
3496 		*m = NULL;
3497 	}
3498 
3499 	return (chk);
3500 }
3501 
3502 static int
3503 pf_check_out(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
3504     struct inpcb *inp)
3505 {
3506 	int chk;
3507 
3508 	/* We need a proper CSUM befor we start (s. OpenBSD ip_output) */
3509 	if ((*m)->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
3510 		in_delayed_cksum(*m);
3511 		(*m)->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
3512 	}
3513 
3514 	chk = pf_test(PF_OUT, ifp, m, inp);
3515 	if (chk && *m) {
3516 		m_freem(*m);
3517 		*m = NULL;
3518 	}
3519 
3520 	return (chk);
3521 }
3522 #endif
3523 
3524 #ifdef INET6
3525 static int
3526 pf_check6_in(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
3527     struct inpcb *inp)
3528 {
3529 	int chk;
3530 
3531 	/*
3532 	 * In case of loopback traffic IPv6 uses the real interface in
3533 	 * order to support scoped addresses. In order to support stateful
3534 	 * filtering we have change this to lo0 as it is the case in IPv4.
3535 	 */
3536 	CURVNET_SET(ifp->if_vnet);
3537 	chk = pf_test6(PF_IN, (*m)->m_flags & M_LOOP ? V_loif : ifp, m, inp);
3538 	CURVNET_RESTORE();
3539 	if (chk && *m) {
3540 		m_freem(*m);
3541 		*m = NULL;
3542 	}
3543 	return chk;
3544 }
3545 
3546 static int
3547 pf_check6_out(void *arg, struct mbuf **m, struct ifnet *ifp, int dir,
3548     struct inpcb *inp)
3549 {
3550 	int chk;
3551 
3552 	/* We need a proper CSUM before we start (s. OpenBSD ip_output) */
3553 	if ((*m)->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
3554 #ifdef INET
3555 		/* XXX-BZ copy&paste error from r126261? */
3556 		in_delayed_cksum(*m);
3557 #endif
3558 		(*m)->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
3559 	}
3560 	CURVNET_SET(ifp->if_vnet);
3561 	chk = pf_test6(PF_OUT, ifp, m, inp);
3562 	CURVNET_RESTORE();
3563 	if (chk && *m) {
3564 		m_freem(*m);
3565 		*m = NULL;
3566 	}
3567 	return chk;
3568 }
3569 #endif /* INET6 */
3570 
3571 static int
3572 hook_pf(void)
3573 {
3574 #ifdef INET
3575 	struct pfil_head *pfh_inet;
3576 #endif
3577 #ifdef INET6
3578 	struct pfil_head *pfh_inet6;
3579 #endif
3580 
3581 	if (V_pf_pfil_hooked)
3582 		return (0);
3583 
3584 #ifdef INET
3585 	pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
3586 	if (pfh_inet == NULL)
3587 		return (ESRCH); /* XXX */
3588 	pfil_add_hook(pf_check_in, NULL, PFIL_IN | PFIL_WAITOK, pfh_inet);
3589 	pfil_add_hook(pf_check_out, NULL, PFIL_OUT | PFIL_WAITOK, pfh_inet);
3590 #endif
3591 #ifdef INET6
3592 	pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
3593 	if (pfh_inet6 == NULL) {
3594 #ifdef INET
3595 		pfil_remove_hook(pf_check_in, NULL, PFIL_IN | PFIL_WAITOK,
3596 		    pfh_inet);
3597 		pfil_remove_hook(pf_check_out, NULL, PFIL_OUT | PFIL_WAITOK,
3598 		    pfh_inet);
3599 #endif
3600 		return (ESRCH); /* XXX */
3601 	}
3602 	pfil_add_hook(pf_check6_in, NULL, PFIL_IN | PFIL_WAITOK, pfh_inet6);
3603 	pfil_add_hook(pf_check6_out, NULL, PFIL_OUT | PFIL_WAITOK, pfh_inet6);
3604 #endif
3605 
3606 	V_pf_pfil_hooked = 1;
3607 	return (0);
3608 }
3609 
3610 static int
3611 dehook_pf(void)
3612 {
3613 #ifdef INET
3614 	struct pfil_head *pfh_inet;
3615 #endif
3616 #ifdef INET6
3617 	struct pfil_head *pfh_inet6;
3618 #endif
3619 
3620 	if (V_pf_pfil_hooked == 0)
3621 		return (0);
3622 
3623 #ifdef INET
3624 	pfh_inet = pfil_head_get(PFIL_TYPE_AF, AF_INET);
3625 	if (pfh_inet == NULL)
3626 		return (ESRCH); /* XXX */
3627 	pfil_remove_hook(pf_check_in, NULL, PFIL_IN | PFIL_WAITOK,
3628 	    pfh_inet);
3629 	pfil_remove_hook(pf_check_out, NULL, PFIL_OUT | PFIL_WAITOK,
3630 	    pfh_inet);
3631 #endif
3632 #ifdef INET6
3633 	pfh_inet6 = pfil_head_get(PFIL_TYPE_AF, AF_INET6);
3634 	if (pfh_inet6 == NULL)
3635 		return (ESRCH); /* XXX */
3636 	pfil_remove_hook(pf_check6_in, NULL, PFIL_IN | PFIL_WAITOK,
3637 	    pfh_inet6);
3638 	pfil_remove_hook(pf_check6_out, NULL, PFIL_OUT | PFIL_WAITOK,
3639 	    pfh_inet6);
3640 #endif
3641 
3642 	V_pf_pfil_hooked = 0;
3643 	return (0);
3644 }
3645 
3646 static int
3647 pf_load(void)
3648 {
3649 	int error;
3650 
3651 	VNET_ITERATOR_DECL(vnet_iter);
3652 
3653 	VNET_LIST_RLOCK();
3654 	VNET_FOREACH(vnet_iter) {
3655 		CURVNET_SET(vnet_iter);
3656 		V_pf_pfil_hooked = 0;
3657 		V_pf_end_threads = 0;
3658 		TAILQ_INIT(&V_pf_tags);
3659 		TAILQ_INIT(&V_pf_qids);
3660 		CURVNET_RESTORE();
3661 	}
3662 	VNET_LIST_RUNLOCK();
3663 
3664 	rw_init(&pf_rules_lock, "pf rulesets");
3665 
3666 	pf_dev = make_dev(&pf_cdevsw, 0, 0, 0, 0600, PF_NAME);
3667 	if ((error = pfattach()) != 0)
3668 		return (error);
3669 
3670 	return (0);
3671 }
3672 
3673 static int
3674 pf_unload(void)
3675 {
3676 	int error = 0;
3677 
3678 	PF_RULES_WLOCK();
3679 	V_pf_status.running = 0;
3680 	PF_RULES_WUNLOCK();
3681 	swi_remove(V_pf_swi_cookie);
3682 	error = dehook_pf();
3683 	if (error) {
3684 		/*
3685 		 * Should not happen!
3686 		 * XXX Due to error code ESRCH, kldunload will show
3687 		 * a message like 'No such process'.
3688 		 */
3689 		printf("%s : pfil unregisteration fail\n", __FUNCTION__);
3690 		return error;
3691 	}
3692 	PF_RULES_WLOCK();
3693 	shutdown_pf();
3694 	V_pf_end_threads = 1;
3695 	while (V_pf_end_threads < 2) {
3696 		wakeup_one(pf_purge_thread);
3697 		rw_sleep(pf_purge_thread, &pf_rules_lock, 0, "pftmo", 0);
3698 	}
3699 	pf_normalize_cleanup();
3700 	pfi_cleanup();
3701 	pfr_cleanup();
3702 	pf_osfp_flush();
3703 	pf_cleanup();
3704 	PF_RULES_WUNLOCK();
3705 	destroy_dev(pf_dev);
3706 	rw_destroy(&pf_rules_lock);
3707 
3708 	return (error);
3709 }
3710 
3711 static int
3712 pf_modevent(module_t mod, int type, void *data)
3713 {
3714 	int error = 0;
3715 
3716 	switch(type) {
3717 	case MOD_LOAD:
3718 		error = pf_load();
3719 		break;
3720 	case MOD_QUIESCE:
3721 		/*
3722 		 * Module should not be unloaded due to race conditions.
3723 		 */
3724 		error = EBUSY;
3725 		break;
3726 	case MOD_UNLOAD:
3727 		error = pf_unload();
3728 		break;
3729 	default:
3730 		error = EINVAL;
3731 		break;
3732 	}
3733 
3734 	return (error);
3735 }
3736 
3737 static moduledata_t pf_mod = {
3738 	"pf",
3739 	pf_modevent,
3740 	0
3741 };
3742 
3743 DECLARE_MODULE(pf, pf_mod, SI_SUB_PSEUDO, SI_ORDER_FIRST);
3744 MODULE_VERSION(pf, PF_MODVER);
3745