xref: /freebsd/sys/netpfil/pf/if_pfsync.c (revision 25ecdc7d52770caf1c9b44b5ec11f468f6b636f3)
1 /*-
2  * SPDX-License-Identifier: (BSD-2-Clause-FreeBSD AND ISC)
3  *
4  * Copyright (c) 2002 Michael Shalayeff
5  * Copyright (c) 2012 Gleb Smirnoff <glebius@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
21  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23  * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
25  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
26  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 /*-
31  * Copyright (c) 2009 David Gwynne <dlg@openbsd.org>
32  *
33  * Permission to use, copy, modify, and distribute this software for any
34  * purpose with or without fee is hereby granted, provided that the above
35  * copyright notice and this permission notice appear in all copies.
36  *
37  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
38  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
39  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
40  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
41  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
42  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
43  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
44  */
45 
46 /*
47  * $OpenBSD: if_pfsync.c,v 1.110 2009/02/24 05:39:19 dlg Exp $
48  *
49  * Revisions picked from OpenBSD after revision 1.110 import:
50  * 1.119 - don't m_copydata() beyond the len of mbuf in pfsync_input()
51  * 1.118, 1.124, 1.148, 1.149, 1.151, 1.171 - fixes to bulk updates
52  * 1.120, 1.175 - use monotonic time_uptime
53  * 1.122 - reduce number of updates for non-TCP sessions
54  * 1.125, 1.127 - rewrite merge or stale processing
55  * 1.128 - cleanups
56  * 1.146 - bzero() mbuf before sparsely filling it with data
57  * 1.170 - SIOCSIFMTU checks
58  * 1.126, 1.142 - deferred packets processing
59  * 1.173 - correct expire time processing
60  */
61 
62 #include <sys/cdefs.h>
63 __FBSDID("$FreeBSD$");
64 
65 #include "opt_inet.h"
66 #include "opt_inet6.h"
67 #include "opt_pf.h"
68 
69 #include <sys/param.h>
70 #include <sys/bus.h>
71 #include <sys/endian.h>
72 #include <sys/interrupt.h>
73 #include <sys/kernel.h>
74 #include <sys/lock.h>
75 #include <sys/mbuf.h>
76 #include <sys/module.h>
77 #include <sys/mutex.h>
78 #include <sys/priv.h>
79 #include <sys/protosw.h>
80 #include <sys/smp.h>
81 #include <sys/socket.h>
82 #include <sys/sockio.h>
83 #include <sys/sysctl.h>
84 #include <sys/syslog.h>
85 
86 #include <net/bpf.h>
87 #include <net/if.h>
88 #include <net/if_var.h>
89 #include <net/if_clone.h>
90 #include <net/if_types.h>
91 #include <net/vnet.h>
92 #include <net/pfvar.h>
93 #include <net/if_pfsync.h>
94 
95 #include <netinet/if_ether.h>
96 #include <netinet/in.h>
97 #include <netinet/in_var.h>
98 #include <netinet/ip.h>
99 #include <netinet/ip_carp.h>
100 #include <netinet/ip_var.h>
101 #include <netinet/tcp.h>
102 #include <netinet/tcp_fsm.h>
103 #include <netinet/tcp_seq.h>
104 
105 #define PFSYNC_MINPKT ( \
106 	sizeof(struct ip) + \
107 	sizeof(struct pfsync_header) + \
108 	sizeof(struct pfsync_subheader) )
109 
110 struct pfsync_bucket;
111 
112 struct pfsync_pkt {
113 	struct ip *ip;
114 	struct in_addr src;
115 	u_int8_t flags;
116 };
117 
118 static int	pfsync_upd_tcp(struct pf_state *, struct pfsync_state_peer *,
119 		    struct pfsync_state_peer *);
120 static int	pfsync_in_clr(struct pfsync_pkt *, struct mbuf *, int, int);
121 static int	pfsync_in_ins(struct pfsync_pkt *, struct mbuf *, int, int);
122 static int	pfsync_in_iack(struct pfsync_pkt *, struct mbuf *, int, int);
123 static int	pfsync_in_upd(struct pfsync_pkt *, struct mbuf *, int, int);
124 static int	pfsync_in_upd_c(struct pfsync_pkt *, struct mbuf *, int, int);
125 static int	pfsync_in_ureq(struct pfsync_pkt *, struct mbuf *, int, int);
126 static int	pfsync_in_del(struct pfsync_pkt *, struct mbuf *, int, int);
127 static int	pfsync_in_del_c(struct pfsync_pkt *, struct mbuf *, int, int);
128 static int	pfsync_in_bus(struct pfsync_pkt *, struct mbuf *, int, int);
129 static int	pfsync_in_tdb(struct pfsync_pkt *, struct mbuf *, int, int);
130 static int	pfsync_in_eof(struct pfsync_pkt *, struct mbuf *, int, int);
131 static int	pfsync_in_error(struct pfsync_pkt *, struct mbuf *, int, int);
132 
133 static int (*pfsync_acts[])(struct pfsync_pkt *, struct mbuf *, int, int) = {
134 	pfsync_in_clr,			/* PFSYNC_ACT_CLR */
135 	pfsync_in_ins,			/* PFSYNC_ACT_INS */
136 	pfsync_in_iack,			/* PFSYNC_ACT_INS_ACK */
137 	pfsync_in_upd,			/* PFSYNC_ACT_UPD */
138 	pfsync_in_upd_c,		/* PFSYNC_ACT_UPD_C */
139 	pfsync_in_ureq,			/* PFSYNC_ACT_UPD_REQ */
140 	pfsync_in_del,			/* PFSYNC_ACT_DEL */
141 	pfsync_in_del_c,		/* PFSYNC_ACT_DEL_C */
142 	pfsync_in_error,		/* PFSYNC_ACT_INS_F */
143 	pfsync_in_error,		/* PFSYNC_ACT_DEL_F */
144 	pfsync_in_bus,			/* PFSYNC_ACT_BUS */
145 	pfsync_in_tdb,			/* PFSYNC_ACT_TDB */
146 	pfsync_in_eof			/* PFSYNC_ACT_EOF */
147 };
148 
149 struct pfsync_q {
150 	void		(*write)(struct pf_state *, void *);
151 	size_t		len;
152 	u_int8_t	action;
153 };
154 
155 /* we have one of these for every PFSYNC_S_ */
156 static void	pfsync_out_state(struct pf_state *, void *);
157 static void	pfsync_out_iack(struct pf_state *, void *);
158 static void	pfsync_out_upd_c(struct pf_state *, void *);
159 static void	pfsync_out_del(struct pf_state *, void *);
160 
161 static struct pfsync_q pfsync_qs[] = {
162 	{ pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_INS },
163 	{ pfsync_out_iack,  sizeof(struct pfsync_ins_ack), PFSYNC_ACT_INS_ACK },
164 	{ pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_UPD },
165 	{ pfsync_out_upd_c, sizeof(struct pfsync_upd_c),   PFSYNC_ACT_UPD_C },
166 	{ pfsync_out_del,   sizeof(struct pfsync_del_c),   PFSYNC_ACT_DEL_C }
167 };
168 
169 static void	pfsync_q_ins(struct pf_state *, int, bool);
170 static void	pfsync_q_del(struct pf_state *, bool, struct pfsync_bucket *);
171 
172 static void	pfsync_update_state(struct pf_state *);
173 
174 struct pfsync_upd_req_item {
175 	TAILQ_ENTRY(pfsync_upd_req_item)	ur_entry;
176 	struct pfsync_upd_req			ur_msg;
177 };
178 
179 struct pfsync_deferral {
180 	struct pfsync_softc		*pd_sc;
181 	TAILQ_ENTRY(pfsync_deferral)	pd_entry;
182 	u_int				pd_refs;
183 	struct callout			pd_tmo;
184 
185 	struct pf_state			*pd_st;
186 	struct mbuf			*pd_m;
187 };
188 
189 struct pfsync_sofct;
190 
191 struct pfsync_bucket
192 {
193 	int			b_id;
194 	struct pfsync_softc	*b_sc;
195 	struct mtx		b_mtx;
196 	struct callout		b_tmo;
197 	int			b_flags;
198 #define	PFSYNCF_BUCKET_PUSH	0x00000001
199 
200 	size_t			b_len;
201 	TAILQ_HEAD(, pf_state)			b_qs[PFSYNC_S_COUNT];
202 	TAILQ_HEAD(, pfsync_upd_req_item)	b_upd_req_list;
203 	TAILQ_HEAD(, pfsync_deferral)		b_deferrals;
204 	u_int			b_deferred;
205 	void			*b_plus;
206 	size_t			b_pluslen;
207 
208 	struct  ifaltq b_snd;
209 };
210 
211 struct pfsync_softc {
212 	/* Configuration */
213 	struct ifnet		*sc_ifp;
214 	struct ifnet		*sc_sync_if;
215 	struct ip_moptions	sc_imo;
216 	struct in_addr		sc_sync_peer;
217 	uint32_t		sc_flags;
218 	uint8_t			sc_maxupdates;
219 	struct ip		sc_template;
220 	struct mtx		sc_mtx;
221 
222 	/* Queued data */
223 	struct pfsync_bucket	*sc_buckets;
224 
225 	/* Bulk update info */
226 	struct mtx		sc_bulk_mtx;
227 	uint32_t		sc_ureq_sent;
228 	int			sc_bulk_tries;
229 	uint32_t		sc_ureq_received;
230 	int			sc_bulk_hashid;
231 	uint64_t		sc_bulk_stateid;
232 	uint32_t		sc_bulk_creatorid;
233 	struct callout		sc_bulk_tmo;
234 	struct callout		sc_bulkfail_tmo;
235 };
236 
237 #define	PFSYNC_LOCK(sc)		mtx_lock(&(sc)->sc_mtx)
238 #define	PFSYNC_UNLOCK(sc)	mtx_unlock(&(sc)->sc_mtx)
239 #define	PFSYNC_LOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_mtx, MA_OWNED)
240 
241 #define PFSYNC_BUCKET_LOCK(b)		mtx_lock(&(b)->b_mtx)
242 #define PFSYNC_BUCKET_UNLOCK(b)		mtx_unlock(&(b)->b_mtx)
243 #define PFSYNC_BUCKET_LOCK_ASSERT(b)	mtx_assert(&(b)->b_mtx, MA_OWNED)
244 
245 #define	PFSYNC_BLOCK(sc)	mtx_lock(&(sc)->sc_bulk_mtx)
246 #define	PFSYNC_BUNLOCK(sc)	mtx_unlock(&(sc)->sc_bulk_mtx)
247 #define	PFSYNC_BLOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_bulk_mtx, MA_OWNED)
248 
249 static const char pfsyncname[] = "pfsync";
250 static MALLOC_DEFINE(M_PFSYNC, pfsyncname, "pfsync(4) data");
251 VNET_DEFINE_STATIC(struct pfsync_softc	*, pfsyncif) = NULL;
252 #define	V_pfsyncif		VNET(pfsyncif)
253 VNET_DEFINE_STATIC(void *, pfsync_swi_cookie) = NULL;
254 #define	V_pfsync_swi_cookie	VNET(pfsync_swi_cookie)
255 VNET_DEFINE_STATIC(struct intr_event *, pfsync_swi_ie);
256 #define	V_pfsync_swi_ie		VNET(pfsync_swi_ie)
257 VNET_DEFINE_STATIC(struct pfsyncstats, pfsyncstats);
258 #define	V_pfsyncstats		VNET(pfsyncstats)
259 VNET_DEFINE_STATIC(int, pfsync_carp_adj) = CARP_MAXSKEW;
260 #define	V_pfsync_carp_adj	VNET(pfsync_carp_adj)
261 
262 static void	pfsync_timeout(void *);
263 static void	pfsync_push(struct pfsync_bucket *);
264 static void	pfsync_push_all(struct pfsync_softc *);
265 static void	pfsyncintr(void *);
266 static int	pfsync_multicast_setup(struct pfsync_softc *, struct ifnet *,
267 		    struct in_mfilter *imf);
268 static void	pfsync_multicast_cleanup(struct pfsync_softc *);
269 static void	pfsync_pointers_init(void);
270 static void	pfsync_pointers_uninit(void);
271 static int	pfsync_init(void);
272 static void	pfsync_uninit(void);
273 
274 static unsigned long pfsync_buckets;
275 
276 SYSCTL_NODE(_net, OID_AUTO, pfsync, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
277     "PFSYNC");
278 SYSCTL_STRUCT(_net_pfsync, OID_AUTO, stats, CTLFLAG_VNET | CTLFLAG_RW,
279     &VNET_NAME(pfsyncstats), pfsyncstats,
280     "PFSYNC statistics (struct pfsyncstats, net/if_pfsync.h)");
281 SYSCTL_INT(_net_pfsync, OID_AUTO, carp_demotion_factor, CTLFLAG_RW,
282     &VNET_NAME(pfsync_carp_adj), 0, "pfsync's CARP demotion factor adjustment");
283 SYSCTL_ULONG(_net_pfsync, OID_AUTO, pfsync_buckets, CTLFLAG_RDTUN,
284     &pfsync_buckets, 0, "Number of pfsync hash buckets");
285 
286 static int	pfsync_clone_create(struct if_clone *, int, caddr_t);
287 static void	pfsync_clone_destroy(struct ifnet *);
288 static int	pfsync_alloc_scrub_memory(struct pfsync_state_peer *,
289 		    struct pf_state_peer *);
290 static int	pfsyncoutput(struct ifnet *, struct mbuf *,
291 		    const struct sockaddr *, struct route *);
292 static int	pfsyncioctl(struct ifnet *, u_long, caddr_t);
293 
294 static int	pfsync_defer(struct pf_state *, struct mbuf *);
295 static void	pfsync_undefer(struct pfsync_deferral *, int);
296 static void	pfsync_undefer_state(struct pf_state *, int);
297 static void	pfsync_defer_tmo(void *);
298 
299 static void	pfsync_request_update(u_int32_t, u_int64_t);
300 static bool	pfsync_update_state_req(struct pf_state *);
301 
302 static void	pfsync_drop(struct pfsync_softc *);
303 static void	pfsync_sendout(int, int);
304 static void	pfsync_send_plus(void *, size_t);
305 
306 static void	pfsync_bulk_start(void);
307 static void	pfsync_bulk_status(u_int8_t);
308 static void	pfsync_bulk_update(void *);
309 static void	pfsync_bulk_fail(void *);
310 
311 static void	pfsync_detach_ifnet(struct ifnet *);
312 #ifdef IPSEC
313 static void	pfsync_update_net_tdb(struct pfsync_tdb *);
314 #endif
315 static struct pfsync_bucket	*pfsync_get_bucket(struct pfsync_softc *,
316 		    struct pf_state *);
317 
318 #define PFSYNC_MAX_BULKTRIES	12
319 
320 VNET_DEFINE(struct if_clone *, pfsync_cloner);
321 #define	V_pfsync_cloner	VNET(pfsync_cloner)
322 
323 static int
324 pfsync_clone_create(struct if_clone *ifc, int unit, caddr_t param)
325 {
326 	struct pfsync_softc *sc;
327 	struct ifnet *ifp;
328 	struct pfsync_bucket *b;
329 	int c, q;
330 
331 	if (unit != 0)
332 		return (EINVAL);
333 
334 	if (! pfsync_buckets)
335 		pfsync_buckets = mp_ncpus * 2;
336 
337 	sc = malloc(sizeof(struct pfsync_softc), M_PFSYNC, M_WAITOK | M_ZERO);
338 	sc->sc_flags |= PFSYNCF_OK;
339 	sc->sc_maxupdates = 128;
340 
341 	ifp = sc->sc_ifp = if_alloc(IFT_PFSYNC);
342 	if (ifp == NULL) {
343 		free(sc, M_PFSYNC);
344 		return (ENOSPC);
345 	}
346 	if_initname(ifp, pfsyncname, unit);
347 	ifp->if_softc = sc;
348 	ifp->if_ioctl = pfsyncioctl;
349 	ifp->if_output = pfsyncoutput;
350 	ifp->if_type = IFT_PFSYNC;
351 	ifp->if_hdrlen = sizeof(struct pfsync_header);
352 	ifp->if_mtu = ETHERMTU;
353 	mtx_init(&sc->sc_mtx, pfsyncname, NULL, MTX_DEF);
354 	mtx_init(&sc->sc_bulk_mtx, "pfsync bulk", NULL, MTX_DEF);
355 	callout_init_mtx(&sc->sc_bulk_tmo, &sc->sc_bulk_mtx, 0);
356 	callout_init_mtx(&sc->sc_bulkfail_tmo, &sc->sc_bulk_mtx, 0);
357 
358 	if_attach(ifp);
359 
360 	bpfattach(ifp, DLT_PFSYNC, PFSYNC_HDRLEN);
361 
362 	sc->sc_buckets = mallocarray(pfsync_buckets, sizeof(*sc->sc_buckets),
363 	    M_PFSYNC, M_ZERO | M_WAITOK);
364 	for (c = 0; c < pfsync_buckets; c++) {
365 		b = &sc->sc_buckets[c];
366 		mtx_init(&b->b_mtx, "pfsync bucket", NULL, MTX_DEF);
367 
368 		b->b_id = c;
369 		b->b_sc = sc;
370 		b->b_len = PFSYNC_MINPKT;
371 
372 		for (q = 0; q < PFSYNC_S_COUNT; q++)
373 			TAILQ_INIT(&b->b_qs[q]);
374 
375 		TAILQ_INIT(&b->b_upd_req_list);
376 		TAILQ_INIT(&b->b_deferrals);
377 
378 		callout_init(&b->b_tmo, 1);
379 
380 		b->b_snd.ifq_maxlen = ifqmaxlen;
381 	}
382 
383 	V_pfsyncif = sc;
384 
385 	return (0);
386 }
387 
388 static void
389 pfsync_clone_destroy(struct ifnet *ifp)
390 {
391 	struct pfsync_softc *sc = ifp->if_softc;
392 	struct pfsync_bucket *b;
393 	int c;
394 
395 	for (c = 0; c < pfsync_buckets; c++) {
396 		b = &sc->sc_buckets[c];
397 		/*
398 		 * At this stage, everything should have already been
399 		 * cleared by pfsync_uninit(), and we have only to
400 		 * drain callouts.
401 		 */
402 		while (b->b_deferred > 0) {
403 			struct pfsync_deferral *pd =
404 			    TAILQ_FIRST(&b->b_deferrals);
405 
406 			TAILQ_REMOVE(&b->b_deferrals, pd, pd_entry);
407 			b->b_deferred--;
408 			if (callout_stop(&pd->pd_tmo) > 0) {
409 				pf_release_state(pd->pd_st);
410 				m_freem(pd->pd_m);
411 				free(pd, M_PFSYNC);
412 			} else {
413 				pd->pd_refs++;
414 				callout_drain(&pd->pd_tmo);
415 				free(pd, M_PFSYNC);
416 			}
417 		}
418 
419 		callout_drain(&b->b_tmo);
420 	}
421 
422 	callout_drain(&sc->sc_bulkfail_tmo);
423 	callout_drain(&sc->sc_bulk_tmo);
424 
425 	if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
426 		(*carp_demote_adj_p)(-V_pfsync_carp_adj, "pfsync destroy");
427 	bpfdetach(ifp);
428 	if_detach(ifp);
429 
430 	pfsync_drop(sc);
431 
432 	if_free(ifp);
433 	pfsync_multicast_cleanup(sc);
434 	mtx_destroy(&sc->sc_mtx);
435 	mtx_destroy(&sc->sc_bulk_mtx);
436 
437 	free(sc->sc_buckets, M_PFSYNC);
438 	free(sc, M_PFSYNC);
439 
440 	V_pfsyncif = NULL;
441 }
442 
443 static int
444 pfsync_alloc_scrub_memory(struct pfsync_state_peer *s,
445     struct pf_state_peer *d)
446 {
447 	if (s->scrub.scrub_flag && d->scrub == NULL) {
448 		d->scrub = uma_zalloc(V_pf_state_scrub_z, M_NOWAIT | M_ZERO);
449 		if (d->scrub == NULL)
450 			return (ENOMEM);
451 	}
452 
453 	return (0);
454 }
455 
456 static int
457 pfsync_state_import(struct pfsync_state *sp, u_int8_t flags)
458 {
459 	struct pfsync_softc *sc = V_pfsyncif;
460 #ifndef	__NO_STRICT_ALIGNMENT
461 	struct pfsync_state_key key[2];
462 #endif
463 	struct pfsync_state_key *kw, *ks;
464 	struct pf_state	*st = NULL;
465 	struct pf_state_key *skw = NULL, *sks = NULL;
466 	struct pf_krule *r = NULL;
467 	struct pfi_kkif	*kif;
468 	int error;
469 
470 	PF_RULES_RASSERT();
471 
472 	if (sp->creatorid == 0) {
473 		if (V_pf_status.debug >= PF_DEBUG_MISC)
474 			printf("%s: invalid creator id: %08x\n", __func__,
475 			    ntohl(sp->creatorid));
476 		return (EINVAL);
477 	}
478 
479 	if ((kif = pfi_kkif_find(sp->ifname)) == NULL) {
480 		if (V_pf_status.debug >= PF_DEBUG_MISC)
481 			printf("%s: unknown interface: %s\n", __func__,
482 			    sp->ifname);
483 		if (flags & PFSYNC_SI_IOCTL)
484 			return (EINVAL);
485 		return (0);	/* skip this state */
486 	}
487 
488 	/*
489 	 * If the ruleset checksums match or the state is coming from the ioctl,
490 	 * it's safe to associate the state with the rule of that number.
491 	 */
492 	if (sp->rule != htonl(-1) && sp->anchor == htonl(-1) &&
493 	    (flags & (PFSYNC_SI_IOCTL | PFSYNC_SI_CKSUM)) && ntohl(sp->rule) <
494 	    pf_main_ruleset.rules[PF_RULESET_FILTER].active.rcount)
495 		r = pf_main_ruleset.rules[
496 		    PF_RULESET_FILTER].active.ptr_array[ntohl(sp->rule)];
497 	else
498 		r = &V_pf_default_rule;
499 
500 	if ((r->max_states &&
501 	    counter_u64_fetch(r->states_cur) >= r->max_states))
502 		goto cleanup;
503 
504 	/*
505 	 * XXXGL: consider M_WAITOK in ioctl path after.
506 	 */
507 	if ((st = uma_zalloc(V_pf_state_z, M_NOWAIT | M_ZERO)) == NULL)
508 		goto cleanup;
509 
510 	for (int i = 0; i < 2; i++) {
511 		st->packets[i] = counter_u64_alloc(M_NOWAIT);
512 		st->bytes[i] = counter_u64_alloc(M_NOWAIT);
513 		if (st->packets[i] == NULL || st->bytes[i] == NULL)
514 			goto cleanup;
515 	}
516 
517 	if ((skw = uma_zalloc(V_pf_state_key_z, M_NOWAIT)) == NULL)
518 		goto cleanup;
519 
520 #ifndef	__NO_STRICT_ALIGNMENT
521 	bcopy(&sp->key, key, sizeof(struct pfsync_state_key) * 2);
522 	kw = &key[PF_SK_WIRE];
523 	ks = &key[PF_SK_STACK];
524 #else
525 	kw = &sp->key[PF_SK_WIRE];
526 	ks = &sp->key[PF_SK_STACK];
527 #endif
528 
529 	if (PF_ANEQ(&kw->addr[0], &ks->addr[0], sp->af) ||
530 	    PF_ANEQ(&kw->addr[1], &ks->addr[1], sp->af) ||
531 	    kw->port[0] != ks->port[0] ||
532 	    kw->port[1] != ks->port[1]) {
533 		sks = uma_zalloc(V_pf_state_key_z, M_NOWAIT);
534 		if (sks == NULL)
535 			goto cleanup;
536 	} else
537 		sks = skw;
538 
539 	/* allocate memory for scrub info */
540 	if (pfsync_alloc_scrub_memory(&sp->src, &st->src) ||
541 	    pfsync_alloc_scrub_memory(&sp->dst, &st->dst))
542 		goto cleanup;
543 
544 	/* Copy to state key(s). */
545 	skw->addr[0] = kw->addr[0];
546 	skw->addr[1] = kw->addr[1];
547 	skw->port[0] = kw->port[0];
548 	skw->port[1] = kw->port[1];
549 	skw->proto = sp->proto;
550 	skw->af = sp->af;
551 	if (sks != skw) {
552 		sks->addr[0] = ks->addr[0];
553 		sks->addr[1] = ks->addr[1];
554 		sks->port[0] = ks->port[0];
555 		sks->port[1] = ks->port[1];
556 		sks->proto = sp->proto;
557 		sks->af = sp->af;
558 	}
559 
560 	/* copy to state */
561 	bcopy(&sp->rt_addr, &st->rt_addr, sizeof(st->rt_addr));
562 	st->creation = time_uptime - ntohl(sp->creation);
563 	st->expire = time_uptime;
564 	if (sp->expire) {
565 		uint32_t timeout;
566 
567 		timeout = r->timeout[sp->timeout];
568 		if (!timeout)
569 			timeout = V_pf_default_rule.timeout[sp->timeout];
570 
571 		/* sp->expire may have been adaptively scaled by export. */
572 		st->expire -= timeout - ntohl(sp->expire);
573 	}
574 
575 	st->direction = sp->direction;
576 	st->log = sp->log;
577 	st->timeout = sp->timeout;
578 	st->state_flags = sp->state_flags;
579 
580 	st->id = sp->id;
581 	st->creatorid = sp->creatorid;
582 	pf_state_peer_ntoh(&sp->src, &st->src);
583 	pf_state_peer_ntoh(&sp->dst, &st->dst);
584 
585 	st->rule.ptr = r;
586 	st->nat_rule.ptr = NULL;
587 	st->anchor.ptr = NULL;
588 	st->rt_kif = NULL;
589 
590 	st->pfsync_time = time_uptime;
591 	st->sync_state = PFSYNC_S_NONE;
592 
593 	if (!(flags & PFSYNC_SI_IOCTL))
594 		st->state_flags |= PFSTATE_NOSYNC;
595 
596 	if ((error = pf_state_insert(kif, kif, skw, sks, st)) != 0)
597 		goto cleanup_state;
598 
599 	/* XXX when we have nat_rule/anchors, use STATE_INC_COUNTERS */
600 	counter_u64_add(r->states_cur, 1);
601 	counter_u64_add(r->states_tot, 1);
602 
603 	if (!(flags & PFSYNC_SI_IOCTL)) {
604 		st->state_flags &= ~PFSTATE_NOSYNC;
605 		if (st->state_flags & PFSTATE_ACK) {
606 			pfsync_q_ins(st, PFSYNC_S_IACK, true);
607 			pfsync_push_all(sc);
608 		}
609 	}
610 	st->state_flags &= ~PFSTATE_ACK;
611 	PF_STATE_UNLOCK(st);
612 
613 	return (0);
614 
615 cleanup:
616 	error = ENOMEM;
617 	if (skw == sks)
618 		sks = NULL;
619 	if (skw != NULL)
620 		uma_zfree(V_pf_state_key_z, skw);
621 	if (sks != NULL)
622 		uma_zfree(V_pf_state_key_z, sks);
623 
624 cleanup_state:	/* pf_state_insert() frees the state keys. */
625 	if (st) {
626 		for (int i = 0; i < 2; i++) {
627 			counter_u64_free(st->packets[i]);
628 			counter_u64_free(st->bytes[i]);
629 		}
630 		if (st->dst.scrub)
631 			uma_zfree(V_pf_state_scrub_z, st->dst.scrub);
632 		if (st->src.scrub)
633 			uma_zfree(V_pf_state_scrub_z, st->src.scrub);
634 		uma_zfree(V_pf_state_z, st);
635 	}
636 	return (error);
637 }
638 
639 static int
640 pfsync_input(struct mbuf **mp, int *offp __unused, int proto __unused)
641 {
642 	struct pfsync_softc *sc = V_pfsyncif;
643 	struct pfsync_pkt pkt;
644 	struct mbuf *m = *mp;
645 	struct ip *ip = mtod(m, struct ip *);
646 	struct pfsync_header *ph;
647 	struct pfsync_subheader subh;
648 
649 	int offset, len;
650 	int rv;
651 	uint16_t count;
652 
653 	PF_RULES_RLOCK_TRACKER;
654 
655 	*mp = NULL;
656 	V_pfsyncstats.pfsyncs_ipackets++;
657 
658 	/* Verify that we have a sync interface configured. */
659 	if (!sc || !sc->sc_sync_if || !V_pf_status.running ||
660 	    (sc->sc_ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
661 		goto done;
662 
663 	/* verify that the packet came in on the right interface */
664 	if (sc->sc_sync_if != m->m_pkthdr.rcvif) {
665 		V_pfsyncstats.pfsyncs_badif++;
666 		goto done;
667 	}
668 
669 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IPACKETS, 1);
670 	if_inc_counter(sc->sc_ifp, IFCOUNTER_IBYTES, m->m_pkthdr.len);
671 	/* verify that the IP TTL is 255. */
672 	if (ip->ip_ttl != PFSYNC_DFLTTL) {
673 		V_pfsyncstats.pfsyncs_badttl++;
674 		goto done;
675 	}
676 
677 	offset = ip->ip_hl << 2;
678 	if (m->m_pkthdr.len < offset + sizeof(*ph)) {
679 		V_pfsyncstats.pfsyncs_hdrops++;
680 		goto done;
681 	}
682 
683 	if (offset + sizeof(*ph) > m->m_len) {
684 		if (m_pullup(m, offset + sizeof(*ph)) == NULL) {
685 			V_pfsyncstats.pfsyncs_hdrops++;
686 			return (IPPROTO_DONE);
687 		}
688 		ip = mtod(m, struct ip *);
689 	}
690 	ph = (struct pfsync_header *)((char *)ip + offset);
691 
692 	/* verify the version */
693 	if (ph->version != PFSYNC_VERSION) {
694 		V_pfsyncstats.pfsyncs_badver++;
695 		goto done;
696 	}
697 
698 	len = ntohs(ph->len) + offset;
699 	if (m->m_pkthdr.len < len) {
700 		V_pfsyncstats.pfsyncs_badlen++;
701 		goto done;
702 	}
703 
704 	/* Cheaper to grab this now than having to mess with mbufs later */
705 	pkt.ip = ip;
706 	pkt.src = ip->ip_src;
707 	pkt.flags = 0;
708 
709 	/*
710 	 * Trusting pf_chksum during packet processing, as well as seeking
711 	 * in interface name tree, require holding PF_RULES_RLOCK().
712 	 */
713 	PF_RULES_RLOCK();
714 	if (!bcmp(&ph->pfcksum, &V_pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
715 		pkt.flags |= PFSYNC_SI_CKSUM;
716 
717 	offset += sizeof(*ph);
718 	while (offset <= len - sizeof(subh)) {
719 		m_copydata(m, offset, sizeof(subh), (caddr_t)&subh);
720 		offset += sizeof(subh);
721 
722 		if (subh.action >= PFSYNC_ACT_MAX) {
723 			V_pfsyncstats.pfsyncs_badact++;
724 			PF_RULES_RUNLOCK();
725 			goto done;
726 		}
727 
728 		count = ntohs(subh.count);
729 		V_pfsyncstats.pfsyncs_iacts[subh.action] += count;
730 		rv = (*pfsync_acts[subh.action])(&pkt, m, offset, count);
731 		if (rv == -1) {
732 			PF_RULES_RUNLOCK();
733 			return (IPPROTO_DONE);
734 		}
735 
736 		offset += rv;
737 	}
738 	PF_RULES_RUNLOCK();
739 
740 done:
741 	m_freem(m);
742 	return (IPPROTO_DONE);
743 }
744 
745 static int
746 pfsync_in_clr(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
747 {
748 	struct pfsync_clr *clr;
749 	struct mbuf *mp;
750 	int len = sizeof(*clr) * count;
751 	int i, offp;
752 	u_int32_t creatorid;
753 
754 	mp = m_pulldown(m, offset, len, &offp);
755 	if (mp == NULL) {
756 		V_pfsyncstats.pfsyncs_badlen++;
757 		return (-1);
758 	}
759 	clr = (struct pfsync_clr *)(mp->m_data + offp);
760 
761 	for (i = 0; i < count; i++) {
762 		creatorid = clr[i].creatorid;
763 
764 		if (clr[i].ifname[0] != '\0' &&
765 		    pfi_kkif_find(clr[i].ifname) == NULL)
766 			continue;
767 
768 		for (int i = 0; i <= pf_hashmask; i++) {
769 			struct pf_idhash *ih = &V_pf_idhash[i];
770 			struct pf_state *s;
771 relock:
772 			PF_HASHROW_LOCK(ih);
773 			LIST_FOREACH(s, &ih->states, entry) {
774 				if (s->creatorid == creatorid) {
775 					s->state_flags |= PFSTATE_NOSYNC;
776 					pf_unlink_state(s, PF_ENTER_LOCKED);
777 					goto relock;
778 				}
779 			}
780 			PF_HASHROW_UNLOCK(ih);
781 		}
782 	}
783 
784 	return (len);
785 }
786 
787 static int
788 pfsync_in_ins(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
789 {
790 	struct mbuf *mp;
791 	struct pfsync_state *sa, *sp;
792 	int len = sizeof(*sp) * count;
793 	int i, offp;
794 
795 	mp = m_pulldown(m, offset, len, &offp);
796 	if (mp == NULL) {
797 		V_pfsyncstats.pfsyncs_badlen++;
798 		return (-1);
799 	}
800 	sa = (struct pfsync_state *)(mp->m_data + offp);
801 
802 	for (i = 0; i < count; i++) {
803 		sp = &sa[i];
804 
805 		/* Check for invalid values. */
806 		if (sp->timeout >= PFTM_MAX ||
807 		    sp->src.state > PF_TCPS_PROXY_DST ||
808 		    sp->dst.state > PF_TCPS_PROXY_DST ||
809 		    sp->direction > PF_OUT ||
810 		    (sp->af != AF_INET && sp->af != AF_INET6)) {
811 			if (V_pf_status.debug >= PF_DEBUG_MISC)
812 				printf("%s: invalid value\n", __func__);
813 			V_pfsyncstats.pfsyncs_badval++;
814 			continue;
815 		}
816 
817 		if (pfsync_state_import(sp, pkt->flags) == ENOMEM)
818 			/* Drop out, but process the rest of the actions. */
819 			break;
820 	}
821 
822 	return (len);
823 }
824 
825 static int
826 pfsync_in_iack(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
827 {
828 	struct pfsync_ins_ack *ia, *iaa;
829 	struct pf_state *st;
830 
831 	struct mbuf *mp;
832 	int len = count * sizeof(*ia);
833 	int offp, i;
834 
835 	mp = m_pulldown(m, offset, len, &offp);
836 	if (mp == NULL) {
837 		V_pfsyncstats.pfsyncs_badlen++;
838 		return (-1);
839 	}
840 	iaa = (struct pfsync_ins_ack *)(mp->m_data + offp);
841 
842 	for (i = 0; i < count; i++) {
843 		ia = &iaa[i];
844 
845 		st = pf_find_state_byid(ia->id, ia->creatorid);
846 		if (st == NULL)
847 			continue;
848 
849 		if (st->state_flags & PFSTATE_ACK) {
850 			pfsync_undefer_state(st, 0);
851 		}
852 		PF_STATE_UNLOCK(st);
853 	}
854 	/*
855 	 * XXX this is not yet implemented, but we know the size of the
856 	 * message so we can skip it.
857 	 */
858 
859 	return (count * sizeof(struct pfsync_ins_ack));
860 }
861 
862 static int
863 pfsync_upd_tcp(struct pf_state *st, struct pfsync_state_peer *src,
864     struct pfsync_state_peer *dst)
865 {
866 	int sync = 0;
867 
868 	PF_STATE_LOCK_ASSERT(st);
869 
870 	/*
871 	 * The state should never go backwards except
872 	 * for syn-proxy states.  Neither should the
873 	 * sequence window slide backwards.
874 	 */
875 	if ((st->src.state > src->state &&
876 	    (st->src.state < PF_TCPS_PROXY_SRC ||
877 	    src->state >= PF_TCPS_PROXY_SRC)) ||
878 
879 	    (st->src.state == src->state &&
880 	    SEQ_GT(st->src.seqlo, ntohl(src->seqlo))))
881 		sync++;
882 	else
883 		pf_state_peer_ntoh(src, &st->src);
884 
885 	if ((st->dst.state > dst->state) ||
886 
887 	    (st->dst.state >= TCPS_SYN_SENT &&
888 	    SEQ_GT(st->dst.seqlo, ntohl(dst->seqlo))))
889 		sync++;
890 	else
891 		pf_state_peer_ntoh(dst, &st->dst);
892 
893 	return (sync);
894 }
895 
896 static int
897 pfsync_in_upd(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
898 {
899 	struct pfsync_softc *sc = V_pfsyncif;
900 	struct pfsync_state *sa, *sp;
901 	struct pf_state *st;
902 	int sync;
903 
904 	struct mbuf *mp;
905 	int len = count * sizeof(*sp);
906 	int offp, i;
907 
908 	mp = m_pulldown(m, offset, len, &offp);
909 	if (mp == NULL) {
910 		V_pfsyncstats.pfsyncs_badlen++;
911 		return (-1);
912 	}
913 	sa = (struct pfsync_state *)(mp->m_data + offp);
914 
915 	for (i = 0; i < count; i++) {
916 		sp = &sa[i];
917 
918 		/* check for invalid values */
919 		if (sp->timeout >= PFTM_MAX ||
920 		    sp->src.state > PF_TCPS_PROXY_DST ||
921 		    sp->dst.state > PF_TCPS_PROXY_DST) {
922 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
923 				printf("pfsync_input: PFSYNC_ACT_UPD: "
924 				    "invalid value\n");
925 			}
926 			V_pfsyncstats.pfsyncs_badval++;
927 			continue;
928 		}
929 
930 		st = pf_find_state_byid(sp->id, sp->creatorid);
931 		if (st == NULL) {
932 			/* insert the update */
933 			if (pfsync_state_import(sp, pkt->flags))
934 				V_pfsyncstats.pfsyncs_badstate++;
935 			continue;
936 		}
937 
938 		if (st->state_flags & PFSTATE_ACK) {
939 			pfsync_undefer_state(st, 1);
940 		}
941 
942 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP)
943 			sync = pfsync_upd_tcp(st, &sp->src, &sp->dst);
944 		else {
945 			sync = 0;
946 
947 			/*
948 			 * Non-TCP protocol state machine always go
949 			 * forwards
950 			 */
951 			if (st->src.state > sp->src.state)
952 				sync++;
953 			else
954 				pf_state_peer_ntoh(&sp->src, &st->src);
955 			if (st->dst.state > sp->dst.state)
956 				sync++;
957 			else
958 				pf_state_peer_ntoh(&sp->dst, &st->dst);
959 		}
960 		if (sync < 2) {
961 			pfsync_alloc_scrub_memory(&sp->dst, &st->dst);
962 			pf_state_peer_ntoh(&sp->dst, &st->dst);
963 			st->expire = time_uptime;
964 			st->timeout = sp->timeout;
965 		}
966 		st->pfsync_time = time_uptime;
967 
968 		if (sync) {
969 			V_pfsyncstats.pfsyncs_stale++;
970 
971 			pfsync_update_state(st);
972 			PF_STATE_UNLOCK(st);
973 			pfsync_push_all(sc);
974 			continue;
975 		}
976 		PF_STATE_UNLOCK(st);
977 	}
978 
979 	return (len);
980 }
981 
982 static int
983 pfsync_in_upd_c(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
984 {
985 	struct pfsync_softc *sc = V_pfsyncif;
986 	struct pfsync_upd_c *ua, *up;
987 	struct pf_state *st;
988 	int len = count * sizeof(*up);
989 	int sync;
990 	struct mbuf *mp;
991 	int offp, i;
992 
993 	mp = m_pulldown(m, offset, len, &offp);
994 	if (mp == NULL) {
995 		V_pfsyncstats.pfsyncs_badlen++;
996 		return (-1);
997 	}
998 	ua = (struct pfsync_upd_c *)(mp->m_data + offp);
999 
1000 	for (i = 0; i < count; i++) {
1001 		up = &ua[i];
1002 
1003 		/* check for invalid values */
1004 		if (up->timeout >= PFTM_MAX ||
1005 		    up->src.state > PF_TCPS_PROXY_DST ||
1006 		    up->dst.state > PF_TCPS_PROXY_DST) {
1007 			if (V_pf_status.debug >= PF_DEBUG_MISC) {
1008 				printf("pfsync_input: "
1009 				    "PFSYNC_ACT_UPD_C: "
1010 				    "invalid value\n");
1011 			}
1012 			V_pfsyncstats.pfsyncs_badval++;
1013 			continue;
1014 		}
1015 
1016 		st = pf_find_state_byid(up->id, up->creatorid);
1017 		if (st == NULL) {
1018 			/* We don't have this state. Ask for it. */
1019 			PFSYNC_BUCKET_LOCK(&sc->sc_buckets[0]);
1020 			pfsync_request_update(up->creatorid, up->id);
1021 			PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[0]);
1022 			continue;
1023 		}
1024 
1025 		if (st->state_flags & PFSTATE_ACK) {
1026 			pfsync_undefer_state(st, 1);
1027 		}
1028 
1029 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP)
1030 			sync = pfsync_upd_tcp(st, &up->src, &up->dst);
1031 		else {
1032 			sync = 0;
1033 
1034 			/*
1035 			 * Non-TCP protocol state machine always go
1036 			 * forwards
1037 			 */
1038 			if (st->src.state > up->src.state)
1039 				sync++;
1040 			else
1041 				pf_state_peer_ntoh(&up->src, &st->src);
1042 			if (st->dst.state > up->dst.state)
1043 				sync++;
1044 			else
1045 				pf_state_peer_ntoh(&up->dst, &st->dst);
1046 		}
1047 		if (sync < 2) {
1048 			pfsync_alloc_scrub_memory(&up->dst, &st->dst);
1049 			pf_state_peer_ntoh(&up->dst, &st->dst);
1050 			st->expire = time_uptime;
1051 			st->timeout = up->timeout;
1052 		}
1053 		st->pfsync_time = time_uptime;
1054 
1055 		if (sync) {
1056 			V_pfsyncstats.pfsyncs_stale++;
1057 
1058 			pfsync_update_state(st);
1059 			PF_STATE_UNLOCK(st);
1060 			pfsync_push_all(sc);
1061 			continue;
1062 		}
1063 		PF_STATE_UNLOCK(st);
1064 	}
1065 
1066 	return (len);
1067 }
1068 
1069 static int
1070 pfsync_in_ureq(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1071 {
1072 	struct pfsync_upd_req *ur, *ura;
1073 	struct mbuf *mp;
1074 	int len = count * sizeof(*ur);
1075 	int i, offp;
1076 
1077 	struct pf_state *st;
1078 
1079 	mp = m_pulldown(m, offset, len, &offp);
1080 	if (mp == NULL) {
1081 		V_pfsyncstats.pfsyncs_badlen++;
1082 		return (-1);
1083 	}
1084 	ura = (struct pfsync_upd_req *)(mp->m_data + offp);
1085 
1086 	for (i = 0; i < count; i++) {
1087 		ur = &ura[i];
1088 
1089 		if (ur->id == 0 && ur->creatorid == 0)
1090 			pfsync_bulk_start();
1091 		else {
1092 			st = pf_find_state_byid(ur->id, ur->creatorid);
1093 			if (st == NULL) {
1094 				V_pfsyncstats.pfsyncs_badstate++;
1095 				continue;
1096 			}
1097 			if (st->state_flags & PFSTATE_NOSYNC) {
1098 				PF_STATE_UNLOCK(st);
1099 				continue;
1100 			}
1101 
1102 			pfsync_update_state_req(st);
1103 			PF_STATE_UNLOCK(st);
1104 		}
1105 	}
1106 
1107 	return (len);
1108 }
1109 
1110 static int
1111 pfsync_in_del(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1112 {
1113 	struct mbuf *mp;
1114 	struct pfsync_state *sa, *sp;
1115 	struct pf_state *st;
1116 	int len = count * sizeof(*sp);
1117 	int offp, i;
1118 
1119 	mp = m_pulldown(m, offset, len, &offp);
1120 	if (mp == NULL) {
1121 		V_pfsyncstats.pfsyncs_badlen++;
1122 		return (-1);
1123 	}
1124 	sa = (struct pfsync_state *)(mp->m_data + offp);
1125 
1126 	for (i = 0; i < count; i++) {
1127 		sp = &sa[i];
1128 
1129 		st = pf_find_state_byid(sp->id, sp->creatorid);
1130 		if (st == NULL) {
1131 			V_pfsyncstats.pfsyncs_badstate++;
1132 			continue;
1133 		}
1134 		st->state_flags |= PFSTATE_NOSYNC;
1135 		pf_unlink_state(st, PF_ENTER_LOCKED);
1136 	}
1137 
1138 	return (len);
1139 }
1140 
1141 static int
1142 pfsync_in_del_c(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1143 {
1144 	struct mbuf *mp;
1145 	struct pfsync_del_c *sa, *sp;
1146 	struct pf_state *st;
1147 	int len = count * sizeof(*sp);
1148 	int offp, i;
1149 
1150 	mp = m_pulldown(m, offset, len, &offp);
1151 	if (mp == NULL) {
1152 		V_pfsyncstats.pfsyncs_badlen++;
1153 		return (-1);
1154 	}
1155 	sa = (struct pfsync_del_c *)(mp->m_data + offp);
1156 
1157 	for (i = 0; i < count; i++) {
1158 		sp = &sa[i];
1159 
1160 		st = pf_find_state_byid(sp->id, sp->creatorid);
1161 		if (st == NULL) {
1162 			V_pfsyncstats.pfsyncs_badstate++;
1163 			continue;
1164 		}
1165 
1166 		st->state_flags |= PFSTATE_NOSYNC;
1167 		pf_unlink_state(st, PF_ENTER_LOCKED);
1168 	}
1169 
1170 	return (len);
1171 }
1172 
1173 static int
1174 pfsync_in_bus(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1175 {
1176 	struct pfsync_softc *sc = V_pfsyncif;
1177 	struct pfsync_bus *bus;
1178 	struct mbuf *mp;
1179 	int len = count * sizeof(*bus);
1180 	int offp;
1181 
1182 	PFSYNC_BLOCK(sc);
1183 
1184 	/* If we're not waiting for a bulk update, who cares. */
1185 	if (sc->sc_ureq_sent == 0) {
1186 		PFSYNC_BUNLOCK(sc);
1187 		return (len);
1188 	}
1189 
1190 	mp = m_pulldown(m, offset, len, &offp);
1191 	if (mp == NULL) {
1192 		PFSYNC_BUNLOCK(sc);
1193 		V_pfsyncstats.pfsyncs_badlen++;
1194 		return (-1);
1195 	}
1196 	bus = (struct pfsync_bus *)(mp->m_data + offp);
1197 
1198 	switch (bus->status) {
1199 	case PFSYNC_BUS_START:
1200 		callout_reset(&sc->sc_bulkfail_tmo, 4 * hz +
1201 		    V_pf_limits[PF_LIMIT_STATES].limit /
1202 		    ((sc->sc_ifp->if_mtu - PFSYNC_MINPKT) /
1203 		    sizeof(struct pfsync_state)),
1204 		    pfsync_bulk_fail, sc);
1205 		if (V_pf_status.debug >= PF_DEBUG_MISC)
1206 			printf("pfsync: received bulk update start\n");
1207 		break;
1208 
1209 	case PFSYNC_BUS_END:
1210 		if (time_uptime - ntohl(bus->endtime) >=
1211 		    sc->sc_ureq_sent) {
1212 			/* that's it, we're happy */
1213 			sc->sc_ureq_sent = 0;
1214 			sc->sc_bulk_tries = 0;
1215 			callout_stop(&sc->sc_bulkfail_tmo);
1216 			if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
1217 				(*carp_demote_adj_p)(-V_pfsync_carp_adj,
1218 				    "pfsync bulk done");
1219 			sc->sc_flags |= PFSYNCF_OK;
1220 			if (V_pf_status.debug >= PF_DEBUG_MISC)
1221 				printf("pfsync: received valid "
1222 				    "bulk update end\n");
1223 		} else {
1224 			if (V_pf_status.debug >= PF_DEBUG_MISC)
1225 				printf("pfsync: received invalid "
1226 				    "bulk update end: bad timestamp\n");
1227 		}
1228 		break;
1229 	}
1230 	PFSYNC_BUNLOCK(sc);
1231 
1232 	return (len);
1233 }
1234 
1235 static int
1236 pfsync_in_tdb(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1237 {
1238 	int len = count * sizeof(struct pfsync_tdb);
1239 
1240 #if defined(IPSEC)
1241 	struct pfsync_tdb *tp;
1242 	struct mbuf *mp;
1243 	int offp;
1244 	int i;
1245 	int s;
1246 
1247 	mp = m_pulldown(m, offset, len, &offp);
1248 	if (mp == NULL) {
1249 		V_pfsyncstats.pfsyncs_badlen++;
1250 		return (-1);
1251 	}
1252 	tp = (struct pfsync_tdb *)(mp->m_data + offp);
1253 
1254 	for (i = 0; i < count; i++)
1255 		pfsync_update_net_tdb(&tp[i]);
1256 #endif
1257 
1258 	return (len);
1259 }
1260 
1261 #if defined(IPSEC)
1262 /* Update an in-kernel tdb. Silently fail if no tdb is found. */
1263 static void
1264 pfsync_update_net_tdb(struct pfsync_tdb *pt)
1265 {
1266 	struct tdb		*tdb;
1267 	int			 s;
1268 
1269 	/* check for invalid values */
1270 	if (ntohl(pt->spi) <= SPI_RESERVED_MAX ||
1271 	    (pt->dst.sa.sa_family != AF_INET &&
1272 	    pt->dst.sa.sa_family != AF_INET6))
1273 		goto bad;
1274 
1275 	tdb = gettdb(pt->spi, &pt->dst, pt->sproto);
1276 	if (tdb) {
1277 		pt->rpl = ntohl(pt->rpl);
1278 		pt->cur_bytes = (unsigned long long)be64toh(pt->cur_bytes);
1279 
1280 		/* Neither replay nor byte counter should ever decrease. */
1281 		if (pt->rpl < tdb->tdb_rpl ||
1282 		    pt->cur_bytes < tdb->tdb_cur_bytes) {
1283 			goto bad;
1284 		}
1285 
1286 		tdb->tdb_rpl = pt->rpl;
1287 		tdb->tdb_cur_bytes = pt->cur_bytes;
1288 	}
1289 	return;
1290 
1291 bad:
1292 	if (V_pf_status.debug >= PF_DEBUG_MISC)
1293 		printf("pfsync_insert: PFSYNC_ACT_TDB_UPD: "
1294 		    "invalid value\n");
1295 	V_pfsyncstats.pfsyncs_badstate++;
1296 	return;
1297 }
1298 #endif
1299 
1300 static int
1301 pfsync_in_eof(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1302 {
1303 	/* check if we are at the right place in the packet */
1304 	if (offset != m->m_pkthdr.len)
1305 		V_pfsyncstats.pfsyncs_badlen++;
1306 
1307 	/* we're done. free and let the caller return */
1308 	m_freem(m);
1309 	return (-1);
1310 }
1311 
1312 static int
1313 pfsync_in_error(struct pfsync_pkt *pkt, struct mbuf *m, int offset, int count)
1314 {
1315 	V_pfsyncstats.pfsyncs_badact++;
1316 
1317 	m_freem(m);
1318 	return (-1);
1319 }
1320 
1321 static int
1322 pfsyncoutput(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *dst,
1323 	struct route *rt)
1324 {
1325 	m_freem(m);
1326 	return (0);
1327 }
1328 
1329 /* ARGSUSED */
1330 static int
1331 pfsyncioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1332 {
1333 	struct pfsync_softc *sc = ifp->if_softc;
1334 	struct ifreq *ifr = (struct ifreq *)data;
1335 	struct pfsyncreq pfsyncr;
1336 	int error;
1337 	int c;
1338 
1339 	switch (cmd) {
1340 	case SIOCSIFFLAGS:
1341 		PFSYNC_LOCK(sc);
1342 		if (ifp->if_flags & IFF_UP) {
1343 			ifp->if_drv_flags |= IFF_DRV_RUNNING;
1344 			PFSYNC_UNLOCK(sc);
1345 			pfsync_pointers_init();
1346 		} else {
1347 			ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1348 			PFSYNC_UNLOCK(sc);
1349 			pfsync_pointers_uninit();
1350 		}
1351 		break;
1352 	case SIOCSIFMTU:
1353 		if (!sc->sc_sync_if ||
1354 		    ifr->ifr_mtu <= PFSYNC_MINPKT ||
1355 		    ifr->ifr_mtu > sc->sc_sync_if->if_mtu)
1356 			return (EINVAL);
1357 		if (ifr->ifr_mtu < ifp->if_mtu) {
1358 			for (c = 0; c < pfsync_buckets; c++) {
1359 				PFSYNC_BUCKET_LOCK(&sc->sc_buckets[c]);
1360 				if (sc->sc_buckets[c].b_len > PFSYNC_MINPKT)
1361 					pfsync_sendout(1, c);
1362 				PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[c]);
1363 			}
1364 		}
1365 		ifp->if_mtu = ifr->ifr_mtu;
1366 		break;
1367 	case SIOCGETPFSYNC:
1368 		bzero(&pfsyncr, sizeof(pfsyncr));
1369 		PFSYNC_LOCK(sc);
1370 		if (sc->sc_sync_if) {
1371 			strlcpy(pfsyncr.pfsyncr_syncdev,
1372 			    sc->sc_sync_if->if_xname, IFNAMSIZ);
1373 		}
1374 		pfsyncr.pfsyncr_syncpeer = sc->sc_sync_peer;
1375 		pfsyncr.pfsyncr_maxupdates = sc->sc_maxupdates;
1376 		pfsyncr.pfsyncr_defer = sc->sc_flags;
1377 		PFSYNC_UNLOCK(sc);
1378 		return (copyout(&pfsyncr, ifr_data_get_ptr(ifr),
1379 		    sizeof(pfsyncr)));
1380 
1381 	case SIOCSETPFSYNC:
1382 	    {
1383 		struct in_mfilter *imf = NULL;
1384 		struct ifnet *sifp;
1385 		struct ip *ip;
1386 
1387 		if ((error = priv_check(curthread, PRIV_NETINET_PF)) != 0)
1388 			return (error);
1389 		if ((error = copyin(ifr_data_get_ptr(ifr), &pfsyncr,
1390 		    sizeof(pfsyncr))))
1391 			return (error);
1392 
1393 		if (pfsyncr.pfsyncr_maxupdates > 255)
1394 			return (EINVAL);
1395 
1396 		if (pfsyncr.pfsyncr_syncdev[0] == 0)
1397 			sifp = NULL;
1398 		else if ((sifp = ifunit_ref(pfsyncr.pfsyncr_syncdev)) == NULL)
1399 			return (EINVAL);
1400 
1401 		if (sifp != NULL && (
1402 		    pfsyncr.pfsyncr_syncpeer.s_addr == 0 ||
1403 		    pfsyncr.pfsyncr_syncpeer.s_addr ==
1404 		    htonl(INADDR_PFSYNC_GROUP)))
1405 			imf = ip_mfilter_alloc(M_WAITOK, 0, 0);
1406 
1407 		PFSYNC_LOCK(sc);
1408 		if (pfsyncr.pfsyncr_syncpeer.s_addr == 0)
1409 			sc->sc_sync_peer.s_addr = htonl(INADDR_PFSYNC_GROUP);
1410 		else
1411 			sc->sc_sync_peer.s_addr =
1412 			    pfsyncr.pfsyncr_syncpeer.s_addr;
1413 
1414 		sc->sc_maxupdates = pfsyncr.pfsyncr_maxupdates;
1415 		if (pfsyncr.pfsyncr_defer) {
1416 			sc->sc_flags |= PFSYNCF_DEFER;
1417 			V_pfsync_defer_ptr = pfsync_defer;
1418 		} else {
1419 			sc->sc_flags &= ~PFSYNCF_DEFER;
1420 			V_pfsync_defer_ptr = NULL;
1421 		}
1422 
1423 		if (sifp == NULL) {
1424 			if (sc->sc_sync_if)
1425 				if_rele(sc->sc_sync_if);
1426 			sc->sc_sync_if = NULL;
1427 			pfsync_multicast_cleanup(sc);
1428 			PFSYNC_UNLOCK(sc);
1429 			break;
1430 		}
1431 
1432 		for (c = 0; c < pfsync_buckets; c++) {
1433 			PFSYNC_BUCKET_LOCK(&sc->sc_buckets[c]);
1434 			if (sc->sc_buckets[c].b_len > PFSYNC_MINPKT &&
1435 			    (sifp->if_mtu < sc->sc_ifp->if_mtu ||
1436 			    (sc->sc_sync_if != NULL &&
1437 			    sifp->if_mtu < sc->sc_sync_if->if_mtu) ||
1438 			    sifp->if_mtu < MCLBYTES - sizeof(struct ip)))
1439 				pfsync_sendout(1, c);
1440 			PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[c]);
1441 		}
1442 
1443 		pfsync_multicast_cleanup(sc);
1444 
1445 		if (sc->sc_sync_peer.s_addr == htonl(INADDR_PFSYNC_GROUP)) {
1446 			error = pfsync_multicast_setup(sc, sifp, imf);
1447 			if (error) {
1448 				if_rele(sifp);
1449 				ip_mfilter_free(imf);
1450 				PFSYNC_UNLOCK(sc);
1451 				return (error);
1452 			}
1453 		}
1454 		if (sc->sc_sync_if)
1455 			if_rele(sc->sc_sync_if);
1456 		sc->sc_sync_if = sifp;
1457 
1458 		ip = &sc->sc_template;
1459 		bzero(ip, sizeof(*ip));
1460 		ip->ip_v = IPVERSION;
1461 		ip->ip_hl = sizeof(sc->sc_template) >> 2;
1462 		ip->ip_tos = IPTOS_LOWDELAY;
1463 		/* len and id are set later. */
1464 		ip->ip_off = htons(IP_DF);
1465 		ip->ip_ttl = PFSYNC_DFLTTL;
1466 		ip->ip_p = IPPROTO_PFSYNC;
1467 		ip->ip_src.s_addr = INADDR_ANY;
1468 		ip->ip_dst.s_addr = sc->sc_sync_peer.s_addr;
1469 
1470 		/* Request a full state table update. */
1471 		if ((sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
1472 			(*carp_demote_adj_p)(V_pfsync_carp_adj,
1473 			    "pfsync bulk start");
1474 		sc->sc_flags &= ~PFSYNCF_OK;
1475 		if (V_pf_status.debug >= PF_DEBUG_MISC)
1476 			printf("pfsync: requesting bulk update\n");
1477 		PFSYNC_UNLOCK(sc);
1478 		PFSYNC_BUCKET_LOCK(&sc->sc_buckets[0]);
1479 		pfsync_request_update(0, 0);
1480 		PFSYNC_BUCKET_UNLOCK(&sc->sc_buckets[0]);
1481 		PFSYNC_BLOCK(sc);
1482 		sc->sc_ureq_sent = time_uptime;
1483 		callout_reset(&sc->sc_bulkfail_tmo, 5 * hz, pfsync_bulk_fail,
1484 		    sc);
1485 		PFSYNC_BUNLOCK(sc);
1486 
1487 		break;
1488 	    }
1489 	default:
1490 		return (ENOTTY);
1491 	}
1492 
1493 	return (0);
1494 }
1495 
1496 static void
1497 pfsync_out_state(struct pf_state *st, void *buf)
1498 {
1499 	struct pfsync_state *sp = buf;
1500 
1501 	pfsync_state_export(sp, st);
1502 }
1503 
1504 static void
1505 pfsync_out_iack(struct pf_state *st, void *buf)
1506 {
1507 	struct pfsync_ins_ack *iack = buf;
1508 
1509 	iack->id = st->id;
1510 	iack->creatorid = st->creatorid;
1511 }
1512 
1513 static void
1514 pfsync_out_upd_c(struct pf_state *st, void *buf)
1515 {
1516 	struct pfsync_upd_c *up = buf;
1517 
1518 	bzero(up, sizeof(*up));
1519 	up->id = st->id;
1520 	pf_state_peer_hton(&st->src, &up->src);
1521 	pf_state_peer_hton(&st->dst, &up->dst);
1522 	up->creatorid = st->creatorid;
1523 	up->timeout = st->timeout;
1524 }
1525 
1526 static void
1527 pfsync_out_del(struct pf_state *st, void *buf)
1528 {
1529 	struct pfsync_del_c *dp = buf;
1530 
1531 	dp->id = st->id;
1532 	dp->creatorid = st->creatorid;
1533 	st->state_flags |= PFSTATE_NOSYNC;
1534 }
1535 
1536 static void
1537 pfsync_drop(struct pfsync_softc *sc)
1538 {
1539 	struct pf_state *st, *next;
1540 	struct pfsync_upd_req_item *ur;
1541 	struct pfsync_bucket *b;
1542 	int c, q;
1543 
1544 	for (c = 0; c < pfsync_buckets; c++) {
1545 		b = &sc->sc_buckets[c];
1546 		for (q = 0; q < PFSYNC_S_COUNT; q++) {
1547 			if (TAILQ_EMPTY(&b->b_qs[q]))
1548 				continue;
1549 
1550 			TAILQ_FOREACH_SAFE(st, &b->b_qs[q], sync_list, next) {
1551 				KASSERT(st->sync_state == q,
1552 					("%s: st->sync_state == q",
1553 						__func__));
1554 				st->sync_state = PFSYNC_S_NONE;
1555 				pf_release_state(st);
1556 			}
1557 			TAILQ_INIT(&b->b_qs[q]);
1558 		}
1559 
1560 		while ((ur = TAILQ_FIRST(&b->b_upd_req_list)) != NULL) {
1561 			TAILQ_REMOVE(&b->b_upd_req_list, ur, ur_entry);
1562 			free(ur, M_PFSYNC);
1563 		}
1564 
1565 		b->b_len = PFSYNC_MINPKT;
1566 		b->b_plus = NULL;
1567 	}
1568 }
1569 
1570 static void
1571 pfsync_sendout(int schedswi, int c)
1572 {
1573 	struct pfsync_softc *sc = V_pfsyncif;
1574 	struct ifnet *ifp = sc->sc_ifp;
1575 	struct mbuf *m;
1576 	struct ip *ip;
1577 	struct pfsync_header *ph;
1578 	struct pfsync_subheader *subh;
1579 	struct pf_state *st, *st_next;
1580 	struct pfsync_upd_req_item *ur;
1581 	struct pfsync_bucket *b = &sc->sc_buckets[c];
1582 	int offset;
1583 	int q, count = 0;
1584 
1585 	KASSERT(sc != NULL, ("%s: null sc", __func__));
1586 	KASSERT(b->b_len > PFSYNC_MINPKT,
1587 	    ("%s: sc_len %zu", __func__, b->b_len));
1588 	PFSYNC_BUCKET_LOCK_ASSERT(b);
1589 
1590 	if (ifp->if_bpf == NULL && sc->sc_sync_if == NULL) {
1591 		pfsync_drop(sc);
1592 		return;
1593 	}
1594 
1595 	m = m_get2(max_linkhdr + b->b_len, M_NOWAIT, MT_DATA, M_PKTHDR);
1596 	if (m == NULL) {
1597 		if_inc_counter(sc->sc_ifp, IFCOUNTER_OERRORS, 1);
1598 		V_pfsyncstats.pfsyncs_onomem++;
1599 		return;
1600 	}
1601 	m->m_data += max_linkhdr;
1602 	m->m_len = m->m_pkthdr.len = b->b_len;
1603 
1604 	/* build the ip header */
1605 	ip = (struct ip *)m->m_data;
1606 	bcopy(&sc->sc_template, ip, sizeof(*ip));
1607 	offset = sizeof(*ip);
1608 
1609 	ip->ip_len = htons(m->m_pkthdr.len);
1610 	ip_fillid(ip);
1611 
1612 	/* build the pfsync header */
1613 	ph = (struct pfsync_header *)(m->m_data + offset);
1614 	bzero(ph, sizeof(*ph));
1615 	offset += sizeof(*ph);
1616 
1617 	ph->version = PFSYNC_VERSION;
1618 	ph->len = htons(b->b_len - sizeof(*ip));
1619 	bcopy(V_pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
1620 
1621 	/* walk the queues */
1622 	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1623 		if (TAILQ_EMPTY(&b->b_qs[q]))
1624 			continue;
1625 
1626 		subh = (struct pfsync_subheader *)(m->m_data + offset);
1627 		offset += sizeof(*subh);
1628 
1629 		count = 0;
1630 		TAILQ_FOREACH_SAFE(st, &b->b_qs[q], sync_list, st_next) {
1631 			KASSERT(st->sync_state == q,
1632 				("%s: st->sync_state == q",
1633 					__func__));
1634 			/*
1635 			 * XXXGL: some of write methods do unlocked reads
1636 			 * of state data :(
1637 			 */
1638 			pfsync_qs[q].write(st, m->m_data + offset);
1639 			offset += pfsync_qs[q].len;
1640 			st->sync_state = PFSYNC_S_NONE;
1641 			pf_release_state(st);
1642 			count++;
1643 		}
1644 		TAILQ_INIT(&b->b_qs[q]);
1645 
1646 		bzero(subh, sizeof(*subh));
1647 		subh->action = pfsync_qs[q].action;
1648 		subh->count = htons(count);
1649 		V_pfsyncstats.pfsyncs_oacts[pfsync_qs[q].action] += count;
1650 	}
1651 
1652 	if (!TAILQ_EMPTY(&b->b_upd_req_list)) {
1653 		subh = (struct pfsync_subheader *)(m->m_data + offset);
1654 		offset += sizeof(*subh);
1655 
1656 		count = 0;
1657 		while ((ur = TAILQ_FIRST(&b->b_upd_req_list)) != NULL) {
1658 			TAILQ_REMOVE(&b->b_upd_req_list, ur, ur_entry);
1659 
1660 			bcopy(&ur->ur_msg, m->m_data + offset,
1661 			    sizeof(ur->ur_msg));
1662 			offset += sizeof(ur->ur_msg);
1663 			free(ur, M_PFSYNC);
1664 			count++;
1665 		}
1666 
1667 		bzero(subh, sizeof(*subh));
1668 		subh->action = PFSYNC_ACT_UPD_REQ;
1669 		subh->count = htons(count);
1670 		V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_UPD_REQ] += count;
1671 	}
1672 
1673 	/* has someone built a custom region for us to add? */
1674 	if (b->b_plus != NULL) {
1675 		bcopy(b->b_plus, m->m_data + offset, b->b_pluslen);
1676 		offset += b->b_pluslen;
1677 
1678 		b->b_plus = NULL;
1679 	}
1680 
1681 	subh = (struct pfsync_subheader *)(m->m_data + offset);
1682 	offset += sizeof(*subh);
1683 
1684 	bzero(subh, sizeof(*subh));
1685 	subh->action = PFSYNC_ACT_EOF;
1686 	subh->count = htons(1);
1687 	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_EOF]++;
1688 
1689 	/* we're done, let's put it on the wire */
1690 	if (ifp->if_bpf) {
1691 		m->m_data += sizeof(*ip);
1692 		m->m_len = m->m_pkthdr.len = b->b_len - sizeof(*ip);
1693 		BPF_MTAP(ifp, m);
1694 		m->m_data -= sizeof(*ip);
1695 		m->m_len = m->m_pkthdr.len = b->b_len;
1696 	}
1697 
1698 	if (sc->sc_sync_if == NULL) {
1699 		b->b_len = PFSYNC_MINPKT;
1700 		m_freem(m);
1701 		return;
1702 	}
1703 
1704 	if_inc_counter(sc->sc_ifp, IFCOUNTER_OPACKETS, 1);
1705 	if_inc_counter(sc->sc_ifp, IFCOUNTER_OBYTES, m->m_pkthdr.len);
1706 	b->b_len = PFSYNC_MINPKT;
1707 
1708 	if (!_IF_QFULL(&b->b_snd))
1709 		_IF_ENQUEUE(&b->b_snd, m);
1710 	else {
1711 		m_freem(m);
1712 		if_inc_counter(sc->sc_ifp, IFCOUNTER_OQDROPS, 1);
1713 	}
1714 	if (schedswi)
1715 		swi_sched(V_pfsync_swi_cookie, 0);
1716 }
1717 
1718 static void
1719 pfsync_insert_state(struct pf_state *st)
1720 {
1721 	struct pfsync_softc *sc = V_pfsyncif;
1722 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
1723 
1724 	if (st->state_flags & PFSTATE_NOSYNC)
1725 		return;
1726 
1727 	if ((st->rule.ptr->rule_flag & PFRULE_NOSYNC) ||
1728 	    st->key[PF_SK_WIRE]->proto == IPPROTO_PFSYNC) {
1729 		st->state_flags |= PFSTATE_NOSYNC;
1730 		return;
1731 	}
1732 
1733 	KASSERT(st->sync_state == PFSYNC_S_NONE,
1734 		("%s: st->sync_state %u", __func__, st->sync_state));
1735 
1736 	PFSYNC_BUCKET_LOCK(b);
1737 	if (b->b_len == PFSYNC_MINPKT)
1738 		callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
1739 
1740 	pfsync_q_ins(st, PFSYNC_S_INS, true);
1741 	PFSYNC_BUCKET_UNLOCK(b);
1742 
1743 	st->sync_updates = 0;
1744 }
1745 
1746 static int
1747 pfsync_defer(struct pf_state *st, struct mbuf *m)
1748 {
1749 	struct pfsync_softc *sc = V_pfsyncif;
1750 	struct pfsync_deferral *pd;
1751 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
1752 
1753 	if (m->m_flags & (M_BCAST|M_MCAST))
1754 		return (0);
1755 
1756 	PFSYNC_LOCK(sc);
1757 
1758 	if (sc == NULL || !(sc->sc_ifp->if_flags & IFF_DRV_RUNNING) ||
1759 	    !(sc->sc_flags & PFSYNCF_DEFER)) {
1760 		PFSYNC_UNLOCK(sc);
1761 		return (0);
1762 	}
1763 
1764 	if (b->b_deferred >= 128)
1765 		pfsync_undefer(TAILQ_FIRST(&b->b_deferrals), 0);
1766 
1767 	pd = malloc(sizeof(*pd), M_PFSYNC, M_NOWAIT);
1768 	if (pd == NULL)
1769 		return (0);
1770 	b->b_deferred++;
1771 
1772 	m->m_flags |= M_SKIP_FIREWALL;
1773 	st->state_flags |= PFSTATE_ACK;
1774 
1775 	pd->pd_sc = sc;
1776 	pd->pd_refs = 0;
1777 	pd->pd_st = st;
1778 	pf_ref_state(st);
1779 	pd->pd_m = m;
1780 
1781 	TAILQ_INSERT_TAIL(&b->b_deferrals, pd, pd_entry);
1782 	callout_init_mtx(&pd->pd_tmo, &b->b_mtx, CALLOUT_RETURNUNLOCKED);
1783 	callout_reset(&pd->pd_tmo, 10, pfsync_defer_tmo, pd);
1784 
1785 	pfsync_push(b);
1786 
1787 	return (1);
1788 }
1789 
1790 static void
1791 pfsync_undefer(struct pfsync_deferral *pd, int drop)
1792 {
1793 	struct pfsync_softc *sc = pd->pd_sc;
1794 	struct mbuf *m = pd->pd_m;
1795 	struct pf_state *st = pd->pd_st;
1796 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
1797 
1798 	PFSYNC_BUCKET_LOCK_ASSERT(b);
1799 
1800 	TAILQ_REMOVE(&b->b_deferrals, pd, pd_entry);
1801 	b->b_deferred--;
1802 	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
1803 	free(pd, M_PFSYNC);
1804 	pf_release_state(st);
1805 
1806 	if (drop)
1807 		m_freem(m);
1808 	else {
1809 		_IF_ENQUEUE(&b->b_snd, m);
1810 		pfsync_push(b);
1811 	}
1812 }
1813 
1814 static void
1815 pfsync_defer_tmo(void *arg)
1816 {
1817 	struct epoch_tracker et;
1818 	struct pfsync_deferral *pd = arg;
1819 	struct pfsync_softc *sc = pd->pd_sc;
1820 	struct mbuf *m = pd->pd_m;
1821 	struct pf_state *st = pd->pd_st;
1822 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
1823 
1824 	PFSYNC_BUCKET_LOCK_ASSERT(b);
1825 
1826 	NET_EPOCH_ENTER(et);
1827 	CURVNET_SET(m->m_pkthdr.rcvif->if_vnet);
1828 
1829 	TAILQ_REMOVE(&b->b_deferrals, pd, pd_entry);
1830 	b->b_deferred--;
1831 	pd->pd_st->state_flags &= ~PFSTATE_ACK;	/* XXX: locking! */
1832 	if (pd->pd_refs == 0)
1833 		free(pd, M_PFSYNC);
1834 	PFSYNC_UNLOCK(sc);
1835 
1836 	ip_output(m, NULL, NULL, 0, NULL, NULL);
1837 
1838 	pf_release_state(st);
1839 
1840 	CURVNET_RESTORE();
1841 	NET_EPOCH_EXIT(et);
1842 }
1843 
1844 static void
1845 pfsync_undefer_state(struct pf_state *st, int drop)
1846 {
1847 	struct pfsync_softc *sc = V_pfsyncif;
1848 	struct pfsync_deferral *pd;
1849 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
1850 
1851 	PFSYNC_BUCKET_LOCK(b);
1852 
1853 	TAILQ_FOREACH(pd, &b->b_deferrals, pd_entry) {
1854 		 if (pd->pd_st == st) {
1855 			if (callout_stop(&pd->pd_tmo) > 0)
1856 				pfsync_undefer(pd, drop);
1857 
1858 			PFSYNC_BUCKET_UNLOCK(b);
1859 			return;
1860 		}
1861 	}
1862 	PFSYNC_BUCKET_UNLOCK(b);
1863 
1864 	panic("%s: unable to find deferred state", __func__);
1865 }
1866 
1867 static struct pfsync_bucket*
1868 pfsync_get_bucket(struct pfsync_softc *sc, struct pf_state *st)
1869 {
1870 	int c = PF_IDHASH(st) % pfsync_buckets;
1871 	return &sc->sc_buckets[c];
1872 }
1873 
1874 static void
1875 pfsync_update_state(struct pf_state *st)
1876 {
1877 	struct pfsync_softc *sc = V_pfsyncif;
1878 	bool sync = false, ref = true;
1879 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
1880 
1881 	PF_STATE_LOCK_ASSERT(st);
1882 	PFSYNC_BUCKET_LOCK(b);
1883 
1884 	if (st->state_flags & PFSTATE_ACK)
1885 		pfsync_undefer_state(st, 0);
1886 	if (st->state_flags & PFSTATE_NOSYNC) {
1887 		if (st->sync_state != PFSYNC_S_NONE)
1888 			pfsync_q_del(st, true, b);
1889 		PFSYNC_BUCKET_UNLOCK(b);
1890 		return;
1891 	}
1892 
1893 	if (b->b_len == PFSYNC_MINPKT)
1894 		callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
1895 
1896 	switch (st->sync_state) {
1897 	case PFSYNC_S_UPD_C:
1898 	case PFSYNC_S_UPD:
1899 	case PFSYNC_S_INS:
1900 		/* we're already handling it */
1901 
1902 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP) {
1903 			st->sync_updates++;
1904 			if (st->sync_updates >= sc->sc_maxupdates)
1905 				sync = true;
1906 		}
1907 		break;
1908 
1909 	case PFSYNC_S_IACK:
1910 		pfsync_q_del(st, false, b);
1911 		ref = false;
1912 		/* FALLTHROUGH */
1913 
1914 	case PFSYNC_S_NONE:
1915 		pfsync_q_ins(st, PFSYNC_S_UPD_C, ref);
1916 		st->sync_updates = 0;
1917 		break;
1918 
1919 	default:
1920 		panic("%s: unexpected sync state %d", __func__, st->sync_state);
1921 	}
1922 
1923 	if (sync || (time_uptime - st->pfsync_time) < 2)
1924 		pfsync_push(b);
1925 
1926 	PFSYNC_BUCKET_UNLOCK(b);
1927 }
1928 
1929 static void
1930 pfsync_request_update(u_int32_t creatorid, u_int64_t id)
1931 {
1932 	struct pfsync_softc *sc = V_pfsyncif;
1933 	struct pfsync_bucket *b = &sc->sc_buckets[0];
1934 	struct pfsync_upd_req_item *item;
1935 	size_t nlen = sizeof(struct pfsync_upd_req);
1936 
1937 	PFSYNC_BUCKET_LOCK_ASSERT(b);
1938 
1939 	/*
1940 	 * This code does a bit to prevent multiple update requests for the
1941 	 * same state being generated. It searches current subheader queue,
1942 	 * but it doesn't lookup into queue of already packed datagrams.
1943 	 */
1944 	TAILQ_FOREACH(item, &b->b_upd_req_list, ur_entry)
1945 		if (item->ur_msg.id == id &&
1946 		    item->ur_msg.creatorid == creatorid)
1947 			return;
1948 
1949 	item = malloc(sizeof(*item), M_PFSYNC, M_NOWAIT);
1950 	if (item == NULL)
1951 		return; /* XXX stats */
1952 
1953 	item->ur_msg.id = id;
1954 	item->ur_msg.creatorid = creatorid;
1955 
1956 	if (TAILQ_EMPTY(&b->b_upd_req_list))
1957 		nlen += sizeof(struct pfsync_subheader);
1958 
1959 	if (b->b_len + nlen > sc->sc_ifp->if_mtu) {
1960 		pfsync_sendout(0, 0);
1961 
1962 		nlen = sizeof(struct pfsync_subheader) +
1963 		    sizeof(struct pfsync_upd_req);
1964 	}
1965 
1966 	TAILQ_INSERT_TAIL(&b->b_upd_req_list, item, ur_entry);
1967 	b->b_len += nlen;
1968 
1969 	pfsync_push(b);
1970 }
1971 
1972 static bool
1973 pfsync_update_state_req(struct pf_state *st)
1974 {
1975 	struct pfsync_softc *sc = V_pfsyncif;
1976 	bool ref = true, full = false;
1977 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
1978 
1979 	PF_STATE_LOCK_ASSERT(st);
1980 	PFSYNC_BUCKET_LOCK(b);
1981 
1982 	if (st->state_flags & PFSTATE_NOSYNC) {
1983 		if (st->sync_state != PFSYNC_S_NONE)
1984 			pfsync_q_del(st, true, b);
1985 		PFSYNC_BUCKET_UNLOCK(b);
1986 		return (full);
1987 	}
1988 
1989 	switch (st->sync_state) {
1990 	case PFSYNC_S_UPD_C:
1991 	case PFSYNC_S_IACK:
1992 		pfsync_q_del(st, false, b);
1993 		ref = false;
1994 		/* FALLTHROUGH */
1995 
1996 	case PFSYNC_S_NONE:
1997 		pfsync_q_ins(st, PFSYNC_S_UPD, ref);
1998 		pfsync_push(b);
1999 		break;
2000 
2001 	case PFSYNC_S_INS:
2002 	case PFSYNC_S_UPD:
2003 	case PFSYNC_S_DEL:
2004 		/* we're already handling it */
2005 		break;
2006 
2007 	default:
2008 		panic("%s: unexpected sync state %d", __func__, st->sync_state);
2009 	}
2010 
2011 	if ((sc->sc_ifp->if_mtu - b->b_len) < sizeof(struct pfsync_state))
2012 		full = true;
2013 
2014 	PFSYNC_BUCKET_UNLOCK(b);
2015 
2016 	return (full);
2017 }
2018 
2019 static void
2020 pfsync_delete_state(struct pf_state *st)
2021 {
2022 	struct pfsync_softc *sc = V_pfsyncif;
2023 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2024 	bool ref = true;
2025 
2026 	PFSYNC_BUCKET_LOCK(b);
2027 	if (st->state_flags & PFSTATE_ACK)
2028 		pfsync_undefer_state(st, 1);
2029 	if (st->state_flags & PFSTATE_NOSYNC) {
2030 		if (st->sync_state != PFSYNC_S_NONE)
2031 			pfsync_q_del(st, true, b);
2032 		PFSYNC_BUCKET_UNLOCK(b);
2033 		return;
2034 	}
2035 
2036 	if (b->b_len == PFSYNC_MINPKT)
2037 		callout_reset(&b->b_tmo, 1 * hz, pfsync_timeout, b);
2038 
2039 	switch (st->sync_state) {
2040 	case PFSYNC_S_INS:
2041 		/* We never got to tell the world so just forget about it. */
2042 		pfsync_q_del(st, true, b);
2043 		break;
2044 
2045 	case PFSYNC_S_UPD_C:
2046 	case PFSYNC_S_UPD:
2047 	case PFSYNC_S_IACK:
2048 		pfsync_q_del(st, false, b);
2049 		ref = false;
2050 		/* FALLTHROUGH */
2051 
2052 	case PFSYNC_S_NONE:
2053 		pfsync_q_ins(st, PFSYNC_S_DEL, ref);
2054 		break;
2055 
2056 	default:
2057 		panic("%s: unexpected sync state %d", __func__, st->sync_state);
2058 	}
2059 
2060 	PFSYNC_BUCKET_UNLOCK(b);
2061 }
2062 
2063 static void
2064 pfsync_clear_states(u_int32_t creatorid, const char *ifname)
2065 {
2066 	struct {
2067 		struct pfsync_subheader subh;
2068 		struct pfsync_clr clr;
2069 	} __packed r;
2070 
2071 	bzero(&r, sizeof(r));
2072 
2073 	r.subh.action = PFSYNC_ACT_CLR;
2074 	r.subh.count = htons(1);
2075 	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_CLR]++;
2076 
2077 	strlcpy(r.clr.ifname, ifname, sizeof(r.clr.ifname));
2078 	r.clr.creatorid = creatorid;
2079 
2080 	pfsync_send_plus(&r, sizeof(r));
2081 }
2082 
2083 static void
2084 pfsync_q_ins(struct pf_state *st, int q, bool ref)
2085 {
2086 	struct pfsync_softc *sc = V_pfsyncif;
2087 	size_t nlen = pfsync_qs[q].len;
2088 	struct pfsync_bucket *b = pfsync_get_bucket(sc, st);
2089 
2090 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2091 
2092 	KASSERT(st->sync_state == PFSYNC_S_NONE,
2093 		("%s: st->sync_state %u", __func__, st->sync_state));
2094 	KASSERT(b->b_len >= PFSYNC_MINPKT, ("pfsync pkt len is too low %zu",
2095 	    b->b_len));
2096 
2097 	if (TAILQ_EMPTY(&b->b_qs[q]))
2098 		nlen += sizeof(struct pfsync_subheader);
2099 
2100 	if (b->b_len + nlen > sc->sc_ifp->if_mtu) {
2101 		pfsync_sendout(1, b->b_id);
2102 
2103 		nlen = sizeof(struct pfsync_subheader) + pfsync_qs[q].len;
2104 	}
2105 
2106 	b->b_len += nlen;
2107 	TAILQ_INSERT_TAIL(&b->b_qs[q], st, sync_list);
2108 	st->sync_state = q;
2109 	if (ref)
2110 		pf_ref_state(st);
2111 }
2112 
2113 static void
2114 pfsync_q_del(struct pf_state *st, bool unref, struct pfsync_bucket *b)
2115 {
2116 	int q = st->sync_state;
2117 
2118 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2119 	KASSERT(st->sync_state != PFSYNC_S_NONE,
2120 		("%s: st->sync_state != PFSYNC_S_NONE", __func__));
2121 
2122 	b->b_len -= pfsync_qs[q].len;
2123 	TAILQ_REMOVE(&b->b_qs[q], st, sync_list);
2124 	st->sync_state = PFSYNC_S_NONE;
2125 	if (unref)
2126 		pf_release_state(st);
2127 
2128 	if (TAILQ_EMPTY(&b->b_qs[q]))
2129 		b->b_len -= sizeof(struct pfsync_subheader);
2130 }
2131 
2132 static void
2133 pfsync_bulk_start(void)
2134 {
2135 	struct pfsync_softc *sc = V_pfsyncif;
2136 
2137 	if (V_pf_status.debug >= PF_DEBUG_MISC)
2138 		printf("pfsync: received bulk update request\n");
2139 
2140 	PFSYNC_BLOCK(sc);
2141 
2142 	sc->sc_ureq_received = time_uptime;
2143 	sc->sc_bulk_hashid = 0;
2144 	sc->sc_bulk_stateid = 0;
2145 	pfsync_bulk_status(PFSYNC_BUS_START);
2146 	callout_reset(&sc->sc_bulk_tmo, 1, pfsync_bulk_update, sc);
2147 	PFSYNC_BUNLOCK(sc);
2148 }
2149 
2150 static void
2151 pfsync_bulk_update(void *arg)
2152 {
2153 	struct pfsync_softc *sc = arg;
2154 	struct pf_state *s;
2155 	int i, sent = 0;
2156 
2157 	PFSYNC_BLOCK_ASSERT(sc);
2158 	CURVNET_SET(sc->sc_ifp->if_vnet);
2159 
2160 	/*
2161 	 * Start with last state from previous invocation.
2162 	 * It may had gone, in this case start from the
2163 	 * hash slot.
2164 	 */
2165 	s = pf_find_state_byid(sc->sc_bulk_stateid, sc->sc_bulk_creatorid);
2166 
2167 	if (s != NULL)
2168 		i = PF_IDHASH(s);
2169 	else
2170 		i = sc->sc_bulk_hashid;
2171 
2172 	for (; i <= pf_hashmask; i++) {
2173 		struct pf_idhash *ih = &V_pf_idhash[i];
2174 
2175 		if (s != NULL)
2176 			PF_HASHROW_ASSERT(ih);
2177 		else {
2178 			PF_HASHROW_LOCK(ih);
2179 			s = LIST_FIRST(&ih->states);
2180 		}
2181 
2182 		for (; s; s = LIST_NEXT(s, entry)) {
2183 			if (s->sync_state == PFSYNC_S_NONE &&
2184 			    s->timeout < PFTM_MAX &&
2185 			    s->pfsync_time <= sc->sc_ureq_received) {
2186 				if (pfsync_update_state_req(s)) {
2187 					/* We've filled a packet. */
2188 					sc->sc_bulk_hashid = i;
2189 					sc->sc_bulk_stateid = s->id;
2190 					sc->sc_bulk_creatorid = s->creatorid;
2191 					PF_HASHROW_UNLOCK(ih);
2192 					callout_reset(&sc->sc_bulk_tmo, 1,
2193 					    pfsync_bulk_update, sc);
2194 					goto full;
2195 				}
2196 				sent++;
2197 			}
2198 		}
2199 		PF_HASHROW_UNLOCK(ih);
2200 	}
2201 
2202 	/* We're done. */
2203 	pfsync_bulk_status(PFSYNC_BUS_END);
2204 full:
2205 	CURVNET_RESTORE();
2206 }
2207 
2208 static void
2209 pfsync_bulk_status(u_int8_t status)
2210 {
2211 	struct {
2212 		struct pfsync_subheader subh;
2213 		struct pfsync_bus bus;
2214 	} __packed r;
2215 
2216 	struct pfsync_softc *sc = V_pfsyncif;
2217 
2218 	bzero(&r, sizeof(r));
2219 
2220 	r.subh.action = PFSYNC_ACT_BUS;
2221 	r.subh.count = htons(1);
2222 	V_pfsyncstats.pfsyncs_oacts[PFSYNC_ACT_BUS]++;
2223 
2224 	r.bus.creatorid = V_pf_status.hostid;
2225 	r.bus.endtime = htonl(time_uptime - sc->sc_ureq_received);
2226 	r.bus.status = status;
2227 
2228 	pfsync_send_plus(&r, sizeof(r));
2229 }
2230 
2231 static void
2232 pfsync_bulk_fail(void *arg)
2233 {
2234 	struct pfsync_softc *sc = arg;
2235 	struct pfsync_bucket *b = &sc->sc_buckets[0];
2236 
2237 	CURVNET_SET(sc->sc_ifp->if_vnet);
2238 
2239 	PFSYNC_BLOCK_ASSERT(sc);
2240 
2241 	if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
2242 		/* Try again */
2243 		callout_reset(&sc->sc_bulkfail_tmo, 5 * hz,
2244 		    pfsync_bulk_fail, V_pfsyncif);
2245 		PFSYNC_BUCKET_LOCK(b);
2246 		pfsync_request_update(0, 0);
2247 		PFSYNC_BUCKET_UNLOCK(b);
2248 	} else {
2249 		/* Pretend like the transfer was ok. */
2250 		sc->sc_ureq_sent = 0;
2251 		sc->sc_bulk_tries = 0;
2252 		PFSYNC_LOCK(sc);
2253 		if (!(sc->sc_flags & PFSYNCF_OK) && carp_demote_adj_p)
2254 			(*carp_demote_adj_p)(-V_pfsync_carp_adj,
2255 			    "pfsync bulk fail");
2256 		sc->sc_flags |= PFSYNCF_OK;
2257 		PFSYNC_UNLOCK(sc);
2258 		if (V_pf_status.debug >= PF_DEBUG_MISC)
2259 			printf("pfsync: failed to receive bulk update\n");
2260 	}
2261 
2262 	CURVNET_RESTORE();
2263 }
2264 
2265 static void
2266 pfsync_send_plus(void *plus, size_t pluslen)
2267 {
2268 	struct pfsync_softc *sc = V_pfsyncif;
2269 	struct pfsync_bucket *b = &sc->sc_buckets[0];
2270 
2271 	PFSYNC_BUCKET_LOCK(b);
2272 
2273 	if (b->b_len + pluslen > sc->sc_ifp->if_mtu)
2274 		pfsync_sendout(1, b->b_id);
2275 
2276 	b->b_plus = plus;
2277 	b->b_len += (b->b_pluslen = pluslen);
2278 
2279 	pfsync_sendout(1, b->b_id);
2280 	PFSYNC_BUCKET_UNLOCK(b);
2281 }
2282 
2283 static void
2284 pfsync_timeout(void *arg)
2285 {
2286 	struct pfsync_bucket *b = arg;
2287 
2288 	CURVNET_SET(b->b_sc->sc_ifp->if_vnet);
2289 	PFSYNC_BUCKET_LOCK(b);
2290 	pfsync_push(b);
2291 	PFSYNC_BUCKET_UNLOCK(b);
2292 	CURVNET_RESTORE();
2293 }
2294 
2295 static void
2296 pfsync_push(struct pfsync_bucket *b)
2297 {
2298 
2299 	PFSYNC_BUCKET_LOCK_ASSERT(b);
2300 
2301 	b->b_flags |= PFSYNCF_BUCKET_PUSH;
2302 	swi_sched(V_pfsync_swi_cookie, 0);
2303 }
2304 
2305 static void
2306 pfsync_push_all(struct pfsync_softc *sc)
2307 {
2308 	int c;
2309 	struct pfsync_bucket *b;
2310 
2311 	for (c = 0; c < pfsync_buckets; c++) {
2312 		b = &sc->sc_buckets[c];
2313 
2314 		PFSYNC_BUCKET_LOCK(b);
2315 		pfsync_push(b);
2316 		PFSYNC_BUCKET_UNLOCK(b);
2317 	}
2318 }
2319 
2320 static void
2321 pfsyncintr(void *arg)
2322 {
2323 	struct epoch_tracker et;
2324 	struct pfsync_softc *sc = arg;
2325 	struct pfsync_bucket *b;
2326 	struct mbuf *m, *n;
2327 	int c;
2328 
2329 	NET_EPOCH_ENTER(et);
2330 	CURVNET_SET(sc->sc_ifp->if_vnet);
2331 
2332 	for (c = 0; c < pfsync_buckets; c++) {
2333 		b = &sc->sc_buckets[c];
2334 
2335 		PFSYNC_BUCKET_LOCK(b);
2336 		if ((b->b_flags & PFSYNCF_BUCKET_PUSH) && b->b_len > PFSYNC_MINPKT) {
2337 			pfsync_sendout(0, b->b_id);
2338 			b->b_flags &= ~PFSYNCF_BUCKET_PUSH;
2339 		}
2340 		_IF_DEQUEUE_ALL(&b->b_snd, m);
2341 		PFSYNC_BUCKET_UNLOCK(b);
2342 
2343 		for (; m != NULL; m = n) {
2344 			n = m->m_nextpkt;
2345 			m->m_nextpkt = NULL;
2346 
2347 			/*
2348 			 * We distinguish between a deferral packet and our
2349 			 * own pfsync packet based on M_SKIP_FIREWALL
2350 			 * flag. This is XXX.
2351 			 */
2352 			if (m->m_flags & M_SKIP_FIREWALL)
2353 				ip_output(m, NULL, NULL, 0, NULL, NULL);
2354 			else if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo,
2355 			    NULL) == 0)
2356 				V_pfsyncstats.pfsyncs_opackets++;
2357 			else
2358 				V_pfsyncstats.pfsyncs_oerrors++;
2359 		}
2360 	}
2361 	CURVNET_RESTORE();
2362 	NET_EPOCH_EXIT(et);
2363 }
2364 
2365 static int
2366 pfsync_multicast_setup(struct pfsync_softc *sc, struct ifnet *ifp,
2367     struct in_mfilter *imf)
2368 {
2369 	struct ip_moptions *imo = &sc->sc_imo;
2370 	int error;
2371 
2372 	if (!(ifp->if_flags & IFF_MULTICAST))
2373 		return (EADDRNOTAVAIL);
2374 
2375 	imo->imo_multicast_vif = -1;
2376 
2377 	if ((error = in_joingroup(ifp, &sc->sc_sync_peer, NULL,
2378 	    &imf->imf_inm)) != 0)
2379 		return (error);
2380 
2381 	ip_mfilter_init(&imo->imo_head);
2382 	ip_mfilter_insert(&imo->imo_head, imf);
2383 	imo->imo_multicast_ifp = ifp;
2384 	imo->imo_multicast_ttl = PFSYNC_DFLTTL;
2385 	imo->imo_multicast_loop = 0;
2386 
2387 	return (0);
2388 }
2389 
2390 static void
2391 pfsync_multicast_cleanup(struct pfsync_softc *sc)
2392 {
2393 	struct ip_moptions *imo = &sc->sc_imo;
2394 	struct in_mfilter *imf;
2395 
2396 	while ((imf = ip_mfilter_first(&imo->imo_head)) != NULL) {
2397 		ip_mfilter_remove(&imo->imo_head, imf);
2398 		in_leavegroup(imf->imf_inm, NULL);
2399 		ip_mfilter_free(imf);
2400 	}
2401 	imo->imo_multicast_ifp = NULL;
2402 }
2403 
2404 void
2405 pfsync_detach_ifnet(struct ifnet *ifp)
2406 {
2407 	struct pfsync_softc *sc = V_pfsyncif;
2408 
2409 	if (sc == NULL)
2410 		return;
2411 
2412 	PFSYNC_LOCK(sc);
2413 
2414 	if (sc->sc_sync_if == ifp) {
2415 		/* We don't need mutlicast cleanup here, because the interface
2416 		 * is going away. We do need to ensure we don't try to do
2417 		 * cleanup later.
2418 		 */
2419 		ip_mfilter_init(&sc->sc_imo.imo_head);
2420 		sc->sc_imo.imo_multicast_ifp = NULL;
2421 		sc->sc_sync_if = NULL;
2422 	}
2423 
2424 	PFSYNC_UNLOCK(sc);
2425 }
2426 
2427 #ifdef INET
2428 extern  struct domain inetdomain;
2429 static struct protosw in_pfsync_protosw = {
2430 	.pr_type =		SOCK_RAW,
2431 	.pr_domain =		&inetdomain,
2432 	.pr_protocol =		IPPROTO_PFSYNC,
2433 	.pr_flags =		PR_ATOMIC|PR_ADDR,
2434 	.pr_input =		pfsync_input,
2435 	.pr_output =		rip_output,
2436 	.pr_ctloutput =		rip_ctloutput,
2437 	.pr_usrreqs =		&rip_usrreqs
2438 };
2439 #endif
2440 
2441 static void
2442 pfsync_pointers_init()
2443 {
2444 
2445 	PF_RULES_WLOCK();
2446 	V_pfsync_state_import_ptr = pfsync_state_import;
2447 	V_pfsync_insert_state_ptr = pfsync_insert_state;
2448 	V_pfsync_update_state_ptr = pfsync_update_state;
2449 	V_pfsync_delete_state_ptr = pfsync_delete_state;
2450 	V_pfsync_clear_states_ptr = pfsync_clear_states;
2451 	V_pfsync_defer_ptr = pfsync_defer;
2452 	PF_RULES_WUNLOCK();
2453 }
2454 
2455 static void
2456 pfsync_pointers_uninit()
2457 {
2458 
2459 	PF_RULES_WLOCK();
2460 	V_pfsync_state_import_ptr = NULL;
2461 	V_pfsync_insert_state_ptr = NULL;
2462 	V_pfsync_update_state_ptr = NULL;
2463 	V_pfsync_delete_state_ptr = NULL;
2464 	V_pfsync_clear_states_ptr = NULL;
2465 	V_pfsync_defer_ptr = NULL;
2466 	PF_RULES_WUNLOCK();
2467 }
2468 
2469 static void
2470 vnet_pfsync_init(const void *unused __unused)
2471 {
2472 	int error;
2473 
2474 	V_pfsync_cloner = if_clone_simple(pfsyncname,
2475 	    pfsync_clone_create, pfsync_clone_destroy, 1);
2476 	error = swi_add(&V_pfsync_swi_ie, pfsyncname, pfsyncintr, V_pfsyncif,
2477 	    SWI_NET, INTR_MPSAFE, &V_pfsync_swi_cookie);
2478 	if (error) {
2479 		if_clone_detach(V_pfsync_cloner);
2480 		log(LOG_INFO, "swi_add() failed in %s\n", __func__);
2481 	}
2482 
2483 	pfsync_pointers_init();
2484 }
2485 VNET_SYSINIT(vnet_pfsync_init, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY,
2486     vnet_pfsync_init, NULL);
2487 
2488 static void
2489 vnet_pfsync_uninit(const void *unused __unused)
2490 {
2491 	int ret;
2492 
2493 	pfsync_pointers_uninit();
2494 
2495 	if_clone_detach(V_pfsync_cloner);
2496 	ret = swi_remove(V_pfsync_swi_cookie);
2497 	MPASS(ret == 0);
2498 	ret = intr_event_destroy(V_pfsync_swi_ie);
2499 	MPASS(ret == 0);
2500 }
2501 
2502 VNET_SYSUNINIT(vnet_pfsync_uninit, SI_SUB_PROTO_FIREWALL, SI_ORDER_FOURTH,
2503     vnet_pfsync_uninit, NULL);
2504 
2505 static int
2506 pfsync_init()
2507 {
2508 #ifdef INET
2509 	int error;
2510 
2511 	pfsync_detach_ifnet_ptr = pfsync_detach_ifnet;
2512 
2513 	error = pf_proto_register(PF_INET, &in_pfsync_protosw);
2514 	if (error)
2515 		return (error);
2516 	error = ipproto_register(IPPROTO_PFSYNC);
2517 	if (error) {
2518 		pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
2519 		return (error);
2520 	}
2521 #endif
2522 
2523 	return (0);
2524 }
2525 
2526 static void
2527 pfsync_uninit()
2528 {
2529 	pfsync_detach_ifnet_ptr = NULL;
2530 
2531 #ifdef INET
2532 	ipproto_unregister(IPPROTO_PFSYNC);
2533 	pf_proto_unregister(PF_INET, IPPROTO_PFSYNC, SOCK_RAW);
2534 #endif
2535 }
2536 
2537 static int
2538 pfsync_modevent(module_t mod, int type, void *data)
2539 {
2540 	int error = 0;
2541 
2542 	switch (type) {
2543 	case MOD_LOAD:
2544 		error = pfsync_init();
2545 		break;
2546 	case MOD_UNLOAD:
2547 		pfsync_uninit();
2548 		break;
2549 	default:
2550 		error = EINVAL;
2551 		break;
2552 	}
2553 
2554 	return (error);
2555 }
2556 
2557 static moduledata_t pfsync_mod = {
2558 	pfsyncname,
2559 	pfsync_modevent,
2560 	0
2561 };
2562 
2563 #define PFSYNC_MODVER 1
2564 
2565 /* Stay on FIREWALL as we depend on pf being initialized and on inetdomain. */
2566 DECLARE_MODULE(pfsync, pfsync_mod, SI_SUB_PROTO_FIREWALL, SI_ORDER_ANY);
2567 MODULE_VERSION(pfsync, PFSYNC_MODVER);
2568 MODULE_DEPEND(pfsync, pf, PF_MODVER, PF_MODVER, PF_MODVER);
2569