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