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