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