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