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