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