Home | History | Annotate | Line # | Download | only in pfctl
pfctl_optimize.c revision 1.1
      1 /*	$OpenBSD: pfctl_optimize.c,v 1.2 2004/08/08 19:04:25 deraadt Exp $ */
      2 
      3 /*
      4  * Copyright (c) 2004 Mike Frantzen <frantzen (at) openbsd.org>
      5  *
      6  * Permission to use, copy, modify, and distribute this software for any
      7  * purpose with or without fee is hereby granted, provided that the above
      8  * copyright notice and this permission notice appear in all copies.
      9  *
     10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     17  */
     18 
     19 #include <sys/types.h>
     20 #include <sys/ioctl.h>
     21 #include <sys/socket.h>
     22 
     23 #include <net/if.h>
     24 #include <net/pfvar.h>
     25 
     26 #include <netinet/in.h>
     27 #include <arpa/inet.h>
     28 
     29 #include <assert.h>
     30 #include <ctype.h>
     31 #include <err.h>
     32 #include <errno.h>
     33 #include <stddef.h>
     34 #include <stdio.h>
     35 #include <stdlib.h>
     36 #include <string.h>
     37 
     38 #include "pfctl_parser.h"
     39 #include "pfctl.h"
     40 
     41 /* The size at which a table becomes faster than individual rules */
     42 #define TABLE_THRESHOLD		6
     43 
     44 
     45 /* #define OPT_DEBUG	1 */
     46 #ifdef OPT_DEBUG
     47 # define DEBUG(str, v...) \
     48 	printf("%s: " str "\n", __FUNCTION__ , ## v)
     49 #else
     50 # define DEBUG(str, v...) ((void)0)
     51 #endif
     52 
     53 
     54 /*
     55  * A container that lets us sort a superblock to optimize the skip step jumps
     56  */
     57 struct pf_skip_step {
     58 	int				ps_count;	/* number of items */
     59 	TAILQ_HEAD( , pf_opt_rule)	ps_rules;
     60 	TAILQ_ENTRY(pf_skip_step)	ps_entry;
     61 };
     62 
     63 
     64 /*
     65  * A superblock is a block of adjacent rules of similar action.  If there
     66  * are five PASS rules in a row, they all become members of a superblock.
     67  * Once we have a superblock, we are free to re-order any rules within it
     68  * in order to improve performance; if a packet is passed, it doesn't matter
     69  * who passed it.
     70  */
     71 struct superblock {
     72 	TAILQ_HEAD( , pf_opt_rule)		 sb_rules;
     73 	TAILQ_ENTRY(superblock)			 sb_entry;
     74 	struct superblock			*sb_profiled_block;
     75 	TAILQ_HEAD(skiplist, pf_skip_step)	 sb_skipsteps[PF_SKIP_COUNT];
     76 };
     77 TAILQ_HEAD(superblocks, superblock);
     78 
     79 
     80 /*
     81  * Description of the PF rule structure.
     82  */
     83 enum {
     84     BARRIER,	/* the presence of the field puts the rule in it's own block */
     85     BREAK,	/* the field may not differ between rules in a superblock */
     86     NOMERGE,	/* the field may not differ between rules when combined */
     87     COMBINED,	/* the field may itself be combined with other rules */
     88     DC,		/* we just don't care about the field */
     89     NEVER};	/* we should never see this field set?!? */
     90 struct pf_rule_field {
     91 	const char	*prf_name;
     92 	int		 prf_type;
     93 	size_t		 prf_offset;
     94 	size_t		 prf_size;
     95 } pf_rule_desc[] = {
     96 #define PF_RULE_FIELD(field, ty)	\
     97     {#field,				\
     98     ty,					\
     99     offsetof(struct pf_rule, field),	\
    100     sizeof(((struct pf_rule *)0)->field)}
    101 
    102 
    103     /*
    104      * The presence of these fields in a rule put the rule in it's own
    105      * superblock.  Thus it will not be optimized.  It also prevents the
    106      * rule from being re-ordered at all.
    107      */
    108     PF_RULE_FIELD(label,		BARRIER),
    109     PF_RULE_FIELD(prob,			BARRIER),
    110     PF_RULE_FIELD(max_states,		BARRIER),
    111     PF_RULE_FIELD(max_src_nodes,	BARRIER),
    112 
    113     /*
    114      * These fields must be the same between all rules in the same superblock.
    115      * These rules are allowed to be re-ordered but only among like rules.
    116      * For instance we can re-order all 'tag "foo"' rules because they have the
    117      * same tag.  But we can not re-order between a 'tag "foo"' and a
    118      * 'tag "bar"' since that would change the meaning of the ruleset.
    119      */
    120     PF_RULE_FIELD(tagname,		BREAK),
    121     PF_RULE_FIELD(keep_state,		BREAK),
    122     PF_RULE_FIELD(qname,		BREAK),
    123     PF_RULE_FIELD(rt,			BREAK),
    124     PF_RULE_FIELD(allow_opts,		BREAK),
    125     PF_RULE_FIELD(rule_flag,		BREAK),
    126     PF_RULE_FIELD(action,		BREAK),
    127 
    128     /*
    129      * Any fields not listed in this structure act as BREAK fields
    130      */
    131 
    132 
    133     /*
    134      * These fields must not differ when we merge two rules together but
    135      * their difference isn't enough to put the rules in different superblocks.
    136      * There are no problems re-ordering any rules with these fields.
    137      */
    138     PF_RULE_FIELD(af,			NOMERGE),
    139     PF_RULE_FIELD(ifnot,		NOMERGE),
    140     PF_RULE_FIELD(ifname,		NOMERGE),
    141     PF_RULE_FIELD(match_tag_not,	NOMERGE),
    142     PF_RULE_FIELD(match_tagname,	NOMERGE),
    143     PF_RULE_FIELD(os_fingerprint,	NOMERGE),
    144     PF_RULE_FIELD(timeout,		NOMERGE),
    145     PF_RULE_FIELD(return_icmp,		NOMERGE),
    146     PF_RULE_FIELD(return_icmp6,		NOMERGE),
    147     PF_RULE_FIELD(uid,			NOMERGE),
    148     PF_RULE_FIELD(gid,			NOMERGE),
    149     PF_RULE_FIELD(direction,		NOMERGE),
    150     PF_RULE_FIELD(proto,		NOMERGE),
    151     PF_RULE_FIELD(type,			NOMERGE),
    152     PF_RULE_FIELD(code,			NOMERGE),
    153     PF_RULE_FIELD(flags,		NOMERGE),
    154     PF_RULE_FIELD(flagset,		NOMERGE),
    155     PF_RULE_FIELD(tos,			NOMERGE),
    156     PF_RULE_FIELD(src.port,		NOMERGE),
    157     PF_RULE_FIELD(dst.port,		NOMERGE),
    158     PF_RULE_FIELD(src.port_op,		NOMERGE),
    159     PF_RULE_FIELD(dst.port_op,		NOMERGE),
    160     PF_RULE_FIELD(src.neg,		NOMERGE),
    161     PF_RULE_FIELD(dst.neg,		NOMERGE),
    162 
    163     /* These fields can be merged */
    164     PF_RULE_FIELD(src.addr,		COMBINED),
    165     PF_RULE_FIELD(dst.addr,		COMBINED),
    166 
    167     /* We just don't care about these fields.  They're set by the kernel */
    168     PF_RULE_FIELD(skip,			DC),
    169     PF_RULE_FIELD(evaluations,		DC),
    170     PF_RULE_FIELD(packets,		DC),
    171     PF_RULE_FIELD(bytes,		DC),
    172     PF_RULE_FIELD(kif,			DC),
    173     PF_RULE_FIELD(anchor,		DC),
    174     PF_RULE_FIELD(states,		DC),
    175     PF_RULE_FIELD(src_nodes,		DC),
    176     PF_RULE_FIELD(nr,			DC),
    177     PF_RULE_FIELD(entries,		DC),
    178     PF_RULE_FIELD(qid,			DC),
    179     PF_RULE_FIELD(pqid,			DC),
    180     PF_RULE_FIELD(anchor_relative,	DC),
    181     PF_RULE_FIELD(anchor_wildcard,	DC),
    182 
    183     /* These fields should never be set in a PASS/BLOCK rule */
    184     PF_RULE_FIELD(natpass,		NEVER),
    185     PF_RULE_FIELD(max_mss,		NEVER),
    186     PF_RULE_FIELD(min_ttl,		NEVER),
    187 };
    188 
    189 
    190 
    191 int	add_opt_table(struct pfctl *, struct pf_opt_tbl **, sa_family_t,
    192 	    struct pf_rule_addr *);
    193 int	addrs_combineable(struct pf_rule_addr *, struct pf_rule_addr *);
    194 int	addrs_equal(struct pf_rule_addr *, struct pf_rule_addr *);
    195 int	block_feedback(struct pfctl *, struct superblock *);
    196 int	combine_rules(struct pfctl *, struct superblock *);
    197 void	comparable_rule(struct pf_rule *, const struct pf_rule *, int);
    198 int	construct_superblocks(struct pfctl *, struct pf_opt_queue *,
    199 	    struct superblocks *);
    200 void	exclude_supersets(struct pf_rule *, struct pf_rule *);
    201 int	load_feedback_profile(struct pfctl *, struct superblocks *);
    202 int	optimize_superblock(struct pfctl *, struct superblock *);
    203 int	pf_opt_create_table(struct pfctl *, struct pf_opt_tbl *);
    204 void	remove_from_skipsteps(struct skiplist *, struct superblock *,
    205 	    struct pf_opt_rule *, struct pf_skip_step *);
    206 int	remove_identical_rules(struct pfctl *, struct superblock *);
    207 int	reorder_rules(struct pfctl *, struct superblock *, int);
    208 int	rules_combineable(struct pf_rule *, struct pf_rule *);
    209 void	skip_append(struct superblock *, int, struct pf_skip_step *,
    210 	    struct pf_opt_rule *);
    211 int	skip_compare(int, struct pf_skip_step *, struct pf_opt_rule *);
    212 void	skip_init(void);
    213 int	skip_cmp_af(struct pf_rule *, struct pf_rule *);
    214 int	skip_cmp_dir(struct pf_rule *, struct pf_rule *);
    215 int	skip_cmp_dst_addr(struct pf_rule *, struct pf_rule *);
    216 int	skip_cmp_dst_port(struct pf_rule *, struct pf_rule *);
    217 int	skip_cmp_ifp(struct pf_rule *, struct pf_rule *);
    218 int	skip_cmp_proto(struct pf_rule *, struct pf_rule *);
    219 int	skip_cmp_src_addr(struct pf_rule *, struct pf_rule *);
    220 int	skip_cmp_src_port(struct pf_rule *, struct pf_rule *);
    221 int	superblock_inclusive(struct superblock *, struct pf_opt_rule *);
    222 void	superblock_free(struct pfctl *, struct superblock *);
    223 
    224 
    225 int (*skip_comparitors[PF_SKIP_COUNT])(struct pf_rule *, struct pf_rule *);
    226 const char *skip_comparitors_names[PF_SKIP_COUNT];
    227 #define PF_SKIP_COMPARITORS {				\
    228     { "ifp", PF_SKIP_IFP, skip_cmp_ifp },		\
    229     { "dir", PF_SKIP_DIR, skip_cmp_dir },		\
    230     { "af", PF_SKIP_AF, skip_cmp_af },			\
    231     { "proto", PF_SKIP_PROTO, skip_cmp_proto },		\
    232     { "saddr", PF_SKIP_SRC_ADDR, skip_cmp_src_addr },	\
    233     { "sport", PF_SKIP_SRC_PORT, skip_cmp_src_port },	\
    234     { "daddr", PF_SKIP_DST_ADDR, skip_cmp_dst_addr },	\
    235     { "dport", PF_SKIP_DST_PORT, skip_cmp_dst_port }	\
    236 }
    237 
    238 struct pfr_buffer table_buffer;
    239 int table_identifier;
    240 
    241 
    242 int
    243 pfctl_optimize_rules(struct pfctl *pf)
    244 {
    245 	struct superblocks superblocks;
    246 	struct superblock *block;
    247 	struct pf_opt_rule *por;
    248 	int nr;
    249 
    250 	DEBUG("optimizing ruleset");
    251 	memset(&table_buffer, 0, sizeof(table_buffer));
    252 	skip_init();
    253 
    254 	if (TAILQ_FIRST(&pf->opt_queue))
    255 		nr = TAILQ_FIRST(&pf->opt_queue)->por_rule.nr;
    256 
    257 	TAILQ_INIT(&superblocks);
    258 	if (construct_superblocks(pf, &pf->opt_queue, &superblocks))
    259 		goto error;
    260 
    261 	if (pf->opts & PF_OPT_OPTIMIZE_PROFILE) {
    262 		if (load_feedback_profile(pf, &superblocks))
    263 			goto error;
    264 	}
    265 
    266 	TAILQ_FOREACH(block, &superblocks, sb_entry) {
    267 		if (optimize_superblock(pf, block))
    268 			goto error;
    269 	}
    270 
    271 
    272 	/*
    273 	 * Optimizations are done so we turn off the optimization flag and
    274 	 * put the rules right back into the regular codepath.
    275 	 */
    276 	pf->opts &= ~PF_OPT_OPTIMIZE;
    277 
    278 	while ((block = TAILQ_FIRST(&superblocks))) {
    279 		TAILQ_REMOVE(&superblocks, block, sb_entry);
    280 
    281 		while ((por = TAILQ_FIRST(&block->sb_rules))) {
    282 			TAILQ_REMOVE(&block->sb_rules, por, por_entry);
    283 			por->por_rule.nr = nr++;
    284 			if (pfctl_add_rule(pf, &por->por_rule,
    285 			    por->por_anchor)) {
    286 				free(por);
    287 				goto error;
    288 			}
    289 			free(por);
    290 		}
    291 		free(block);
    292 	}
    293 
    294 	return (0);
    295 
    296 error:
    297 	while ((por = TAILQ_FIRST(&pf->opt_queue))) {
    298 		TAILQ_REMOVE(&pf->opt_queue, por, por_entry);
    299 		if (por->por_src_tbl) {
    300 			pfr_buf_clear(por->por_src_tbl->pt_buf);
    301 			free(por->por_src_tbl->pt_buf);
    302 			free(por->por_src_tbl);
    303 		}
    304 		if (por->por_dst_tbl) {
    305 			pfr_buf_clear(por->por_dst_tbl->pt_buf);
    306 			free(por->por_dst_tbl->pt_buf);
    307 			free(por->por_dst_tbl);
    308 		}
    309 		free(por);
    310 	}
    311 	while ((block = TAILQ_FIRST(&superblocks))) {
    312 		TAILQ_REMOVE(&superblocks, block, sb_entry);
    313 		superblock_free(pf, block);
    314 	}
    315 	return (1);
    316 }
    317 
    318 
    319 /*
    320  * Go ahead and optimize a superblock
    321  */
    322 int
    323 optimize_superblock(struct pfctl *pf, struct superblock *block)
    324 {
    325 #ifdef OPT_DEBUG
    326 	struct pf_opt_rule *por;
    327 #endif /* OPT_DEBUG */
    328 
    329 	/* We have a few optimization passes:
    330 	 *   1) remove duplicate rules or rules that are a subset of other
    331 	 *      rules
    332 	 *   2) combine otherwise identical rules with different IP addresses
    333 	 *      into a single rule and put the addresses in a table.
    334 	 *   3) re-order the rules to improve kernel skip steps
    335 	 *   4) re-order the 'quick' rules based on feedback from the
    336 	 *      active ruleset statistics
    337 	 *
    338 	 * XXX combine_rules() doesn't combine v4 and v6 rules.  would just
    339 	 *     have to keep af in the table container, make af 'COMBINE' and
    340 	 *     twiddle the af on the merged rule
    341 	 * XXX maybe add a weighting to the metric on skipsteps when doing
    342 	 *     reordering.  sometimes two sequential tables will be better
    343 	 *     that four consecutive interfaces.
    344 	 * XXX need to adjust the skipstep count of everything after PROTO,
    345 	 *     since they aren't actually checked on a proto mismatch in
    346 	 *     pf_test_{tcp, udp, icmp}()
    347 	 * XXX should i treat proto=0, af=0 or dir=0 special in skepstep
    348 	 *     calculation since they are a DC?
    349 	 * XXX keep last skiplist of last superblock to influence this
    350 	 *     superblock.  '5 inet6 log' should make '3 inet6' come before '4
    351 	 *     inet' in the next superblock.
    352 	 * XXX would be useful to add tables for ports
    353 	 * XXX we can also re-order some mutually exclusive superblocks to
    354 	 *     try merging superblocks before any of these optimization passes.
    355 	 *     for instance a single 'log in' rule in the middle of non-logging
    356 	 *     out rules.
    357 	 */
    358 
    359 	/* shortcut.  there will be alot of 1-rule superblocks */
    360 	if (!TAILQ_NEXT(TAILQ_FIRST(&block->sb_rules), por_entry))
    361 		return (0);
    362 
    363 #ifdef OPT_DEBUG
    364 	printf("--- Superblock ---\n");
    365 	TAILQ_FOREACH(por, &block->sb_rules, por_entry) {
    366 		printf("  ");
    367 		print_rule(&por->por_rule, por->por_anchor, 1);
    368 	}
    369 #endif /* OPT_DEBUG */
    370 
    371 
    372 	if (remove_identical_rules(pf, block))
    373 		return (1);
    374 	if (combine_rules(pf, block))
    375 		return (1);
    376 	if ((pf->opts & PF_OPT_OPTIMIZE_PROFILE) &&
    377 	    TAILQ_FIRST(&block->sb_rules)->por_rule.quick &&
    378 	    block->sb_profiled_block) {
    379 		if (block_feedback(pf, block))
    380 			return (1);
    381 	} else if (reorder_rules(pf, block, 0)) {
    382 		return (1);
    383 	}
    384 
    385 	/*
    386 	 * Don't add any optimization passes below reorder_rules().  It will
    387 	 * have divided superblocks into smaller blocks for further refinement
    388 	 * and doesn't put them back together again.  What once was a true
    389 	 * superblock might have been split into multiple superblocks.
    390 	 */
    391 
    392 #ifdef OPT_DEBUG
    393 	printf("--- END Superblock ---\n");
    394 #endif /* OPT_DEBUG */
    395 	return (0);
    396 }
    397 
    398 
    399 /*
    400  * Optimization pass #1: remove identical rules
    401  */
    402 int
    403 remove_identical_rules(struct pfctl *pf, struct superblock *block)
    404 {
    405 	struct pf_opt_rule *por1, *por2, *por_next, *por2_next;
    406 	struct pf_rule a, a2, b, b2;
    407 
    408 	for (por1 = TAILQ_FIRST(&block->sb_rules); por1; por1 = por_next) {
    409 		por_next = TAILQ_NEXT(por1, por_entry);
    410 		for (por2 = por_next; por2; por2 = por2_next) {
    411 			por2_next = TAILQ_NEXT(por2, por_entry);
    412 			comparable_rule(&a, &por1->por_rule, DC);
    413 			comparable_rule(&b, &por2->por_rule, DC);
    414 			memcpy(&a2, &a, sizeof(a2));
    415 			memcpy(&b2, &b, sizeof(b2));
    416 
    417 			exclude_supersets(&a, &b);
    418 			exclude_supersets(&b2, &a2);
    419 			if (memcmp(&a, &b, sizeof(a)) == 0) {
    420 				DEBUG("removing identical rule  nr%d = *nr%d*",
    421 				    por1->por_rule.nr, por2->por_rule.nr);
    422 				TAILQ_REMOVE(&block->sb_rules, por2, por_entry);
    423 				if (por_next == por2)
    424 					por_next = TAILQ_NEXT(por1, por_entry);
    425 				free(por2);
    426 			} else if (memcmp(&a2, &b2, sizeof(a2)) == 0) {
    427 				DEBUG("removing identical rule  *nr%d* = nr%d",
    428 				    por1->por_rule.nr, por2->por_rule.nr);
    429 				TAILQ_REMOVE(&block->sb_rules, por1, por_entry);
    430 				free(por1);
    431 				break;
    432 			}
    433 		}
    434 	}
    435 
    436 	return (0);
    437 }
    438 
    439 
    440 /*
    441  * Optimization pass #2: combine similar rules with different addresses
    442  * into a single rule and a table
    443  */
    444 int
    445 combine_rules(struct pfctl *pf, struct superblock *block)
    446 {
    447 	struct pf_opt_rule *p1, *p2, *por_next;
    448 	int src_eq, dst_eq;
    449 
    450 	if ((pf->loadopt & PFCTL_FLAG_TABLE) == 0) {
    451 		warnx("Must enable table loading for optimizations");
    452 		return (1);
    453 	}
    454 
    455 	/* First we make a pass to combine the rules.  O(n log n) */
    456 	TAILQ_FOREACH(p1, &block->sb_rules, por_entry) {
    457 		for (p2 = TAILQ_NEXT(p1, por_entry); p2; p2 = por_next) {
    458 			por_next = TAILQ_NEXT(p2, por_entry);
    459 
    460 			src_eq = addrs_equal(&p1->por_rule.src,
    461 			    &p2->por_rule.src);
    462 			dst_eq = addrs_equal(&p1->por_rule.dst,
    463 			    &p2->por_rule.dst);
    464 
    465 			if (src_eq && !dst_eq && p1->por_src_tbl == NULL &&
    466 			    p2->por_dst_tbl == NULL &&
    467 			    rules_combineable(&p1->por_rule, &p2->por_rule) &&
    468 			    addrs_combineable(&p1->por_rule.dst,
    469 			    &p2->por_rule.dst)) {
    470 				DEBUG("can combine rules  nr%d = nr%d",
    471 				    p1->por_rule.nr, p2->por_rule.nr);
    472 				if (p1->por_dst_tbl == NULL &&
    473 				    add_opt_table(pf, &p1->por_dst_tbl,
    474 				    p1->por_rule.af, &p1->por_rule.dst))
    475 					return (1);
    476 				if (add_opt_table(pf, &p1->por_dst_tbl,
    477 				    p1->por_rule.af, &p2->por_rule.dst))
    478 					return (1);
    479 				p2->por_dst_tbl = p1->por_dst_tbl;
    480 				if (p1->por_dst_tbl->pt_rulecount >=
    481 				    TABLE_THRESHOLD) {
    482 					TAILQ_REMOVE(&block->sb_rules, p2,
    483 					    por_entry);
    484 					free(p2);
    485 				}
    486 			} else if (!src_eq && dst_eq && p1->por_dst_tbl == NULL
    487 			    && p2->por_src_tbl == NULL &&
    488 			    rules_combineable(&p1->por_rule, &p2->por_rule) &&
    489 			    addrs_combineable(&p1->por_rule.src,
    490 			    &p2->por_rule.src)) {
    491 				DEBUG("can combine rules  nr%d = nr%d",
    492 				    p1->por_rule.nr, p2->por_rule.nr);
    493 				if (p1->por_src_tbl == NULL &&
    494 				    add_opt_table(pf, &p1->por_src_tbl,
    495 				    p1->por_rule.af, &p1->por_rule.src))
    496 					return (1);
    497 				if (add_opt_table(pf, &p1->por_src_tbl,
    498 				    p1->por_rule.af, &p2->por_rule.src))
    499 					return (1);
    500 				p2->por_src_tbl = p1->por_src_tbl;
    501 				if (p1->por_src_tbl->pt_rulecount >=
    502 				    TABLE_THRESHOLD) {
    503 					TAILQ_REMOVE(&block->sb_rules, p2,
    504 					    por_entry);
    505 					free(p2);
    506 				}
    507 			}
    508 		}
    509 	}
    510 
    511 
    512 	/*
    513 	 * Then we make a final pass to create a valid table name and
    514 	 * insert the name into the rules.
    515 	 */
    516 	for (p1 = TAILQ_FIRST(&block->sb_rules); p1; p1 = por_next) {
    517 		por_next = TAILQ_NEXT(p1, por_entry);
    518 		assert(p1->por_src_tbl == NULL || p1->por_dst_tbl == NULL);
    519 
    520 		if (p1->por_src_tbl && p1->por_src_tbl->pt_rulecount >=
    521 		    TABLE_THRESHOLD) {
    522 			if (p1->por_src_tbl->pt_generated) {
    523 				/* This rule is included in a table */
    524 				TAILQ_REMOVE(&block->sb_rules, p1, por_entry);
    525 				free(p1);
    526 				continue;
    527 			}
    528 			p1->por_src_tbl->pt_generated = 1;
    529 
    530 			if ((pf->opts & PF_OPT_NOACTION) == 0 &&
    531 			    pf_opt_create_table(pf, p1->por_src_tbl))
    532 				return (1);
    533 
    534 			pf->tdirty = 1;
    535 
    536 			if (pf->opts & PF_OPT_VERBOSE)
    537 				print_tabledef(p1->por_src_tbl->pt_name,
    538 				    PFR_TFLAG_CONST, 1,
    539 				    &p1->por_src_tbl->pt_nodes);
    540 
    541 			memset(&p1->por_rule.src.addr, 0,
    542 			    sizeof(p1->por_rule.src.addr));
    543 			p1->por_rule.src.addr.type = PF_ADDR_TABLE;
    544 			strlcpy(p1->por_rule.src.addr.v.tblname,
    545 			    p1->por_src_tbl->pt_name,
    546 			    sizeof(p1->por_rule.src.addr.v.tblname));
    547 
    548 			pfr_buf_clear(p1->por_src_tbl->pt_buf);
    549 			free(p1->por_src_tbl->pt_buf);
    550 			p1->por_src_tbl->pt_buf = NULL;
    551 		}
    552 		if (p1->por_dst_tbl && p1->por_dst_tbl->pt_rulecount >=
    553 		    TABLE_THRESHOLD) {
    554 			if (p1->por_dst_tbl->pt_generated) {
    555 				/* This rule is included in a table */
    556 				TAILQ_REMOVE(&block->sb_rules, p1, por_entry);
    557 				free(p1);
    558 				continue;
    559 			}
    560 			p1->por_dst_tbl->pt_generated = 1;
    561 
    562 			if ((pf->opts & PF_OPT_NOACTION) == 0 &&
    563 			    pf_opt_create_table(pf, p1->por_dst_tbl))
    564 				return (1);
    565 			pf->tdirty = 1;
    566 
    567 			if (pf->opts & PF_OPT_VERBOSE)
    568 				print_tabledef(p1->por_dst_tbl->pt_name,
    569 				    PFR_TFLAG_CONST, 1,
    570 				    &p1->por_dst_tbl->pt_nodes);
    571 
    572 			memset(&p1->por_rule.dst.addr, 0,
    573 			    sizeof(p1->por_rule.dst.addr));
    574 			p1->por_rule.dst.addr.type = PF_ADDR_TABLE;
    575 			strlcpy(p1->por_rule.dst.addr.v.tblname,
    576 			    p1->por_dst_tbl->pt_name,
    577 			    sizeof(p1->por_rule.dst.addr.v.tblname));
    578 
    579 			pfr_buf_clear(p1->por_dst_tbl->pt_buf);
    580 			free(p1->por_dst_tbl->pt_buf);
    581 			p1->por_dst_tbl->pt_buf = NULL;
    582 		}
    583 	}
    584 
    585 	return (0);
    586 }
    587 
    588 
    589 /*
    590  * Optimization pass #3: re-order rules to improve skip steps
    591  */
    592 int
    593 reorder_rules(struct pfctl *pf, struct superblock *block, int depth)
    594 {
    595 	struct superblock *newblock;
    596 	struct pf_skip_step *skiplist;
    597 	struct pf_opt_rule *por;
    598 	int i, largest, largest_list, rule_count = 0;
    599 	TAILQ_HEAD( , pf_opt_rule) head;
    600 
    601 	/*
    602 	 * Calculate the best-case skip steps.  We put each rule in a list
    603 	 * of other rules with common fields
    604 	 */
    605 	for (i = 0; i < PF_SKIP_COUNT; i++) {
    606 		TAILQ_FOREACH(por, &block->sb_rules, por_entry) {
    607 			TAILQ_FOREACH(skiplist, &block->sb_skipsteps[i],
    608 			    ps_entry) {
    609 				if (skip_compare(i, skiplist, por) == 0)
    610 					break;
    611 			}
    612 			if (skiplist == NULL) {
    613 				if ((skiplist = calloc(1, sizeof(*skiplist))) ==
    614 				    NULL)
    615 					err(1, "calloc");
    616 				TAILQ_INIT(&skiplist->ps_rules);
    617 				TAILQ_INSERT_TAIL(&block->sb_skipsteps[i],
    618 				    skiplist, ps_entry);
    619 			}
    620 			skip_append(block, i, skiplist, por);
    621 		}
    622 	}
    623 
    624 	TAILQ_FOREACH(por, &block->sb_rules, por_entry)
    625 		rule_count++;
    626 
    627 	/*
    628 	 * Now we're going to ignore any fields that are identical between
    629 	 * all of the rules in the superblock and those fields which differ
    630 	 * between every rule in the superblock.
    631 	 */
    632 	largest = 0;
    633 	for (i = 0; i < PF_SKIP_COUNT; i++) {
    634 		skiplist = TAILQ_FIRST(&block->sb_skipsteps[i]);
    635 		if (skiplist->ps_count == rule_count) {
    636 			DEBUG("(%d) original skipstep '%s' is all rules",
    637 			    depth, skip_comparitors_names[i]);
    638 			skiplist->ps_count = 0;
    639 		} else if (skiplist->ps_count == 1) {
    640 			skiplist->ps_count = 0;
    641 		} else {
    642 			DEBUG("(%d) original skipstep '%s' largest jump is %d",
    643 			    depth, skip_comparitors_names[i],
    644 			    skiplist->ps_count);
    645 			if (skiplist->ps_count > largest)
    646 				largest = skiplist->ps_count;
    647 		}
    648 	}
    649 	if (largest == 0) {
    650 		/* Ugh.  There is NO commonality in the superblock on which
    651 		 * optimize the skipsteps optimization.
    652 		 */
    653 		goto done;
    654 	}
    655 
    656 	/*
    657 	 * Now we're going to empty the superblock rule list and re-create
    658 	 * it based on a more optimal skipstep order.
    659 	 */
    660 	TAILQ_INIT(&head);
    661 	while ((por = TAILQ_FIRST(&block->sb_rules))) {
    662 		TAILQ_REMOVE(&block->sb_rules, por, por_entry);
    663 		TAILQ_INSERT_TAIL(&head, por, por_entry);
    664 	}
    665 
    666 
    667 	while (!TAILQ_EMPTY(&head)) {
    668 		largest = 1;
    669 
    670 		/*
    671 		 * Find the most useful skip steps remaining
    672 		 */
    673 		for (i = 0; i < PF_SKIP_COUNT; i++) {
    674 			skiplist = TAILQ_FIRST(&block->sb_skipsteps[i]);
    675 			if (skiplist->ps_count > largest) {
    676 				largest = skiplist->ps_count;
    677 				largest_list = i;
    678 			}
    679 		}
    680 
    681 		if (largest <= 1) {
    682 			/*
    683 			 * Nothing useful left.  Leave remaining rules in order.
    684 			 */
    685 			DEBUG("(%d) no more commonality for skip steps", depth);
    686 			while ((por = TAILQ_FIRST(&head))) {
    687 				TAILQ_REMOVE(&head, por, por_entry);
    688 				TAILQ_INSERT_TAIL(&block->sb_rules, por,
    689 				    por_entry);
    690 			}
    691 		} else {
    692 			/*
    693 			 * There is commonality.  Extract those common rules
    694 			 * and place them in the ruleset adjacent to each
    695 			 * other.
    696 			 */
    697 			skiplist = TAILQ_FIRST(&block->sb_skipsteps[
    698 			    largest_list]);
    699 			DEBUG("(%d) skipstep '%s' largest jump is %d @ #%d",
    700 			    depth, skip_comparitors_names[largest_list],
    701 			    largest, TAILQ_FIRST(&TAILQ_FIRST(&block->
    702 			    sb_skipsteps [largest_list])->ps_rules)->
    703 			    por_rule.nr);
    704 			TAILQ_REMOVE(&block->sb_skipsteps[largest_list],
    705 			    skiplist, ps_entry);
    706 
    707 
    708 			/*
    709 			 * There may be further commonality inside these
    710 			 * rules.  So we'll split them off into they're own
    711 			 * superblock and pass it back into the optimizer.
    712 			 */
    713 			if (skiplist->ps_count > 2) {
    714 				if ((newblock = calloc(1, sizeof(*newblock)))
    715 				    == NULL) {
    716 					warn("calloc");
    717 					return (1);
    718 				}
    719 				TAILQ_INIT(&newblock->sb_rules);
    720 				for (i = 0; i < PF_SKIP_COUNT; i++)
    721 					TAILQ_INIT(&newblock->sb_skipsteps[i]);
    722 				TAILQ_INSERT_BEFORE(block, newblock, sb_entry);
    723 				DEBUG("(%d) splitting off %d rules from superblock @ #%d",
    724 				    depth, skiplist->ps_count,
    725 				    TAILQ_FIRST(&skiplist->ps_rules)->
    726 				    por_rule.nr);
    727 			} else {
    728 				newblock = block;
    729 			}
    730 
    731 			while ((por = TAILQ_FIRST(&skiplist->ps_rules))) {
    732 				TAILQ_REMOVE(&head, por, por_entry);
    733 				TAILQ_REMOVE(&skiplist->ps_rules, por,
    734 				    por_skip_entry[largest_list]);
    735 				TAILQ_INSERT_TAIL(&newblock->sb_rules, por,
    736 				    por_entry);
    737 
    738 				/* Remove this rule from all other skiplists */
    739 				remove_from_skipsteps(&block->sb_skipsteps[
    740 				    largest_list], block, por, skiplist);
    741 			}
    742 			free(skiplist);
    743 			if (newblock != block)
    744 				if (reorder_rules(pf, newblock, depth + 1))
    745 					return (1);
    746 		}
    747 	}
    748 
    749 done:
    750 	for (i = 0; i < PF_SKIP_COUNT; i++) {
    751 		while ((skiplist = TAILQ_FIRST(&block->sb_skipsteps[i]))) {
    752 			TAILQ_REMOVE(&block->sb_skipsteps[i], skiplist,
    753 			    ps_entry);
    754 			free(skiplist);
    755 		}
    756 	}
    757 
    758 	return (0);
    759 }
    760 
    761 
    762 /*
    763  * Optimization pass #4: re-order 'quick' rules based on feedback from the
    764  * currently running ruleset
    765  */
    766 int
    767 block_feedback(struct pfctl *pf, struct superblock *block)
    768 {
    769 	TAILQ_HEAD( , pf_opt_rule) queue;
    770 	struct pf_opt_rule *por1, *por2;
    771 	u_int64_t total_count = 0;
    772 	struct pf_rule a, b;
    773 
    774 
    775 	/*
    776 	 * Walk through all of the profiled superblock's rules and copy
    777 	 * the counters onto our rules.
    778 	 */
    779 	TAILQ_FOREACH(por1, &block->sb_profiled_block->sb_rules, por_entry) {
    780 		comparable_rule(&a, &por1->por_rule, DC);
    781 		total_count += por1->por_rule.packets;
    782 		TAILQ_FOREACH(por2, &block->sb_rules, por_entry) {
    783 			if (por2->por_profile_count)
    784 				continue;
    785 			comparable_rule(&b, &por2->por_rule, DC);
    786 			if (memcmp(&a, &b, sizeof(a)) == 0) {
    787 				por2->por_profile_count =
    788 				    por1->por_rule.packets;
    789 				break;
    790 			}
    791 		}
    792 	}
    793 	superblock_free(pf, block->sb_profiled_block);
    794 	block->sb_profiled_block = NULL;
    795 
    796 	/*
    797 	 * Now we pull all of the rules off the superblock and re-insert them
    798 	 * in sorted order.
    799 	 */
    800 
    801 	TAILQ_INIT(&queue);
    802 	while ((por1 = TAILQ_FIRST(&block->sb_rules)) != NULL) {
    803 		TAILQ_REMOVE(&block->sb_rules, por1, por_entry);
    804 		TAILQ_INSERT_TAIL(&queue, por1, por_entry);
    805 	}
    806 
    807 	while ((por1 = TAILQ_FIRST(&queue)) != NULL) {
    808 		TAILQ_REMOVE(&queue, por1, por_entry);
    809 /* XXX I should sort all of the unused rules based on skip steps */
    810 		TAILQ_FOREACH(por2, &block->sb_rules, por_entry) {
    811 			if (por1->por_profile_count > por2->por_profile_count) {
    812 				TAILQ_INSERT_BEFORE(por2, por1, por_entry);
    813 				break;
    814 			}
    815 		}
    816 		if (por2 == TAILQ_END(&block->sb_rules))
    817 			TAILQ_INSERT_TAIL(&block->sb_rules, por1, por_entry);
    818 	}
    819 
    820 	return (0);
    821 }
    822 
    823 
    824 /*
    825  * Load the current ruleset from the kernel and try to associate them with
    826  * the ruleset we're optimizing.
    827  */
    828 int
    829 load_feedback_profile(struct pfctl *pf, struct superblocks *superblocks)
    830 {
    831 	struct superblock *block, *blockcur;
    832 	struct superblocks prof_superblocks;
    833 	struct pf_opt_rule *por;
    834 	struct pf_opt_queue queue;
    835 	struct pfioc_rule pr;
    836 	struct pf_rule a, b;
    837 	int nr, mnr;
    838 
    839 	TAILQ_INIT(&queue);
    840 	TAILQ_INIT(&prof_superblocks);
    841 
    842 	memset(&pr, 0, sizeof(pr));
    843 	pr.rule.action = PF_PASS;
    844 	if (ioctl(pf->dev, DIOCGETRULES, &pr)) {
    845 		warn("DIOCGETRULES");
    846 		return (1);
    847 	}
    848 	mnr = pr.nr;
    849 
    850 	DEBUG("Loading %d active rules for a feedback profile", mnr);
    851 	for (nr = 0; nr < mnr; ++nr) {
    852 		if ((por = calloc(1, sizeof(*por))) == NULL) {
    853 			warn("calloc");
    854 			return (1);
    855 		}
    856 		pr.nr = nr;
    857 		if (ioctl(pf->dev, DIOCGETRULE, &pr)) {
    858 			warn("DIOCGETRULES");
    859 			return (1);
    860 		}
    861 		memcpy(&por->por_rule, &pr.rule, sizeof(por->por_rule));
    862 		strlcpy(por->por_anchor, pr.anchor_call,
    863 		    sizeof(por->por_anchor));
    864 		if (TAILQ_EMPTY(&por->por_rule.rpool.list))
    865 			memset(&por->por_rule.rpool, 0,
    866 			    sizeof(por->por_rule.rpool));
    867 		TAILQ_INSERT_TAIL(&queue, por, por_entry);
    868 
    869 		/* XXX pfctl_get_pool(pf->dev, &pr.rule.rpool, nr, pr.ticket,
    870 		 *         PF_PASS, pf->anchor) ???
    871 		 * ... pfctl_clear_pool(&pr.rule.rpool)
    872 		 */
    873 	}
    874 
    875 	if (construct_superblocks(pf, &queue, &prof_superblocks))
    876 		return (1);
    877 
    878 
    879 	/*
    880 	 * Now we try to associate the active ruleset's superblocks with
    881 	 * the superblocks we're compiling.
    882 	 */
    883 	block = TAILQ_FIRST(superblocks);
    884 	blockcur = TAILQ_FIRST(&prof_superblocks);
    885 	while (block && blockcur) {
    886 		comparable_rule(&a, &TAILQ_FIRST(&block->sb_rules)->por_rule,
    887 		    BREAK);
    888 		comparable_rule(&b, &TAILQ_FIRST(&blockcur->sb_rules)->por_rule,
    889 		    BREAK);
    890 		if (memcmp(&a, &b, sizeof(a)) == 0) {
    891 			/* The two superblocks lined up */
    892 			block->sb_profiled_block = blockcur;
    893 		} else {
    894 			DEBUG("superblocks don't line up between #%d and #%d",
    895 			    TAILQ_FIRST(&block->sb_rules)->por_rule.nr,
    896 			    TAILQ_FIRST(&blockcur->sb_rules)->por_rule.nr);
    897 			break;
    898 		}
    899 		block = TAILQ_NEXT(block, sb_entry);
    900 		blockcur = TAILQ_NEXT(blockcur, sb_entry);
    901 	}
    902 
    903 
    904 
    905 	/* Free any superblocks we couldn't link */
    906 	while (blockcur) {
    907 		block = TAILQ_NEXT(blockcur, sb_entry);
    908 		superblock_free(pf, blockcur);
    909 		blockcur = block;
    910 	}
    911 	return (0);
    912 }
    913 
    914 
    915 /*
    916  * Compare a rule to a skiplist to see if the rule is a member
    917  */
    918 int
    919 skip_compare(int skipnum, struct pf_skip_step *skiplist,
    920     struct pf_opt_rule *por)
    921 {
    922 	struct pf_rule *a, *b;
    923 	if (skipnum >= PF_SKIP_COUNT || skipnum < 0)
    924 		errx(1, "skip_compare() out of bounds");
    925 	a = &por->por_rule;
    926 	b = &TAILQ_FIRST(&skiplist->ps_rules)->por_rule;
    927 
    928 	return ((skip_comparitors[skipnum])(a, b));
    929 }
    930 
    931 
    932 /*
    933  * Add a rule to a skiplist
    934  */
    935 void
    936 skip_append(struct superblock *superblock, int skipnum,
    937     struct pf_skip_step *skiplist, struct pf_opt_rule *por)
    938 {
    939 	struct pf_skip_step *prev;
    940 
    941 	skiplist->ps_count++;
    942 	TAILQ_INSERT_TAIL(&skiplist->ps_rules, por, por_skip_entry[skipnum]);
    943 
    944 	/* Keep the list of skiplists sorted by whichever is larger */
    945 	while ((prev = TAILQ_PREV(skiplist, skiplist, ps_entry)) &&
    946 	    prev->ps_count < skiplist->ps_count) {
    947 		TAILQ_REMOVE(&superblock->sb_skipsteps[skipnum],
    948 		    skiplist, ps_entry);
    949 		TAILQ_INSERT_BEFORE(prev, skiplist, ps_entry);
    950 	}
    951 }
    952 
    953 
    954 /*
    955  * Remove a rule from the other skiplist calculations.
    956  */
    957 void
    958 remove_from_skipsteps(struct skiplist *head, struct superblock *block,
    959     struct pf_opt_rule *por, struct pf_skip_step *active_list)
    960 {
    961 	struct pf_skip_step *sk, *next;
    962 	struct pf_opt_rule *p2;
    963 	int i, found;
    964 
    965 	for (i = 0; i < PF_SKIP_COUNT; i++) {
    966 		sk = TAILQ_FIRST(&block->sb_skipsteps[i]);
    967 		if (sk == NULL || sk == active_list || sk->ps_count <= 1)
    968 			continue;
    969 		found = 0;
    970 		do {
    971 			TAILQ_FOREACH(p2, &sk->ps_rules, por_skip_entry[i])
    972 				if (p2 == por) {
    973 					TAILQ_REMOVE(&sk->ps_rules, p2,
    974 					    por_skip_entry[i]);
    975 					found = 1;
    976 					sk->ps_count--;
    977 					break;
    978 				}
    979 		} while (!found && (sk = TAILQ_NEXT(sk, ps_entry)));
    980 		if (found && sk) {
    981 			/* Does this change the sorting order? */
    982 			while ((next = TAILQ_NEXT(sk, ps_entry)) &&
    983 			    next->ps_count > sk->ps_count) {
    984 				TAILQ_REMOVE(head, sk, ps_entry);
    985 				TAILQ_INSERT_AFTER(head, next, sk, ps_entry);
    986 			}
    987 #ifdef OPT_DEBUG
    988 			next = TAILQ_NEXT(sk, ps_entry);
    989 			assert(next == NULL || next->ps_count <= sk->ps_count);
    990 #endif /* OPT_DEBUG */
    991 		}
    992 	}
    993 }
    994 
    995 
    996 /* Compare two rules AF field for skiplist construction */
    997 int
    998 skip_cmp_af(struct pf_rule *a, struct pf_rule *b)
    999 {
   1000 	if (a->af != b->af || a->af == 0)
   1001 		return (1);
   1002 	return (0);
   1003 }
   1004 
   1005 /* Compare two rules DIRECTION field for skiplist construction */
   1006 int
   1007 skip_cmp_dir(struct pf_rule *a, struct pf_rule *b)
   1008 {
   1009 	if (a->direction == 0 || a->direction != b->direction)
   1010 		return (1);
   1011 	return (0);
   1012 }
   1013 
   1014 /* Compare two rules DST Address field for skiplist construction */
   1015 int
   1016 skip_cmp_dst_addr(struct pf_rule *a, struct pf_rule *b)
   1017 {
   1018 	if (a->dst.neg != b->dst.neg ||
   1019 	    a->dst.addr.type != b->dst.addr.type)
   1020 		return (1);
   1021 	/* XXX if (a->proto != b->proto && a->proto != 0 && b->proto != 0
   1022 	 *    && (a->proto == IPPROTO_TCP || a->proto == IPPROTO_UDP ||
   1023 	 *    a->proto == IPPROTO_ICMP
   1024 	 *	return (1);
   1025 	 */
   1026 	switch (a->dst.addr.type) {
   1027 	case PF_ADDR_ADDRMASK:
   1028 		if (memcmp(&a->dst.addr.v.a.addr, &b->dst.addr.v.a.addr,
   1029 		    sizeof(a->dst.addr.v.a.addr)) ||
   1030 		    memcmp(&a->dst.addr.v.a.mask, &b->dst.addr.v.a.mask,
   1031 		    sizeof(a->dst.addr.v.a.mask)) ||
   1032 		    (a->dst.addr.v.a.addr.addr32[0] == 0 &&
   1033 		    a->dst.addr.v.a.addr.addr32[1] == 0 &&
   1034 		    a->dst.addr.v.a.addr.addr32[2] == 0 &&
   1035 		    a->dst.addr.v.a.addr.addr32[3] == 0))
   1036 			return (1);
   1037 		return (0);
   1038 	case PF_ADDR_DYNIFTL:
   1039 		if (strcmp(a->dst.addr.v.ifname, b->dst.addr.v.ifname) != 0 ||
   1040 		    a->dst.addr.iflags != a->dst.addr.iflags ||
   1041 		    memcmp(&a->dst.addr.v.a.mask, &b->dst.addr.v.a.mask,
   1042 		    sizeof(a->dst.addr.v.a.mask)))
   1043 			return (1);
   1044 		return (0);
   1045 	case PF_ADDR_NOROUTE:
   1046 		return (0);
   1047 	case PF_ADDR_TABLE:
   1048 		return (strcmp(a->dst.addr.v.tblname, b->dst.addr.v.tblname));
   1049 	}
   1050 	return (1);
   1051 }
   1052 
   1053 /* Compare two rules DST port field for skiplist construction */
   1054 int
   1055 skip_cmp_dst_port(struct pf_rule *a, struct pf_rule *b)
   1056 {
   1057 	/* XXX if (a->proto != b->proto && a->proto != 0 && b->proto != 0
   1058 	 *    && (a->proto == IPPROTO_TCP || a->proto == IPPROTO_UDP ||
   1059 	 *    a->proto == IPPROTO_ICMP
   1060 	 *	return (1);
   1061 	 */
   1062 	if (a->dst.port_op == PF_OP_NONE || a->dst.port_op != b->dst.port_op ||
   1063 	    a->dst.port[0] != b->dst.port[0] ||
   1064 	    a->dst.port[1] != b->dst.port[1])
   1065 		return (1);
   1066 	return (0);
   1067 }
   1068 
   1069 /* Compare two rules IFP field for skiplist construction */
   1070 int
   1071 skip_cmp_ifp(struct pf_rule *a, struct pf_rule *b)
   1072 {
   1073 	if (strcmp(a->ifname, b->ifname) || a->ifname[0] == '\0')
   1074 		return (1);
   1075 	return (a->ifnot != b->ifnot);
   1076 }
   1077 
   1078 /* Compare two rules PROTO field for skiplist construction */
   1079 int
   1080 skip_cmp_proto(struct pf_rule *a, struct pf_rule *b)
   1081 {
   1082 	return (a->proto != b->proto || a->proto == 0);
   1083 }
   1084 
   1085 /* Compare two rules SRC addr field for skiplist construction */
   1086 int
   1087 skip_cmp_src_addr(struct pf_rule *a, struct pf_rule *b)
   1088 {
   1089 	if (a->src.neg != b->src.neg ||
   1090 	    a->src.addr.type != b->src.addr.type)
   1091 		return (1);
   1092 	/* XXX if (a->proto != b->proto && a->proto != 0 && b->proto != 0
   1093 	 *    && (a->proto == IPPROTO_TCP || a->proto == IPPROTO_UDP ||
   1094 	 *    a->proto == IPPROTO_ICMP
   1095 	 *	return (1);
   1096 	 */
   1097 	switch (a->src.addr.type) {
   1098 	case PF_ADDR_ADDRMASK:
   1099 		if (memcmp(&a->src.addr.v.a.addr, &b->src.addr.v.a.addr,
   1100 		    sizeof(a->src.addr.v.a.addr)) ||
   1101 		    memcmp(&a->src.addr.v.a.mask, &b->src.addr.v.a.mask,
   1102 		    sizeof(a->src.addr.v.a.mask)) ||
   1103 		    (a->src.addr.v.a.addr.addr32[0] == 0 &&
   1104 		    a->src.addr.v.a.addr.addr32[1] == 0 &&
   1105 		    a->src.addr.v.a.addr.addr32[2] == 0 &&
   1106 		    a->src.addr.v.a.addr.addr32[3] == 0))
   1107 			return (1);
   1108 		return (0);
   1109 	case PF_ADDR_DYNIFTL:
   1110 		if (strcmp(a->src.addr.v.ifname, b->src.addr.v.ifname) != 0 ||
   1111 		    a->src.addr.iflags != a->src.addr.iflags ||
   1112 		    memcmp(&a->src.addr.v.a.mask, &b->src.addr.v.a.mask,
   1113 		    sizeof(a->src.addr.v.a.mask)))
   1114 			return (1);
   1115 		return (0);
   1116 	case PF_ADDR_NOROUTE:
   1117 		return (0);
   1118 	case PF_ADDR_TABLE:
   1119 		return (strcmp(a->src.addr.v.tblname, b->src.addr.v.tblname));
   1120 	}
   1121 	return (1);
   1122 }
   1123 
   1124 /* Compare two rules SRC port field for skiplist construction */
   1125 int
   1126 skip_cmp_src_port(struct pf_rule *a, struct pf_rule *b)
   1127 {
   1128 	if (a->src.port_op == PF_OP_NONE || a->src.port_op != b->src.port_op ||
   1129 	    a->src.port[0] != b->src.port[0] ||
   1130 	    a->src.port[1] != b->src.port[1])
   1131 		return (1);
   1132 	/* XXX if (a->proto != b->proto && a->proto != 0 && b->proto != 0
   1133 	 *    && (a->proto == IPPROTO_TCP || a->proto == IPPROTO_UDP ||
   1134 	 *    a->proto == IPPROTO_ICMP
   1135 	 *	return (1);
   1136 	 */
   1137 	return (0);
   1138 }
   1139 
   1140 
   1141 void
   1142 skip_init(void)
   1143 {
   1144 	struct {
   1145 		char *name;
   1146 		int skipnum;
   1147 		int (*func)(struct pf_rule *, struct pf_rule *);
   1148 	} comps[] = PF_SKIP_COMPARITORS;
   1149 	int skipnum, i;
   1150 
   1151 	for (skipnum = 0; skipnum < PF_SKIP_COUNT; skipnum++) {
   1152 		for (i = 0; i < sizeof(comps)/sizeof(*comps); i++)
   1153 			if (comps[i].skipnum == skipnum) {
   1154 				skip_comparitors[skipnum] = comps[i].func;
   1155 				skip_comparitors_names[skipnum] = comps[i].name;
   1156 			}
   1157 	}
   1158 	for (skipnum = 0; skipnum < PF_SKIP_COUNT; skipnum++)
   1159 		if (skip_comparitors[skipnum] == NULL)
   1160 			errx(1, "Need to add skip step comparitor to pfctl?!");
   1161 }
   1162 
   1163 /*
   1164  * Add a host/netmask to a table
   1165  */
   1166 int
   1167 add_opt_table(struct pfctl *pf, struct pf_opt_tbl **tbl, sa_family_t af,
   1168     struct pf_rule_addr *addr)
   1169 {
   1170 #ifdef OPT_DEBUG
   1171 	char buf[128];
   1172 #endif /* OPT_DEBUG */
   1173 	static int tablenum = 0;
   1174 	struct node_host node_host;
   1175 
   1176 	if (*tbl == NULL) {
   1177 		if ((*tbl = calloc(1, sizeof(**tbl))) == NULL ||
   1178 		    ((*tbl)->pt_buf = calloc(1, sizeof(*(*tbl)->pt_buf))) ==
   1179 		    NULL)
   1180 			err(1, "calloc");
   1181 		(*tbl)->pt_buf->pfrb_type = PFRB_ADDRS;
   1182 		SIMPLEQ_INIT(&(*tbl)->pt_nodes);
   1183 
   1184 		/* This is just a temporary table name */
   1185 		snprintf((*tbl)->pt_name, sizeof((*tbl)->pt_name), "%s%d",
   1186 		    PF_OPT_TABLE_PREFIX, tablenum++);
   1187 		DEBUG("creating table <%s>", (*tbl)->pt_name);
   1188 	}
   1189 
   1190 	memset(&node_host, 0, sizeof(node_host));
   1191 	node_host.af = af;
   1192 	node_host.addr = addr->addr;
   1193 
   1194 #ifdef OPT_DEBUG
   1195 	DEBUG("<%s> adding %s/%d", (*tbl)->pt_name, inet_ntop(af,
   1196 	    &node_host.addr.v.a.addr, buf, sizeof(buf)),
   1197 	    unmask(&node_host.addr.v.a.mask, af));
   1198 #endif /* OPT_DEBUG */
   1199 
   1200 	if (append_addr_host((*tbl)->pt_buf, &node_host, 0, 0))
   1201 		return (1);
   1202 	if (pf->opts & PF_OPT_VERBOSE) {
   1203 		struct node_tinit *ti;
   1204 
   1205 		if ((ti = calloc(1, sizeof(*ti))) == NULL)
   1206 			err(1, "malloc");
   1207 		if ((ti->host = malloc(sizeof(*ti->host))) == NULL)
   1208 			err(1, "malloc");
   1209 		memcpy(ti->host, &node_host, sizeof(*ti->host));
   1210 		SIMPLEQ_INSERT_TAIL(&(*tbl)->pt_nodes, ti, entries);
   1211 	}
   1212 
   1213 	(*tbl)->pt_rulecount++;
   1214 	if ((*tbl)->pt_rulecount == TABLE_THRESHOLD)
   1215 		DEBUG("table <%s> now faster than skip steps", (*tbl)->pt_name);
   1216 
   1217 	return (0);
   1218 }
   1219 
   1220 
   1221 /*
   1222  * Do the dirty work of choosing an unused table name and creating it.
   1223  * (be careful with the table name, it might already be used in another anchor)
   1224  */
   1225 int
   1226 pf_opt_create_table(struct pfctl *pf, struct pf_opt_tbl *tbl)
   1227 {
   1228 	static int tablenum;
   1229 	struct pfr_table *t;
   1230 
   1231 	if (table_buffer.pfrb_type == 0) {
   1232 		/* Initialize the list of tables */
   1233 		table_buffer.pfrb_type = PFRB_TABLES;
   1234 		for (;;) {
   1235 			pfr_buf_grow(&table_buffer, table_buffer.pfrb_size);
   1236 			table_buffer.pfrb_size = table_buffer.pfrb_msize;
   1237 			if (pfr_get_tables(NULL, table_buffer.pfrb_caddr,
   1238 			    &table_buffer.pfrb_size, PFR_FLAG_ALLRSETS))
   1239 				err(1, "pfr_get_tables");
   1240 			if (table_buffer.pfrb_size <= table_buffer.pfrb_msize)
   1241 				break;
   1242 		}
   1243 		table_identifier = arc4random();
   1244 	}
   1245 
   1246 	/* XXX would be *really* nice to avoid duplicating identical tables */
   1247 
   1248 	/* Now we have to pick a table name that isn't used */
   1249 again:
   1250 	DEBUG("translating temporary table <%s> to <%s%x_%d>", tbl->pt_name,
   1251 	    PF_OPT_TABLE_PREFIX, table_identifier, tablenum);
   1252 	snprintf(tbl->pt_name, sizeof(tbl->pt_name), "%s%x_%d",
   1253 	    PF_OPT_TABLE_PREFIX, table_identifier, tablenum);
   1254 	PFRB_FOREACH(t, &table_buffer) {
   1255 		if (strcasecmp(t->pfrt_name, tbl->pt_name) == 0) {
   1256 			/* Collision.  Try again */
   1257 			DEBUG("wow, table <%s> in use.  trying again",
   1258 			    tbl->pt_name);
   1259 			table_identifier = arc4random();
   1260 			goto again;
   1261 		}
   1262 	}
   1263 	tablenum++;
   1264 
   1265 
   1266 	if (pfctl_define_table(tbl->pt_name, PFR_TFLAG_CONST, 1, pf->anchor,
   1267 	    tbl->pt_buf, pf->tticket))
   1268 		return (1);
   1269 	return (0);
   1270 }
   1271 
   1272 /*
   1273  * Partition the flat ruleset into a list of distinct superblocks
   1274  */
   1275 int
   1276 construct_superblocks(struct pfctl *pf, struct pf_opt_queue *opt_queue,
   1277     struct superblocks *superblocks)
   1278 {
   1279 	struct superblock *block = NULL;
   1280 	struct pf_opt_rule *por;
   1281 	int i;
   1282 
   1283 	while (!TAILQ_EMPTY(opt_queue)) {
   1284 		por = TAILQ_FIRST(opt_queue);
   1285 		TAILQ_REMOVE(opt_queue, por, por_entry);
   1286 		if (block == NULL || !superblock_inclusive(block, por)) {
   1287 			if ((block = calloc(1, sizeof(*block))) == NULL) {
   1288 				warn("calloc");
   1289 				return (1);
   1290 			}
   1291 			TAILQ_INIT(&block->sb_rules);
   1292 			for (i = 0; i < PF_SKIP_COUNT; i++)
   1293 				TAILQ_INIT(&block->sb_skipsteps[i]);
   1294 			TAILQ_INSERT_TAIL(superblocks, block, sb_entry);
   1295 		}
   1296 		TAILQ_INSERT_TAIL(&block->sb_rules, por, por_entry);
   1297 	}
   1298 
   1299 	return (0);
   1300 }
   1301 
   1302 
   1303 /*
   1304  * Compare two rule addresses
   1305  */
   1306 int
   1307 addrs_equal(struct pf_rule_addr *a, struct pf_rule_addr *b)
   1308 {
   1309 	if (a->neg != b->neg)
   1310 		return (0);
   1311 	return (memcmp(&a->addr, &b->addr, sizeof(a->addr)) == 0);
   1312 }
   1313 
   1314 
   1315 /*
   1316  * The addresses are not equal, but can we combine them into one table?
   1317  */
   1318 int
   1319 addrs_combineable(struct pf_rule_addr *a, struct pf_rule_addr *b)
   1320 {
   1321 	if (a->addr.type != PF_ADDR_ADDRMASK &&
   1322 	    b->addr.type != PF_ADDR_ADDRMASK)
   1323 		return (0);
   1324 	if (a->neg != b->neg || a->port_op != b->port_op ||
   1325 	    a->port[0] != b->port[0] || a->port[1] != b->port[1])
   1326 		return (0);
   1327 	return (1);
   1328 }
   1329 
   1330 
   1331 /*
   1332  * Are we allowed to combine these two rules
   1333  */
   1334 int
   1335 rules_combineable(struct pf_rule *p1, struct pf_rule *p2)
   1336 {
   1337 	struct pf_rule a, b;
   1338 
   1339 	comparable_rule(&a, p1, COMBINED);
   1340 	comparable_rule(&b, p2, COMBINED);
   1341 	return (memcmp(&a, &b, sizeof(a)) == 0);
   1342 }
   1343 
   1344 
   1345 /*
   1346  * Can a rule be included inside a superblock
   1347  */
   1348 int
   1349 superblock_inclusive(struct superblock *block, struct pf_opt_rule *por)
   1350 {
   1351 	struct pf_rule a, b;
   1352 	int i, j;
   1353 
   1354 	/* First check for hard breaks */
   1355 	for (i = 0; i < sizeof(pf_rule_desc)/sizeof(*pf_rule_desc); i++) {
   1356 		if (pf_rule_desc[i].prf_type == BARRIER) {
   1357 			for (j = 0; j < pf_rule_desc[i].prf_size; j++)
   1358 				if (((char *)&por->por_rule)[j +
   1359 				    pf_rule_desc[i].prf_offset] != 0)
   1360 					return (0);
   1361 		}
   1362 	}
   1363 
   1364 	/* 'anchor' heads and per-rule src-track are also hard breaks */
   1365 	if (por->por_anchor[0] != '\0' ||
   1366 	    (por->por_rule.rule_flag & PFRULE_RULESRCTRACK))
   1367 		return (0);
   1368 
   1369 	comparable_rule(&a, &TAILQ_FIRST(&block->sb_rules)->por_rule, NOMERGE);
   1370 	comparable_rule(&b, &por->por_rule, NOMERGE);
   1371 	if (strcmp(TAILQ_FIRST(&block->sb_rules)->por_anchor,
   1372 	    por->por_anchor) == 0 && memcmp(&a, &b, sizeof(a)) == 0)
   1373 		return (1);
   1374 
   1375 #ifdef OPT_DEBUG
   1376 	for (i = 0; i < sizeof(por->por_rule); i++) {
   1377 		int closest = -1;
   1378 		if (((u_int8_t *)&a)[i] != ((u_int8_t *)&b)[i]) {
   1379 			for (j = 0; j < sizeof(pf_rule_desc) /
   1380 			    sizeof(*pf_rule_desc); j++) {
   1381 				if (i >= pf_rule_desc[j].prf_offset &&
   1382 				    i < pf_rule_desc[j].prf_offset +
   1383 				    pf_rule_desc[j].prf_size) {
   1384 					DEBUG("superblock break @ %d due to %s",
   1385 					    por->por_rule.nr,
   1386 					    pf_rule_desc[j].prf_name);
   1387 					return (0);
   1388 				}
   1389 				if (i > pf_rule_desc[j].prf_offset) {
   1390 					if (closest == -1 ||
   1391 					    i-pf_rule_desc[j].prf_offset <
   1392 					    i-pf_rule_desc[closest].prf_offset)
   1393 						closest = j;
   1394 				}
   1395 			}
   1396 
   1397 			if (closest >= 0)
   1398 				DEBUG("superblock break @ %d on %s+%xh",
   1399 				    por->por_rule.nr,
   1400 				    pf_rule_desc[closest].prf_name,
   1401 				    i - pf_rule_desc[closest].prf_offset -
   1402 				    pf_rule_desc[closest].prf_size);
   1403 			else
   1404 				DEBUG("superblock break @ %d on field @ %d",
   1405 				    por->por_rule.nr, i);
   1406 			return (0);
   1407 		}
   1408 	}
   1409 #endif /* OPT_DEBUG */
   1410 
   1411 	return (0);
   1412 }
   1413 
   1414 
   1415 /*
   1416  * Make a rule that can directly compared by memcmp()
   1417  */
   1418 void
   1419 comparable_rule(struct pf_rule *dst, const struct pf_rule *src, int type)
   1420 {
   1421 	int i;
   1422 	/*
   1423 	 * To simplify the comparison, we just zero out the fields that are
   1424 	 * allowed to be different and then do a simple memcmp()
   1425 	 */
   1426 	memcpy(dst, src, sizeof(*dst));
   1427 	for (i = 0; i < sizeof(pf_rule_desc)/sizeof(*pf_rule_desc); i++)
   1428 		if (pf_rule_desc[i].prf_type >= type) {
   1429 #ifdef OPT_DEBUG
   1430 			assert(pf_rule_desc[i].prf_type != NEVER ||
   1431 			    *(((char *)dst) + pf_rule_desc[i].prf_offset) == 0);
   1432 #endif /* OPT_DEBUG */
   1433 			memset(((char *)dst) + pf_rule_desc[i].prf_offset, 0,
   1434 			    pf_rule_desc[i].prf_size);
   1435 		}
   1436 }
   1437 
   1438 
   1439 /*
   1440  * Remove superset information from two rules so we can directly compare them
   1441  * with memcmp()
   1442  */
   1443 void
   1444 exclude_supersets(struct pf_rule *super, struct pf_rule *sub)
   1445 {
   1446 	if (super->ifname[0] == '\0')
   1447 		memset(sub->ifname, 0, sizeof(sub->ifname));
   1448 	if (super->direction == PF_INOUT)
   1449 		sub->direction = PF_INOUT;
   1450 	if ((super->proto == 0 || super->proto == sub->proto) &&
   1451 	    super->flags == 0 && super->flagset == 0 && (sub->flags ||
   1452 	    sub->flagset)) {
   1453 		sub->flags = super->flags;
   1454 		sub->flagset = super->flagset;
   1455 	}
   1456 	if (super->proto == 0)
   1457 		sub->proto = 0;
   1458 
   1459 	if (super->src.port_op == 0) {
   1460 		sub->src.port_op = 0;
   1461 		sub->src.port[0] = 0;
   1462 		sub->src.port[1] = 0;
   1463 	}
   1464 	if (super->dst.port_op == 0) {
   1465 		sub->dst.port_op = 0;
   1466 		sub->dst.port[0] = 0;
   1467 		sub->dst.port[1] = 0;
   1468 	}
   1469 
   1470 	if (super->src.addr.type == PF_ADDR_ADDRMASK && !super->src.neg &&
   1471 	    !sub->src.neg && super->src.addr.v.a.mask.addr32[0] == 0 &&
   1472 	    super->src.addr.v.a.mask.addr32[1] == 0 &&
   1473 	    super->src.addr.v.a.mask.addr32[2] == 0 &&
   1474 	    super->src.addr.v.a.mask.addr32[3] == 0)
   1475 		memset(&sub->src.addr, 0, sizeof(sub->src.addr));
   1476 	else if (super->src.addr.type == PF_ADDR_ADDRMASK &&
   1477 	    sub->src.addr.type == PF_ADDR_ADDRMASK &&
   1478 	    super->src.neg == sub->src.neg &&
   1479 	    super->af == sub->af &&
   1480 	    unmask(&super->src.addr.v.a.mask, super->af) <
   1481 	    unmask(&sub->src.addr.v.a.mask, sub->af) &&
   1482 	    super->src.addr.v.a.addr.addr32[0] ==
   1483 	    (sub->src.addr.v.a.addr.addr32[0] &
   1484 	    super->src.addr.v.a.mask.addr32[0]) &&
   1485 	    super->src.addr.v.a.addr.addr32[1] ==
   1486 	    (sub->src.addr.v.a.addr.addr32[1] &
   1487 	    super->src.addr.v.a.mask.addr32[1]) &&
   1488 	    super->src.addr.v.a.addr.addr32[2] ==
   1489 	    (sub->src.addr.v.a.addr.addr32[2] &
   1490 	    super->src.addr.v.a.mask.addr32[2]) &&
   1491 	    super->src.addr.v.a.addr.addr32[3] ==
   1492 	    (sub->src.addr.v.a.addr.addr32[3] &
   1493 	    super->src.addr.v.a.mask.addr32[3])) {
   1494 		/* sub->src.addr is a subset of super->src.addr/mask */
   1495 		memcpy(&sub->src.addr, &super->src.addr, sizeof(sub->src.addr));
   1496 	}
   1497 
   1498 	if (super->dst.addr.type == PF_ADDR_ADDRMASK && !super->dst.neg &&
   1499 	    !sub->dst.neg && super->dst.addr.v.a.mask.addr32[0] == 0 &&
   1500 	    super->dst.addr.v.a.mask.addr32[1] == 0 &&
   1501 	    super->dst.addr.v.a.mask.addr32[2] == 0 &&
   1502 	    super->dst.addr.v.a.mask.addr32[3] == 0)
   1503 		memset(&sub->dst.addr, 0, sizeof(sub->dst.addr));
   1504 	else if (super->dst.addr.type == PF_ADDR_ADDRMASK &&
   1505 	    sub->dst.addr.type == PF_ADDR_ADDRMASK &&
   1506 	    super->dst.neg == sub->dst.neg &&
   1507 	    super->af == sub->af &&
   1508 	    unmask(&super->dst.addr.v.a.mask, super->af) <
   1509 	    unmask(&sub->dst.addr.v.a.mask, sub->af) &&
   1510 	    super->dst.addr.v.a.addr.addr32[0] ==
   1511 	    (sub->dst.addr.v.a.addr.addr32[0] &
   1512 	    super->dst.addr.v.a.mask.addr32[0]) &&
   1513 	    super->dst.addr.v.a.addr.addr32[1] ==
   1514 	    (sub->dst.addr.v.a.addr.addr32[1] &
   1515 	    super->dst.addr.v.a.mask.addr32[1]) &&
   1516 	    super->dst.addr.v.a.addr.addr32[2] ==
   1517 	    (sub->dst.addr.v.a.addr.addr32[2] &
   1518 	    super->dst.addr.v.a.mask.addr32[2]) &&
   1519 	    super->dst.addr.v.a.addr.addr32[3] ==
   1520 	    (sub->dst.addr.v.a.addr.addr32[3] &
   1521 	    super->dst.addr.v.a.mask.addr32[3])) {
   1522 		/* sub->dst.addr is a subset of super->dst.addr/mask */
   1523 		memcpy(&sub->dst.addr, &super->dst.addr, sizeof(sub->dst.addr));
   1524 	}
   1525 
   1526 	if (super->af == 0)
   1527 		sub->af = 0;
   1528 }
   1529 
   1530 
   1531 void
   1532 superblock_free(struct pfctl *pf, struct superblock *block)
   1533 {
   1534 	struct pf_opt_rule *por;
   1535 	while ((por = TAILQ_FIRST(&block->sb_rules))) {
   1536 		TAILQ_REMOVE(&block->sb_rules, por, por_entry);
   1537 		if (por->por_src_tbl) {
   1538 			if (por->por_src_tbl->pt_buf) {
   1539 				pfr_buf_clear(por->por_src_tbl->pt_buf);
   1540 				free(por->por_src_tbl->pt_buf);
   1541 			}
   1542 			free(por->por_src_tbl);
   1543 		}
   1544 		if (por->por_dst_tbl) {
   1545 			if (por->por_dst_tbl->pt_buf) {
   1546 				pfr_buf_clear(por->por_dst_tbl->pt_buf);
   1547 				free(por->por_dst_tbl->pt_buf);
   1548 			}
   1549 			free(por->por_dst_tbl);
   1550 		}
   1551 		free(por);
   1552 	}
   1553 	if (block->sb_profiled_block)
   1554 		superblock_free(pf, block->sb_profiled_block);
   1555 	free(block);
   1556 }
   1557 
   1558