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