xref: /openbsd-src/sys/net/if_pfsync.c (revision fc405d53b73a2d73393cb97f684863d17b583e38)
1 /*	$OpenBSD: if_pfsync.c,v 1.315 2023/05/18 12:10:04 sashan Exp $	*/
2 
3 /*
4  * Copyright (c) 2002 Michael Shalayeff
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
20  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
24  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
25  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26  * THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*
30  * Copyright (c) 2009 David Gwynne <dlg@openbsd.org>
31  *
32  * Permission to use, copy, modify, and distribute this software for any
33  * purpose with or without fee is hereby granted, provided that the above
34  * copyright notice and this permission notice appear in all copies.
35  *
36  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
37  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
38  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
39  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
40  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
41  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
42  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
43  */
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/time.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/socket.h>
51 #include <sys/ioctl.h>
52 #include <sys/timeout.h>
53 #include <sys/kernel.h>
54 #include <sys/sysctl.h>
55 #include <sys/pool.h>
56 #include <sys/syslog.h>
57 
58 #include <net/if.h>
59 #include <net/if_types.h>
60 #include <net/bpf.h>
61 #include <net/netisr.h>
62 
63 #include <netinet/in.h>
64 #include <netinet/if_ether.h>
65 #include <netinet/ip.h>
66 #include <netinet/in_var.h>
67 #include <netinet/ip_var.h>
68 #include <netinet/ip_ipsp.h>
69 #include <netinet/ip_icmp.h>
70 #include <netinet/icmp6.h>
71 #include <netinet/tcp.h>
72 #include <netinet/tcp_seq.h>
73 #include <netinet/tcp_fsm.h>
74 #include <netinet/udp.h>
75 
76 #ifdef INET6
77 #include <netinet6/in6_var.h>
78 #include <netinet/ip6.h>
79 #include <netinet6/ip6_var.h>
80 #include <netinet6/nd6.h>
81 #endif /* INET6 */
82 
83 #include "carp.h"
84 #if NCARP > 0
85 #include <netinet/ip_carp.h>
86 #endif
87 
88 #define PF_DEBUGNAME	"pfsync: "
89 #include <net/pfvar.h>
90 #include <net/pfvar_priv.h>
91 #include <net/if_pfsync.h>
92 
93 #include "bpfilter.h"
94 #include "pfsync.h"
95 
96 #define PFSYNC_DEFER_NSEC 20000000ULL
97 
98 #define PFSYNC_MINPKT ( \
99 	sizeof(struct ip) + \
100 	sizeof(struct pfsync_header))
101 
102 int	pfsync_upd_tcp(struct pf_state *, struct pfsync_state_peer *,
103 	    struct pfsync_state_peer *);
104 
105 int	pfsync_in_clr(caddr_t, int, int, int);
106 int	pfsync_in_iack(caddr_t, int, int, int);
107 int	pfsync_in_upd_c(caddr_t, int, int, int);
108 int	pfsync_in_ureq(caddr_t, int, int, int);
109 int	pfsync_in_del(caddr_t, int, int, int);
110 int	pfsync_in_del_c(caddr_t, int, int, int);
111 int	pfsync_in_bus(caddr_t, int, int, int);
112 int	pfsync_in_tdb(caddr_t, int, int, int);
113 int	pfsync_in_ins(caddr_t, int, int, int);
114 int	pfsync_in_upd(caddr_t, int, int, int);
115 int	pfsync_in_eof(caddr_t, int, int, int);
116 
117 int	pfsync_in_error(caddr_t, int, int, int);
118 
119 void	pfsync_update_state_locked(struct pf_state *);
120 
121 const struct {
122 	int	(*in)(caddr_t, int, int, int);
123 	size_t	len;
124 } pfsync_acts[] = {
125 	/* PFSYNC_ACT_CLR */
126 	{ pfsync_in_clr,	sizeof(struct pfsync_clr) },
127 	 /* PFSYNC_ACT_OINS */
128 	{ pfsync_in_error,	0 },
129 	/* PFSYNC_ACT_INS_ACK */
130 	{ pfsync_in_iack,	sizeof(struct pfsync_ins_ack) },
131 	/* PFSYNC_ACT_OUPD */
132 	{ pfsync_in_error,	0 },
133 	/* PFSYNC_ACT_UPD_C */
134 	{ pfsync_in_upd_c,	sizeof(struct pfsync_upd_c) },
135 	/* PFSYNC_ACT_UPD_REQ */
136 	{ pfsync_in_ureq,	sizeof(struct pfsync_upd_req) },
137 	/* PFSYNC_ACT_DEL */
138 	{ pfsync_in_del,	sizeof(struct pfsync_state) },
139 	/* PFSYNC_ACT_DEL_C */
140 	{ pfsync_in_del_c,	sizeof(struct pfsync_del_c) },
141 	/* PFSYNC_ACT_INS_F */
142 	{ pfsync_in_error,	0 },
143 	/* PFSYNC_ACT_DEL_F */
144 	{ pfsync_in_error,	0 },
145 	/* PFSYNC_ACT_BUS */
146 	{ pfsync_in_bus,	sizeof(struct pfsync_bus) },
147 	/* PFSYNC_ACT_OTDB */
148 	{ pfsync_in_error,	0 },
149 	/* PFSYNC_ACT_EOF */
150 	{ pfsync_in_error,	0 },
151 	/* PFSYNC_ACT_INS */
152 	{ pfsync_in_ins,	sizeof(struct pfsync_state) },
153 	/* PFSYNC_ACT_UPD */
154 	{ pfsync_in_upd,	sizeof(struct pfsync_state) },
155 	/* PFSYNC_ACT_TDB */
156 	{ pfsync_in_tdb,	sizeof(struct pfsync_tdb) },
157 };
158 
159 struct pfsync_q {
160 	void		(*write)(struct pf_state *, void *);
161 	size_t		len;
162 	u_int8_t	action;
163 };
164 
165 /* we have one of these for every PFSYNC_S_ */
166 void	pfsync_out_state(struct pf_state *, void *);
167 void	pfsync_out_iack(struct pf_state *, void *);
168 void	pfsync_out_upd_c(struct pf_state *, void *);
169 void	pfsync_out_del(struct pf_state *, void *);
170 
171 struct pfsync_q pfsync_qs[] = {
172 	{ pfsync_out_iack,  sizeof(struct pfsync_ins_ack), PFSYNC_ACT_INS_ACK },
173 	{ pfsync_out_upd_c, sizeof(struct pfsync_upd_c),   PFSYNC_ACT_UPD_C },
174 	{ pfsync_out_del,   sizeof(struct pfsync_del_c),   PFSYNC_ACT_DEL_C },
175 	{ pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_INS },
176 	{ pfsync_out_state, sizeof(struct pfsync_state),   PFSYNC_ACT_UPD }
177 };
178 
179 void	pfsync_q_ins(struct pf_state *, int);
180 void	pfsync_q_del(struct pf_state *);
181 
182 struct pfsync_upd_req_item {
183 	TAILQ_ENTRY(pfsync_upd_req_item)	ur_entry;
184 	TAILQ_ENTRY(pfsync_upd_req_item)	ur_snap;
185 	struct pfsync_upd_req			ur_msg;
186 };
187 TAILQ_HEAD(pfsync_upd_reqs, pfsync_upd_req_item);
188 
189 struct pfsync_deferral {
190 	TAILQ_ENTRY(pfsync_deferral)		 pd_entry;
191 	struct pf_state				*pd_st;
192 	struct mbuf				*pd_m;
193 	uint64_t				 pd_deadline;
194 };
195 TAILQ_HEAD(pfsync_deferrals, pfsync_deferral);
196 
197 #define PFSYNC_PLSIZE	MAX(sizeof(struct pfsync_upd_req_item), \
198 			    sizeof(struct pfsync_deferral))
199 
200 void	pfsync_out_tdb(struct tdb *, void *);
201 
202 struct pfsync_softc {
203 	struct ifnet		 sc_if;
204 	unsigned int		 sc_sync_ifidx;
205 
206 	struct pool		 sc_pool;
207 
208 	struct ip_moptions	 sc_imo;
209 
210 	struct in_addr		 sc_sync_peer;
211 	u_int8_t		 sc_maxupdates;
212 
213 	struct ip		 sc_template;
214 
215 	struct pf_state_queue	 sc_qs[PFSYNC_S_COUNT];
216 	struct mutex		 sc_st_mtx;
217 	size_t			 sc_len;
218 
219 	struct pfsync_upd_reqs	 sc_upd_req_list;
220 	struct mutex		 sc_upd_req_mtx;
221 
222 	int			 sc_initial_bulk;
223 	int			 sc_link_demoted;
224 
225 	int			 sc_defer;
226 	struct pfsync_deferrals	 sc_deferrals;
227 	u_int			 sc_deferred;
228 	struct mutex		 sc_deferrals_mtx;
229 	struct timeout		 sc_deferrals_tmo;
230 
231 	void			*sc_plus;
232 	size_t			 sc_pluslen;
233 
234 	u_int32_t		 sc_ureq_sent;
235 	int			 sc_bulk_tries;
236 	struct timeout		 sc_bulkfail_tmo;
237 
238 	u_int32_t		 sc_ureq_received;
239 	struct pf_state		*sc_bulk_next;
240 	struct pf_state		*sc_bulk_last;
241 	struct timeout		 sc_bulk_tmo;
242 
243 	TAILQ_HEAD(, tdb)	 sc_tdb_q;
244 	struct mutex		 sc_tdb_mtx;
245 
246 	struct task		 sc_ltask;
247 	struct task		 sc_dtask;
248 
249 	struct timeout		 sc_tmo;
250 };
251 
252 struct pfsync_snapshot {
253 	struct pfsync_softc	*sn_sc;
254 	struct pf_state_queue	 sn_qs[PFSYNC_S_COUNT];
255 	struct pfsync_upd_reqs	 sn_upd_req_list;
256 	TAILQ_HEAD(, tdb)	 sn_tdb_q;
257 	size_t			 sn_len;
258 	void			*sn_plus;
259 	size_t			 sn_pluslen;
260 };
261 
262 struct pfsync_softc	*pfsyncif = NULL;
263 struct cpumem		*pfsynccounters;
264 
265 void	pfsyncattach(int);
266 int	pfsync_clone_create(struct if_clone *, int);
267 int	pfsync_clone_destroy(struct ifnet *);
268 void	pfsync_update_net_tdb(struct pfsync_tdb *);
269 int	pfsyncoutput(struct ifnet *, struct mbuf *, struct sockaddr *,
270 	    struct rtentry *);
271 int	pfsyncioctl(struct ifnet *, u_long, caddr_t);
272 void	pfsyncstart(struct ifqueue *);
273 void	pfsync_syncdev_state(void *);
274 void	pfsync_ifdetach(void *);
275 
276 void	pfsync_deferred(struct pf_state *, int);
277 void	pfsync_undefer(struct pfsync_deferral *, int);
278 void	pfsync_deferrals_tmo(void *);
279 
280 void	pfsync_cancel_full_update(struct pfsync_softc *);
281 void	pfsync_request_full_update(struct pfsync_softc *);
282 void	pfsync_request_update(u_int32_t, u_int64_t);
283 void	pfsync_update_state_req(struct pf_state *);
284 
285 void	pfsync_drop(struct pfsync_softc *);
286 void	pfsync_sendout(void);
287 void	pfsync_send_plus(void *, size_t);
288 void	pfsync_timeout(void *);
289 void	pfsync_tdb_timeout(void *);
290 
291 void	pfsync_bulk_start(void);
292 void	pfsync_bulk_status(u_int8_t);
293 void	pfsync_bulk_update(void *);
294 void	pfsync_bulk_fail(void *);
295 
296 void	pfsync_grab_snapshot(struct pfsync_snapshot *, struct pfsync_softc *);
297 void	pfsync_drop_snapshot(struct pfsync_snapshot *);
298 
299 void	pfsync_send_dispatch(void *);
300 void	pfsync_send_pkt(struct mbuf *);
301 
302 static struct mbuf_queue	pfsync_mq;
303 static struct task	pfsync_task =
304     TASK_INITIALIZER(pfsync_send_dispatch, &pfsync_mq);
305 
306 #define PFSYNC_MAX_BULKTRIES	12
307 int	pfsync_sync_ok;
308 
309 struct if_clone	pfsync_cloner =
310     IF_CLONE_INITIALIZER("pfsync", pfsync_clone_create, pfsync_clone_destroy);
311 
312 void
313 pfsyncattach(int npfsync)
314 {
315 	if_clone_attach(&pfsync_cloner);
316 	pfsynccounters = counters_alloc(pfsyncs_ncounters);
317 	mq_init(&pfsync_mq, 4096, IPL_MPFLOOR);
318 }
319 
320 int
321 pfsync_clone_create(struct if_clone *ifc, int unit)
322 {
323 	struct pfsync_softc *sc;
324 	struct ifnet *ifp;
325 	int q;
326 
327 	if (unit != 0)
328 		return (EINVAL);
329 
330 	pfsync_sync_ok = 1;
331 
332 	sc = malloc(sizeof(*pfsyncif), M_DEVBUF, M_WAITOK|M_ZERO);
333 	for (q = 0; q < PFSYNC_S_COUNT; q++)
334 		TAILQ_INIT(&sc->sc_qs[q]);
335 	mtx_init(&sc->sc_st_mtx, IPL_MPFLOOR);
336 
337 	pool_init(&sc->sc_pool, PFSYNC_PLSIZE, 0, IPL_MPFLOOR, 0, "pfsync",
338 	    NULL);
339 	TAILQ_INIT(&sc->sc_upd_req_list);
340 	mtx_init(&sc->sc_upd_req_mtx, IPL_MPFLOOR);
341 	TAILQ_INIT(&sc->sc_deferrals);
342 	mtx_init(&sc->sc_deferrals_mtx, IPL_MPFLOOR);
343 	timeout_set_proc(&sc->sc_deferrals_tmo, pfsync_deferrals_tmo, sc);
344 	task_set(&sc->sc_ltask, pfsync_syncdev_state, sc);
345 	task_set(&sc->sc_dtask, pfsync_ifdetach, sc);
346 	sc->sc_deferred = 0;
347 
348 	TAILQ_INIT(&sc->sc_tdb_q);
349 	mtx_init(&sc->sc_tdb_mtx, IPL_MPFLOOR);
350 
351 	sc->sc_len = PFSYNC_MINPKT;
352 	sc->sc_maxupdates = 128;
353 
354 	sc->sc_imo.imo_membership = mallocarray(IP_MIN_MEMBERSHIPS,
355 	    sizeof(struct in_multi *), M_IPMOPTS, M_WAITOK|M_ZERO);
356 	sc->sc_imo.imo_max_memberships = IP_MIN_MEMBERSHIPS;
357 
358 	ifp = &sc->sc_if;
359 	snprintf(ifp->if_xname, sizeof ifp->if_xname, "pfsync%d", unit);
360 	ifp->if_softc = sc;
361 	ifp->if_ioctl = pfsyncioctl;
362 	ifp->if_output = pfsyncoutput;
363 	ifp->if_qstart = pfsyncstart;
364 	ifp->if_type = IFT_PFSYNC;
365 	ifp->if_hdrlen = sizeof(struct pfsync_header);
366 	ifp->if_mtu = ETHERMTU;
367 	ifp->if_xflags = IFXF_CLONED | IFXF_MPSAFE;
368 	timeout_set_proc(&sc->sc_tmo, pfsync_timeout, NULL);
369 	timeout_set_proc(&sc->sc_bulk_tmo, pfsync_bulk_update, NULL);
370 	timeout_set_proc(&sc->sc_bulkfail_tmo, pfsync_bulk_fail, NULL);
371 
372 	if_attach(ifp);
373 	if_alloc_sadl(ifp);
374 
375 #if NCARP > 0
376 	if_addgroup(ifp, "carp");
377 #endif
378 
379 #if NBPFILTER > 0
380 	bpfattach(&sc->sc_if.if_bpf, ifp, DLT_PFSYNC, PFSYNC_HDRLEN);
381 #endif
382 
383 	pfsyncif = sc;
384 
385 	return (0);
386 }
387 
388 int
389 pfsync_clone_destroy(struct ifnet *ifp)
390 {
391 	struct pfsync_softc *sc = ifp->if_softc;
392 	struct ifnet *ifp0;
393 	struct pfsync_deferral *pd;
394 	struct pfsync_deferrals	 deferrals;
395 
396 	NET_LOCK();
397 
398 #if NCARP > 0
399 	if (!pfsync_sync_ok)
400 		carp_group_demote_adj(&sc->sc_if, -1, "pfsync destroy");
401 	if (sc->sc_link_demoted)
402 		carp_group_demote_adj(&sc->sc_if, -1, "pfsync destroy");
403 #endif
404 	if ((ifp0 = if_get(sc->sc_sync_ifidx)) != NULL) {
405 		if_linkstatehook_del(ifp0, &sc->sc_ltask);
406 		if_detachhook_del(ifp0, &sc->sc_dtask);
407 	}
408 	if_put(ifp0);
409 
410 	/* XXXSMP breaks atomicity */
411 	NET_UNLOCK();
412 	if_detach(ifp);
413 	NET_LOCK();
414 
415 	pfsync_drop(sc);
416 
417 	if (sc->sc_deferred > 0) {
418 		TAILQ_INIT(&deferrals);
419 		mtx_enter(&sc->sc_deferrals_mtx);
420 		TAILQ_CONCAT(&deferrals, &sc->sc_deferrals, pd_entry);
421 		sc->sc_deferred = 0;
422 		mtx_leave(&sc->sc_deferrals_mtx);
423 
424 		while ((pd = TAILQ_FIRST(&deferrals)) != NULL) {
425 			TAILQ_REMOVE(&deferrals, pd, pd_entry);
426 			pfsync_undefer(pd, 0);
427 		}
428 	}
429 
430 	pfsyncif = NULL;
431 	timeout_del(&sc->sc_bulkfail_tmo);
432 	timeout_del(&sc->sc_bulk_tmo);
433 	timeout_del(&sc->sc_tmo);
434 
435 	NET_UNLOCK();
436 
437 	pool_destroy(&sc->sc_pool);
438 	free(sc->sc_imo.imo_membership, M_IPMOPTS,
439 	    sc->sc_imo.imo_max_memberships * sizeof(struct in_multi *));
440 	free(sc, M_DEVBUF, sizeof(*sc));
441 
442 	return (0);
443 }
444 
445 /*
446  * Start output on the pfsync interface.
447  */
448 void
449 pfsyncstart(struct ifqueue *ifq)
450 {
451 	ifq_purge(ifq);
452 }
453 
454 void
455 pfsync_syncdev_state(void *arg)
456 {
457 	struct pfsync_softc *sc = arg;
458 	struct ifnet *ifp;
459 
460 	if ((sc->sc_if.if_flags & IFF_UP) == 0)
461 		return;
462 	if ((ifp = if_get(sc->sc_sync_ifidx)) == NULL)
463 		return;
464 
465 	if (ifp->if_link_state == LINK_STATE_DOWN) {
466 		sc->sc_if.if_flags &= ~IFF_RUNNING;
467 		if (!sc->sc_link_demoted) {
468 #if NCARP > 0
469 			carp_group_demote_adj(&sc->sc_if, 1,
470 			    "pfsync link state down");
471 #endif
472 			sc->sc_link_demoted = 1;
473 		}
474 
475 		/* drop everything */
476 		timeout_del(&sc->sc_tmo);
477 		pfsync_drop(sc);
478 
479 		pfsync_cancel_full_update(sc);
480 	} else if (sc->sc_link_demoted) {
481 		sc->sc_if.if_flags |= IFF_RUNNING;
482 
483 		pfsync_request_full_update(sc);
484 	}
485 
486 	if_put(ifp);
487 }
488 
489 void
490 pfsync_ifdetach(void *arg)
491 {
492 	struct pfsync_softc *sc = arg;
493 	struct ifnet *ifp;
494 
495 	if ((ifp = if_get(sc->sc_sync_ifidx)) != NULL) {
496 		if_linkstatehook_del(ifp, &sc->sc_ltask);
497 		if_detachhook_del(ifp, &sc->sc_dtask);
498 	}
499 	if_put(ifp);
500 
501 	sc->sc_sync_ifidx = 0;
502 }
503 
504 int
505 pfsync_input(struct mbuf **mp, int *offp, int proto, int af)
506 {
507 	struct mbuf *n, *m = *mp;
508 	struct pfsync_softc *sc = pfsyncif;
509 	struct ip *ip = mtod(m, struct ip *);
510 	struct pfsync_header *ph;
511 	struct pfsync_subheader subh;
512 	int offset, noff, len, count, mlen, flags = 0;
513 	int e;
514 
515 	NET_ASSERT_LOCKED();
516 
517 	pfsyncstat_inc(pfsyncs_ipackets);
518 
519 	/* verify that we have a sync interface configured */
520 	if (sc == NULL || !ISSET(sc->sc_if.if_flags, IFF_RUNNING) ||
521 	    sc->sc_sync_ifidx == 0 || !pf_status.running)
522 		goto done;
523 
524 	/* verify that the packet came in on the right interface */
525 	if (sc->sc_sync_ifidx != m->m_pkthdr.ph_ifidx) {
526 		pfsyncstat_inc(pfsyncs_badif);
527 		goto done;
528 	}
529 
530 	sc->sc_if.if_ipackets++;
531 	sc->sc_if.if_ibytes += m->m_pkthdr.len;
532 
533 	/* verify that the IP TTL is 255. */
534 	if (ip->ip_ttl != PFSYNC_DFLTTL) {
535 		pfsyncstat_inc(pfsyncs_badttl);
536 		goto done;
537 	}
538 
539 	offset = ip->ip_hl << 2;
540 	n = m_pulldown(m, offset, sizeof(*ph), &noff);
541 	if (n == NULL) {
542 		pfsyncstat_inc(pfsyncs_hdrops);
543 		return IPPROTO_DONE;
544 	}
545 	ph = (struct pfsync_header *)(n->m_data + noff);
546 
547 	/* verify the version */
548 	if (ph->version != PFSYNC_VERSION) {
549 		pfsyncstat_inc(pfsyncs_badver);
550 		goto done;
551 	}
552 	len = ntohs(ph->len) + offset;
553 	if (m->m_pkthdr.len < len) {
554 		pfsyncstat_inc(pfsyncs_badlen);
555 		goto done;
556 	}
557 
558 	if (!bcmp(&ph->pfcksum, &pf_status.pf_chksum, PF_MD5_DIGEST_LENGTH))
559 		flags = PFSYNC_SI_CKSUM;
560 
561 	offset += sizeof(*ph);
562 	while (offset <= len - sizeof(subh)) {
563 		m_copydata(m, offset, sizeof(subh), &subh);
564 		offset += sizeof(subh);
565 
566 		mlen = subh.len << 2;
567 		count = ntohs(subh.count);
568 
569 		if (subh.action >= PFSYNC_ACT_MAX ||
570 		    subh.action >= nitems(pfsync_acts) ||
571 		    mlen < pfsync_acts[subh.action].len) {
572 			/*
573 			 * subheaders are always followed by at least one
574 			 * message, so if the peer is new
575 			 * enough to tell us how big its messages are then we
576 			 * know enough to skip them.
577 			 */
578 			if (count > 0 && mlen > 0) {
579 				offset += count * mlen;
580 				continue;
581 			}
582 			pfsyncstat_inc(pfsyncs_badact);
583 			goto done;
584 		}
585 
586 		n = m_pulldown(m, offset, mlen * count, &noff);
587 		if (n == NULL) {
588 			pfsyncstat_inc(pfsyncs_badlen);
589 			return IPPROTO_DONE;
590 		}
591 
592 		e = pfsync_acts[subh.action].in(n->m_data + noff, mlen, count,
593 		    flags);
594 		if (e != 0)
595 			goto done;
596 
597 		offset += mlen * count;
598 	}
599 
600 done:
601 	m_freem(m);
602 	return IPPROTO_DONE;
603 }
604 
605 int
606 pfsync_in_clr(caddr_t buf, int len, int count, int flags)
607 {
608 	struct pfsync_clr *clr;
609 	struct pf_state *st, *nexts;
610 	struct pfi_kif *kif;
611 	u_int32_t creatorid;
612 	int i;
613 
614 	PF_LOCK();
615 	for (i = 0; i < count; i++) {
616 		clr = (struct pfsync_clr *)buf + len * i;
617 		kif = NULL;
618 		creatorid = clr->creatorid;
619 		if (strlen(clr->ifname) &&
620 		    (kif = pfi_kif_find(clr->ifname)) == NULL)
621 			continue;
622 
623 		PF_STATE_ENTER_WRITE();
624 		RBT_FOREACH_SAFE(st, pf_state_tree_id, &tree_id, nexts) {
625 			if (st->creatorid == creatorid &&
626 			    ((kif && st->kif == kif) || !kif)) {
627 				SET(st->state_flags, PFSTATE_NOSYNC);
628 				pf_remove_state(st);
629 			}
630 		}
631 		PF_STATE_EXIT_WRITE();
632 	}
633 	PF_UNLOCK();
634 
635 	return (0);
636 }
637 
638 int
639 pfsync_in_ins(caddr_t buf, int len, int count, int flags)
640 {
641 	struct pfsync_state *sp;
642 	sa_family_t af1, af2;
643 	int i;
644 
645 	PF_LOCK();
646 	for (i = 0; i < count; i++) {
647 		sp = (struct pfsync_state *)(buf + len * i);
648 		af1 = sp->key[0].af;
649 		af2 = sp->key[1].af;
650 
651 		/* check for invalid values */
652 		if (sp->timeout >= PFTM_MAX ||
653 		    sp->src.state > PF_TCPS_PROXY_DST ||
654 		    sp->dst.state > PF_TCPS_PROXY_DST ||
655 		    sp->direction > PF_OUT ||
656 		    (((af1 || af2) &&
657 		     ((af1 != AF_INET && af1 != AF_INET6) ||
658 		      (af2 != AF_INET && af2 != AF_INET6))) ||
659 		    (sp->af != AF_INET && sp->af != AF_INET6))) {
660 			DPFPRINTF(LOG_NOTICE,
661 			    "pfsync_input: PFSYNC5_ACT_INS: invalid value");
662 			pfsyncstat_inc(pfsyncs_badval);
663 			continue;
664 		}
665 
666 		if (pf_state_import(sp, flags) == ENOMEM) {
667 			/* drop out, but process the rest of the actions */
668 			break;
669 		}
670 	}
671 	PF_UNLOCK();
672 
673 	return (0);
674 }
675 
676 int
677 pfsync_in_iack(caddr_t buf, int len, int count, int flags)
678 {
679 	struct pfsync_ins_ack *ia;
680 	struct pf_state_cmp id_key;
681 	struct pf_state *st;
682 	int i;
683 
684 	for (i = 0; i < count; i++) {
685 		ia = (struct pfsync_ins_ack *)(buf + len * i);
686 
687 		id_key.id = ia->id;
688 		id_key.creatorid = ia->creatorid;
689 
690 		PF_STATE_ENTER_READ();
691 		st = pf_find_state_byid(&id_key);
692 		pf_state_ref(st);
693 		PF_STATE_EXIT_READ();
694 		if (st == NULL)
695 			continue;
696 
697 		if (ISSET(st->state_flags, PFSTATE_ACK))
698 			pfsync_deferred(st, 0);
699 
700 		pf_state_unref(st);
701 	}
702 
703 	return (0);
704 }
705 
706 int
707 pfsync_upd_tcp(struct pf_state *st, struct pfsync_state_peer *src,
708     struct pfsync_state_peer *dst)
709 {
710 	int sync = 0;
711 
712 	/*
713 	 * The state should never go backwards except
714 	 * for syn-proxy states.  Neither should the
715 	 * sequence window slide backwards.
716 	 */
717 	if ((st->src.state > src->state &&
718 	    (st->src.state < PF_TCPS_PROXY_SRC ||
719 	    src->state >= PF_TCPS_PROXY_SRC)) ||
720 
721 	    (st->src.state == src->state &&
722 	    SEQ_GT(st->src.seqlo, ntohl(src->seqlo))))
723 		sync++;
724 	else
725 		pf_state_peer_ntoh(src, &st->src);
726 
727 	if ((st->dst.state > dst->state) ||
728 
729 	    (st->dst.state >= TCPS_SYN_SENT &&
730 	    SEQ_GT(st->dst.seqlo, ntohl(dst->seqlo))))
731 		sync++;
732 	else
733 		pf_state_peer_ntoh(dst, &st->dst);
734 
735 	return (sync);
736 }
737 
738 int
739 pfsync_in_upd(caddr_t buf, int len, int count, int flags)
740 {
741 	struct pfsync_state *sp;
742 	struct pf_state_cmp id_key;
743 	struct pf_state *st;
744 	int sync, error;
745 	int i;
746 
747 	for (i = 0; i < count; i++) {
748 		sp = (struct pfsync_state *)(buf + len * i);
749 
750 		/* check for invalid values */
751 		if (sp->timeout >= PFTM_MAX ||
752 		    sp->src.state > PF_TCPS_PROXY_DST ||
753 		    sp->dst.state > PF_TCPS_PROXY_DST) {
754 			DPFPRINTF(LOG_NOTICE,
755 			    "pfsync_input: PFSYNC_ACT_UPD: invalid value");
756 			pfsyncstat_inc(pfsyncs_badval);
757 			continue;
758 		}
759 
760 		id_key.id = sp->id;
761 		id_key.creatorid = sp->creatorid;
762 
763 		PF_STATE_ENTER_READ();
764 		st = pf_find_state_byid(&id_key);
765 		pf_state_ref(st);
766 		PF_STATE_EXIT_READ();
767 		if (st == NULL) {
768 			/* insert the update */
769 			PF_LOCK();
770 			error = pf_state_import(sp, flags);
771 			if (error)
772 				pfsyncstat_inc(pfsyncs_badstate);
773 			PF_UNLOCK();
774 			continue;
775 		}
776 
777 		if (ISSET(st->state_flags, PFSTATE_ACK))
778 			pfsync_deferred(st, 1);
779 
780 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP)
781 			sync = pfsync_upd_tcp(st, &sp->src, &sp->dst);
782 		else {
783 			sync = 0;
784 
785 			/*
786 			 * Non-TCP protocol state machine always go
787 			 * forwards
788 			 */
789 			if (st->src.state > sp->src.state)
790 				sync++;
791 			else
792 				pf_state_peer_ntoh(&sp->src, &st->src);
793 
794 			if (st->dst.state > sp->dst.state)
795 				sync++;
796 			else
797 				pf_state_peer_ntoh(&sp->dst, &st->dst);
798 		}
799 
800 		if (sync < 2) {
801 			pf_state_alloc_scrub_memory(&sp->dst, &st->dst);
802 			pf_state_peer_ntoh(&sp->dst, &st->dst);
803 			st->expire = getuptime();
804 			st->timeout = sp->timeout;
805 		}
806 		st->pfsync_time = getuptime();
807 
808 		if (sync) {
809 			pfsyncstat_inc(pfsyncs_stale);
810 
811 			pfsync_update_state(st);
812 			schednetisr(NETISR_PFSYNC);
813 		}
814 
815 		pf_state_unref(st);
816 	}
817 
818 	return (0);
819 }
820 
821 int
822 pfsync_in_upd_c(caddr_t buf, int len, int count, int flags)
823 {
824 	struct pfsync_upd_c *up;
825 	struct pf_state_cmp id_key;
826 	struct pf_state *st;
827 
828 	int sync;
829 
830 	int i;
831 
832 	for (i = 0; i < count; i++) {
833 		up = (struct pfsync_upd_c *)(buf + len * i);
834 
835 		/* check for invalid values */
836 		if (up->timeout >= PFTM_MAX ||
837 		    up->src.state > PF_TCPS_PROXY_DST ||
838 		    up->dst.state > PF_TCPS_PROXY_DST) {
839 			DPFPRINTF(LOG_NOTICE,
840 			    "pfsync_input: PFSYNC_ACT_UPD_C: invalid value");
841 			pfsyncstat_inc(pfsyncs_badval);
842 			continue;
843 		}
844 
845 		id_key.id = up->id;
846 		id_key.creatorid = up->creatorid;
847 
848 		PF_STATE_ENTER_READ();
849 		st = pf_find_state_byid(&id_key);
850 		pf_state_ref(st);
851 		PF_STATE_EXIT_READ();
852 		if (st == NULL) {
853 			/* We don't have this state. Ask for it. */
854 			pfsync_request_update(id_key.creatorid, id_key.id);
855 			continue;
856 		}
857 
858 		if (ISSET(st->state_flags, PFSTATE_ACK))
859 			pfsync_deferred(st, 1);
860 
861 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP)
862 			sync = pfsync_upd_tcp(st, &up->src, &up->dst);
863 		else {
864 			sync = 0;
865 			/*
866 			 * Non-TCP protocol state machine always go
867 			 * forwards
868 			 */
869 			if (st->src.state > up->src.state)
870 				sync++;
871 			else
872 				pf_state_peer_ntoh(&up->src, &st->src);
873 
874 			if (st->dst.state > up->dst.state)
875 				sync++;
876 			else
877 				pf_state_peer_ntoh(&up->dst, &st->dst);
878 		}
879 		if (sync < 2) {
880 			pf_state_alloc_scrub_memory(&up->dst, &st->dst);
881 			pf_state_peer_ntoh(&up->dst, &st->dst);
882 			st->expire = getuptime();
883 			st->timeout = up->timeout;
884 		}
885 		st->pfsync_time = getuptime();
886 
887 		if (sync) {
888 			pfsyncstat_inc(pfsyncs_stale);
889 
890 			pfsync_update_state(st);
891 			schednetisr(NETISR_PFSYNC);
892 		}
893 
894 		pf_state_unref(st);
895 	}
896 
897 	return (0);
898 }
899 
900 int
901 pfsync_in_ureq(caddr_t buf, int len, int count, int flags)
902 {
903 	struct pfsync_upd_req *ur;
904 	int i;
905 
906 	struct pf_state_cmp id_key;
907 	struct pf_state *st;
908 
909 	for (i = 0; i < count; i++) {
910 		ur = (struct pfsync_upd_req *)(buf + len * i);
911 
912 		id_key.id = ur->id;
913 		id_key.creatorid = ur->creatorid;
914 
915 		if (id_key.id == 0 && id_key.creatorid == 0)
916 			pfsync_bulk_start();
917 		else {
918 			PF_STATE_ENTER_READ();
919 			st = pf_find_state_byid(&id_key);
920 			pf_state_ref(st);
921 			PF_STATE_EXIT_READ();
922 			if (st == NULL) {
923 				pfsyncstat_inc(pfsyncs_badstate);
924 				continue;
925 			}
926 			if (ISSET(st->state_flags, PFSTATE_NOSYNC)) {
927 				pf_state_unref(st);
928 				continue;
929 			}
930 
931 			pfsync_update_state_req(st);
932 			pf_state_unref(st);
933 		}
934 	}
935 
936 	return (0);
937 }
938 
939 int
940 pfsync_in_del(caddr_t buf, int len, int count, int flags)
941 {
942 	struct pfsync_state *sp;
943 	struct pf_state_cmp id_key;
944 	struct pf_state *st;
945 	int i;
946 
947 	PF_STATE_ENTER_WRITE();
948 	for (i = 0; i < count; i++) {
949 		sp = (struct pfsync_state *)(buf + len * i);
950 
951 		id_key.id = sp->id;
952 		id_key.creatorid = sp->creatorid;
953 
954 		st = pf_find_state_byid(&id_key);
955 		if (st == NULL) {
956 			pfsyncstat_inc(pfsyncs_badstate);
957 			continue;
958 		}
959 		SET(st->state_flags, PFSTATE_NOSYNC);
960 		pf_remove_state(st);
961 	}
962 	PF_STATE_EXIT_WRITE();
963 
964 	return (0);
965 }
966 
967 int
968 pfsync_in_del_c(caddr_t buf, int len, int count, int flags)
969 {
970 	struct pfsync_del_c *sp;
971 	struct pf_state_cmp id_key;
972 	struct pf_state *st;
973 	int i;
974 
975 	PF_LOCK();
976 	PF_STATE_ENTER_WRITE();
977 	for (i = 0; i < count; i++) {
978 		sp = (struct pfsync_del_c *)(buf + len * i);
979 
980 		id_key.id = sp->id;
981 		id_key.creatorid = sp->creatorid;
982 
983 		st = pf_find_state_byid(&id_key);
984 		if (st == NULL) {
985 			pfsyncstat_inc(pfsyncs_badstate);
986 			continue;
987 		}
988 
989 		SET(st->state_flags, PFSTATE_NOSYNC);
990 		pf_remove_state(st);
991 	}
992 	PF_STATE_EXIT_WRITE();
993 	PF_UNLOCK();
994 
995 	return (0);
996 }
997 
998 int
999 pfsync_in_bus(caddr_t buf, int len, int count, int flags)
1000 {
1001 	struct pfsync_softc *sc = pfsyncif;
1002 	struct pfsync_bus *bus;
1003 
1004 	/* If we're not waiting for a bulk update, who cares. */
1005 	if (sc->sc_ureq_sent == 0)
1006 		return (0);
1007 
1008 	bus = (struct pfsync_bus *)buf;
1009 
1010 	switch (bus->status) {
1011 	case PFSYNC_BUS_START:
1012 		timeout_add(&sc->sc_bulkfail_tmo, 4 * hz +
1013 		    pf_pool_limits[PF_LIMIT_STATES].limit /
1014 		    ((sc->sc_if.if_mtu - PFSYNC_MINPKT) /
1015 		    sizeof(struct pfsync_state)));
1016 		DPFPRINTF(LOG_INFO, "received bulk update start");
1017 		break;
1018 
1019 	case PFSYNC_BUS_END:
1020 		if (getuptime() - ntohl(bus->endtime) >=
1021 		    sc->sc_ureq_sent) {
1022 			/* that's it, we're happy */
1023 			sc->sc_ureq_sent = 0;
1024 			sc->sc_bulk_tries = 0;
1025 			timeout_del(&sc->sc_bulkfail_tmo);
1026 #if NCARP > 0
1027 			if (!pfsync_sync_ok)
1028 				carp_group_demote_adj(&sc->sc_if, -1,
1029 				    sc->sc_link_demoted ?
1030 				    "pfsync link state up" :
1031 				    "pfsync bulk done");
1032 			if (sc->sc_initial_bulk) {
1033 				carp_group_demote_adj(&sc->sc_if, -32,
1034 				    "pfsync init");
1035 				sc->sc_initial_bulk = 0;
1036 			}
1037 #endif
1038 			pfsync_sync_ok = 1;
1039 			sc->sc_link_demoted = 0;
1040 			DPFPRINTF(LOG_INFO, "received valid bulk update end");
1041 		} else {
1042 			DPFPRINTF(LOG_WARNING, "received invalid "
1043 			    "bulk update end: bad timestamp");
1044 		}
1045 		break;
1046 	}
1047 
1048 	return (0);
1049 }
1050 
1051 int
1052 pfsync_in_tdb(caddr_t buf, int len, int count, int flags)
1053 {
1054 #if defined(IPSEC)
1055 	struct pfsync_tdb *tp;
1056 	int i;
1057 
1058 	for (i = 0; i < count; i++) {
1059 		tp = (struct pfsync_tdb *)(buf + len * i);
1060 		pfsync_update_net_tdb(tp);
1061 	}
1062 #endif
1063 
1064 	return (0);
1065 }
1066 
1067 #if defined(IPSEC)
1068 /* Update an in-kernel tdb. Silently fail if no tdb is found. */
1069 void
1070 pfsync_update_net_tdb(struct pfsync_tdb *pt)
1071 {
1072 	struct tdb		*tdb;
1073 
1074 	NET_ASSERT_LOCKED();
1075 
1076 	/* check for invalid values */
1077 	if (ntohl(pt->spi) <= SPI_RESERVED_MAX ||
1078 	    (pt->dst.sa.sa_family != AF_INET &&
1079 	     pt->dst.sa.sa_family != AF_INET6))
1080 		goto bad;
1081 
1082 	tdb = gettdb(ntohs(pt->rdomain), pt->spi,
1083 	    (union sockaddr_union *)&pt->dst, pt->sproto);
1084 	if (tdb) {
1085 		pt->rpl = betoh64(pt->rpl);
1086 		pt->cur_bytes = betoh64(pt->cur_bytes);
1087 
1088 		/* Neither replay nor byte counter should ever decrease. */
1089 		if (pt->rpl < tdb->tdb_rpl ||
1090 		    pt->cur_bytes < tdb->tdb_cur_bytes) {
1091 			tdb_unref(tdb);
1092 			goto bad;
1093 		}
1094 
1095 		tdb->tdb_rpl = pt->rpl;
1096 		tdb->tdb_cur_bytes = pt->cur_bytes;
1097 		tdb_unref(tdb);
1098 	}
1099 	return;
1100 
1101  bad:
1102 	DPFPRINTF(LOG_WARNING, "pfsync_insert: PFSYNC_ACT_TDB_UPD: "
1103 	    "invalid value");
1104 	pfsyncstat_inc(pfsyncs_badstate);
1105 	return;
1106 }
1107 #endif
1108 
1109 
1110 int
1111 pfsync_in_eof(caddr_t buf, int len, int count, int flags)
1112 {
1113 	if (len > 0 || count > 0)
1114 		pfsyncstat_inc(pfsyncs_badact);
1115 
1116 	/* we're done. let the caller return */
1117 	return (1);
1118 }
1119 
1120 int
1121 pfsync_in_error(caddr_t buf, int len, int count, int flags)
1122 {
1123 	pfsyncstat_inc(pfsyncs_badact);
1124 	return (-1);
1125 }
1126 
1127 int
1128 pfsyncoutput(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst,
1129 	struct rtentry *rt)
1130 {
1131 	m_freem(m);	/* drop packet */
1132 	return (EAFNOSUPPORT);
1133 }
1134 
1135 int
1136 pfsyncioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1137 {
1138 	struct proc *p = curproc;
1139 	struct pfsync_softc *sc = ifp->if_softc;
1140 	struct ifreq *ifr = (struct ifreq *)data;
1141 	struct ip_moptions *imo = &sc->sc_imo;
1142 	struct pfsyncreq pfsyncr;
1143 	struct ifnet *ifp0, *sifp;
1144 	struct ip *ip;
1145 	int error;
1146 
1147 	switch (cmd) {
1148 	case SIOCSIFFLAGS:
1149 		if ((ifp->if_flags & IFF_RUNNING) == 0 &&
1150 		    (ifp->if_flags & IFF_UP)) {
1151 			ifp->if_flags |= IFF_RUNNING;
1152 
1153 #if NCARP > 0
1154 			sc->sc_initial_bulk = 1;
1155 			carp_group_demote_adj(&sc->sc_if, 32, "pfsync init");
1156 #endif
1157 
1158 			pfsync_request_full_update(sc);
1159 		}
1160 		if ((ifp->if_flags & IFF_RUNNING) &&
1161 		    (ifp->if_flags & IFF_UP) == 0) {
1162 			ifp->if_flags &= ~IFF_RUNNING;
1163 
1164 			/* drop everything */
1165 			timeout_del(&sc->sc_tmo);
1166 			pfsync_drop(sc);
1167 
1168 			pfsync_cancel_full_update(sc);
1169 		}
1170 		break;
1171 	case SIOCSIFMTU:
1172 		if ((ifp0 = if_get(sc->sc_sync_ifidx)) == NULL)
1173 			return (EINVAL);
1174 		error = 0;
1175 		if (ifr->ifr_mtu <= PFSYNC_MINPKT ||
1176 		    ifr->ifr_mtu > ifp0->if_mtu) {
1177 			error = EINVAL;
1178 		}
1179 		if_put(ifp0);
1180 		if (error)
1181 			return error;
1182 		if (ifr->ifr_mtu < ifp->if_mtu)
1183 			pfsync_sendout();
1184 		ifp->if_mtu = ifr->ifr_mtu;
1185 		break;
1186 	case SIOCGETPFSYNC:
1187 		bzero(&pfsyncr, sizeof(pfsyncr));
1188 		if ((ifp0 = if_get(sc->sc_sync_ifidx)) != NULL) {
1189 			strlcpy(pfsyncr.pfsyncr_syncdev,
1190 			    ifp0->if_xname, IFNAMSIZ);
1191 		}
1192 		if_put(ifp0);
1193 		pfsyncr.pfsyncr_syncpeer = sc->sc_sync_peer;
1194 		pfsyncr.pfsyncr_maxupdates = sc->sc_maxupdates;
1195 		pfsyncr.pfsyncr_defer = sc->sc_defer;
1196 		return (copyout(&pfsyncr, ifr->ifr_data, sizeof(pfsyncr)));
1197 
1198 	case SIOCSETPFSYNC:
1199 		if ((error = suser(p)) != 0)
1200 			return (error);
1201 		if ((error = copyin(ifr->ifr_data, &pfsyncr, sizeof(pfsyncr))))
1202 			return (error);
1203 
1204 		if (pfsyncr.pfsyncr_syncpeer.s_addr == 0)
1205 			sc->sc_sync_peer.s_addr = INADDR_PFSYNC_GROUP;
1206 		else
1207 			sc->sc_sync_peer.s_addr =
1208 			    pfsyncr.pfsyncr_syncpeer.s_addr;
1209 
1210 		if (pfsyncr.pfsyncr_maxupdates > 255)
1211 			return (EINVAL);
1212 		sc->sc_maxupdates = pfsyncr.pfsyncr_maxupdates;
1213 
1214 		sc->sc_defer = pfsyncr.pfsyncr_defer;
1215 
1216 		if (pfsyncr.pfsyncr_syncdev[0] == 0) {
1217 			if ((ifp0 = if_get(sc->sc_sync_ifidx)) != NULL) {
1218 				if_linkstatehook_del(ifp0, &sc->sc_ltask);
1219 				if_detachhook_del(ifp0, &sc->sc_dtask);
1220 			}
1221 			if_put(ifp0);
1222 			sc->sc_sync_ifidx = 0;
1223 			if (imo->imo_num_memberships > 0) {
1224 				in_delmulti(imo->imo_membership[
1225 				    --imo->imo_num_memberships]);
1226 				imo->imo_ifidx = 0;
1227 			}
1228 			break;
1229 		}
1230 
1231 		if ((sifp = if_unit(pfsyncr.pfsyncr_syncdev)) == NULL)
1232 			return (EINVAL);
1233 
1234 		ifp0 = if_get(sc->sc_sync_ifidx);
1235 
1236 		if (sifp->if_mtu < sc->sc_if.if_mtu || (ifp0 != NULL &&
1237 		    sifp->if_mtu < ifp0->if_mtu) ||
1238 		    sifp->if_mtu < MCLBYTES - sizeof(struct ip))
1239 			pfsync_sendout();
1240 
1241 		if (ifp0) {
1242 			if_linkstatehook_del(ifp0, &sc->sc_ltask);
1243 			if_detachhook_del(ifp0, &sc->sc_dtask);
1244 		}
1245 		if_put(ifp0);
1246 		sc->sc_sync_ifidx = sifp->if_index;
1247 
1248 		if (imo->imo_num_memberships > 0) {
1249 			in_delmulti(imo->imo_membership[--imo->imo_num_memberships]);
1250 			imo->imo_ifidx = 0;
1251 		}
1252 
1253 		if (sc->sc_sync_peer.s_addr == INADDR_PFSYNC_GROUP) {
1254 			struct in_addr addr;
1255 
1256 			if (!(sifp->if_flags & IFF_MULTICAST)) {
1257 				sc->sc_sync_ifidx = 0;
1258 				if_put(sifp);
1259 				return (EADDRNOTAVAIL);
1260 			}
1261 
1262 			addr.s_addr = INADDR_PFSYNC_GROUP;
1263 
1264 			if ((imo->imo_membership[0] =
1265 			    in_addmulti(&addr, sifp)) == NULL) {
1266 				sc->sc_sync_ifidx = 0;
1267 				if_put(sifp);
1268 				return (ENOBUFS);
1269 			}
1270 			imo->imo_num_memberships++;
1271 			imo->imo_ifidx = sc->sc_sync_ifidx;
1272 			imo->imo_ttl = PFSYNC_DFLTTL;
1273 			imo->imo_loop = 0;
1274 		}
1275 
1276 		ip = &sc->sc_template;
1277 		bzero(ip, sizeof(*ip));
1278 		ip->ip_v = IPVERSION;
1279 		ip->ip_hl = sizeof(sc->sc_template) >> 2;
1280 		ip->ip_tos = IPTOS_LOWDELAY;
1281 		/* len and id are set later */
1282 		ip->ip_off = htons(IP_DF);
1283 		ip->ip_ttl = PFSYNC_DFLTTL;
1284 		ip->ip_p = IPPROTO_PFSYNC;
1285 		ip->ip_src.s_addr = INADDR_ANY;
1286 		ip->ip_dst.s_addr = sc->sc_sync_peer.s_addr;
1287 
1288 		if_linkstatehook_add(sifp, &sc->sc_ltask);
1289 		if_detachhook_add(sifp, &sc->sc_dtask);
1290 		if_put(sifp);
1291 
1292 		pfsync_request_full_update(sc);
1293 
1294 		break;
1295 
1296 	default:
1297 		return (ENOTTY);
1298 	}
1299 
1300 	return (0);
1301 }
1302 
1303 void
1304 pfsync_out_state(struct pf_state *st, void *buf)
1305 {
1306 	struct pfsync_state *sp = buf;
1307 
1308 	pf_state_export(sp, st);
1309 }
1310 
1311 void
1312 pfsync_out_iack(struct pf_state *st, void *buf)
1313 {
1314 	struct pfsync_ins_ack *iack = buf;
1315 
1316 	iack->id = st->id;
1317 	iack->creatorid = st->creatorid;
1318 }
1319 
1320 void
1321 pfsync_out_upd_c(struct pf_state *st, void *buf)
1322 {
1323 	struct pfsync_upd_c *up = buf;
1324 
1325 	bzero(up, sizeof(*up));
1326 	up->id = st->id;
1327 	pf_state_peer_hton(&st->src, &up->src);
1328 	pf_state_peer_hton(&st->dst, &up->dst);
1329 	up->creatorid = st->creatorid;
1330 	up->timeout = st->timeout;
1331 }
1332 
1333 void
1334 pfsync_out_del(struct pf_state *st, void *buf)
1335 {
1336 	struct pfsync_del_c *dp = buf;
1337 
1338 	dp->id = st->id;
1339 	dp->creatorid = st->creatorid;
1340 
1341 	SET(st->state_flags, PFSTATE_NOSYNC);
1342 }
1343 
1344 void
1345 pfsync_grab_snapshot(struct pfsync_snapshot *sn, struct pfsync_softc *sc)
1346 {
1347 	int q;
1348 	struct pf_state *st;
1349 	struct pfsync_upd_req_item *ur;
1350 #if defined(IPSEC)
1351 	struct tdb *tdb;
1352 #endif
1353 
1354 	sn->sn_sc = sc;
1355 
1356 	mtx_enter(&sc->sc_st_mtx);
1357 	mtx_enter(&sc->sc_upd_req_mtx);
1358 	mtx_enter(&sc->sc_tdb_mtx);
1359 
1360 	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1361 		TAILQ_INIT(&sn->sn_qs[q]);
1362 
1363 		while ((st = TAILQ_FIRST(&sc->sc_qs[q])) != NULL) {
1364 			TAILQ_REMOVE(&sc->sc_qs[q], st, sync_list);
1365 			mtx_enter(&st->mtx);
1366 			if (st->snapped == 0) {
1367 				TAILQ_INSERT_TAIL(&sn->sn_qs[q], st, sync_snap);
1368 				st->snapped = 1;
1369 				mtx_leave(&st->mtx);
1370 			} else {
1371 				/*
1372 				 * item is on snapshot list already, so we can
1373 				 * skip it now.
1374 				 */
1375 				mtx_leave(&st->mtx);
1376 				pf_state_unref(st);
1377 			}
1378 		}
1379 	}
1380 
1381 	TAILQ_INIT(&sn->sn_upd_req_list);
1382 	while ((ur = TAILQ_FIRST(&sc->sc_upd_req_list)) != NULL) {
1383 		TAILQ_REMOVE(&sc->sc_upd_req_list, ur, ur_entry);
1384 		TAILQ_INSERT_TAIL(&sn->sn_upd_req_list, ur, ur_snap);
1385 	}
1386 
1387 	TAILQ_INIT(&sn->sn_tdb_q);
1388 #if defined(IPSEC)
1389 	while ((tdb = TAILQ_FIRST(&sc->sc_tdb_q)) != NULL) {
1390 		TAILQ_REMOVE(&sc->sc_tdb_q, tdb, tdb_sync_entry);
1391 		TAILQ_INSERT_TAIL(&sn->sn_tdb_q, tdb, tdb_sync_snap);
1392 
1393 		mtx_enter(&tdb->tdb_mtx);
1394 		KASSERT(!ISSET(tdb->tdb_flags, TDBF_PFSYNC_SNAPPED));
1395 		SET(tdb->tdb_flags, TDBF_PFSYNC_SNAPPED);
1396 		mtx_leave(&tdb->tdb_mtx);
1397 	}
1398 #endif
1399 
1400 	sn->sn_len = sc->sc_len;
1401 	sc->sc_len = PFSYNC_MINPKT;
1402 
1403 	sn->sn_plus = sc->sc_plus;
1404 	sc->sc_plus = NULL;
1405 	sn->sn_pluslen = sc->sc_pluslen;
1406 	sc->sc_pluslen = 0;
1407 
1408 	mtx_leave(&sc->sc_tdb_mtx);
1409 	mtx_leave(&sc->sc_upd_req_mtx);
1410 	mtx_leave(&sc->sc_st_mtx);
1411 }
1412 
1413 void
1414 pfsync_drop_snapshot(struct pfsync_snapshot *sn)
1415 {
1416 	struct pf_state *st;
1417 	struct pfsync_upd_req_item *ur;
1418 #if defined(IPSEC)
1419 	struct tdb *t;
1420 #endif
1421 	int q;
1422 
1423 	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1424 		if (TAILQ_EMPTY(&sn->sn_qs[q]))
1425 			continue;
1426 
1427 		while ((st = TAILQ_FIRST(&sn->sn_qs[q])) != NULL) {
1428 			mtx_enter(&st->mtx);
1429 			KASSERT(st->sync_state == q);
1430 			KASSERT(st->snapped == 1);
1431 			TAILQ_REMOVE(&sn->sn_qs[q], st, sync_snap);
1432 			st->sync_state = PFSYNC_S_NONE;
1433 			st->snapped = 0;
1434 			mtx_leave(&st->mtx);
1435 			pf_state_unref(st);
1436 		}
1437 	}
1438 
1439 	while ((ur = TAILQ_FIRST(&sn->sn_upd_req_list)) != NULL) {
1440 		TAILQ_REMOVE(&sn->sn_upd_req_list, ur, ur_snap);
1441 		pool_put(&sn->sn_sc->sc_pool, ur);
1442 	}
1443 
1444 #if defined(IPSEC)
1445 	while ((t = TAILQ_FIRST(&sn->sn_tdb_q)) != NULL) {
1446 		TAILQ_REMOVE(&sn->sn_tdb_q, t, tdb_sync_snap);
1447 		mtx_enter(&t->tdb_mtx);
1448 		KASSERT(ISSET(t->tdb_flags, TDBF_PFSYNC_SNAPPED));
1449 		CLR(t->tdb_flags, TDBF_PFSYNC_SNAPPED);
1450 		CLR(t->tdb_flags, TDBF_PFSYNC);
1451 		mtx_leave(&t->tdb_mtx);
1452 	}
1453 #endif
1454 }
1455 
1456 int
1457 pfsync_is_snapshot_empty(struct pfsync_snapshot *sn)
1458 {
1459 	int	q;
1460 
1461 	for (q = 0; q < PFSYNC_S_COUNT; q++)
1462 		if (!TAILQ_EMPTY(&sn->sn_qs[q]))
1463 			return (0);
1464 
1465 	if (!TAILQ_EMPTY(&sn->sn_upd_req_list))
1466 		return (0);
1467 
1468 	if (!TAILQ_EMPTY(&sn->sn_tdb_q))
1469 		return (0);
1470 
1471 	return (sn->sn_plus == NULL);
1472 }
1473 
1474 void
1475 pfsync_drop(struct pfsync_softc *sc)
1476 {
1477 	struct pfsync_snapshot	sn;
1478 
1479 	pfsync_grab_snapshot(&sn, sc);
1480 	pfsync_drop_snapshot(&sn);
1481 }
1482 
1483 void
1484 pfsync_send_dispatch(void *xmq)
1485 {
1486 	struct mbuf_queue *mq = xmq;
1487 	struct pfsync_softc *sc;
1488 	struct mbuf *m;
1489 	struct mbuf_list ml;
1490 	int error;
1491 
1492 	mq_delist(mq, &ml);
1493 	if (ml_empty(&ml))
1494 		return;
1495 
1496 	NET_LOCK();
1497 	sc = pfsyncif;
1498 	if (sc == NULL) {
1499 		ml_purge(&ml);
1500 		goto done;
1501 	}
1502 
1503 	while ((m = ml_dequeue(&ml)) != NULL) {
1504 		if ((error = ip_output(m, NULL, NULL, IP_RAWOUTPUT,
1505 		    &sc->sc_imo, NULL, 0)) == 0)
1506 			pfsyncstat_inc(pfsyncs_opackets);
1507 		else {
1508 			DPFPRINTF(LOG_DEBUG,
1509 			    "ip_output() @ %s failed (%d)\n", __func__, error);
1510 			pfsyncstat_inc(pfsyncs_oerrors);
1511 		}
1512 	}
1513 done:
1514 	NET_UNLOCK();
1515 }
1516 
1517 void
1518 pfsync_send_pkt(struct mbuf *m)
1519 {
1520 	if (mq_enqueue(&pfsync_mq, m) != 0) {
1521 		pfsyncstat_inc(pfsyncs_oerrors);
1522 		DPFPRINTF(LOG_DEBUG, "mq_enqueue() @ %s failed, queue full\n",
1523 		    __func__);
1524 	} else
1525 		task_add(net_tq(0), &pfsync_task);
1526 }
1527 
1528 void
1529 pfsync_sendout(void)
1530 {
1531 	struct pfsync_snapshot sn;
1532 	struct pfsync_softc *sc = pfsyncif;
1533 #if NBPFILTER > 0
1534 	struct ifnet *ifp = &sc->sc_if;
1535 #endif
1536 	struct mbuf *m;
1537 	struct ip *ip;
1538 	struct pfsync_header *ph;
1539 	struct pfsync_subheader *subh;
1540 	struct pf_state *st;
1541 	struct pfsync_upd_req_item *ur;
1542 	int offset;
1543 	int q, count = 0;
1544 
1545 	if (sc == NULL || sc->sc_len == PFSYNC_MINPKT)
1546 		return;
1547 
1548 	if (!ISSET(sc->sc_if.if_flags, IFF_RUNNING) ||
1549 #if NBPFILTER > 0
1550 	    (ifp->if_bpf == NULL && sc->sc_sync_ifidx == 0)) {
1551 #else
1552 	    sc->sc_sync_ifidx == 0) {
1553 #endif
1554 		pfsync_drop(sc);
1555 		return;
1556 	}
1557 
1558 	pfsync_grab_snapshot(&sn, sc);
1559 
1560 	/*
1561 	 * Check below is sufficient to prevent us from sending empty packets,
1562 	 * but it does not stop us from sending short packets.
1563 	 */
1564 	if (pfsync_is_snapshot_empty(&sn))
1565 		return;
1566 
1567 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1568 	if (m == NULL) {
1569 		sc->sc_if.if_oerrors++;
1570 		pfsyncstat_inc(pfsyncs_onomem);
1571 		pfsync_drop_snapshot(&sn);
1572 		return;
1573 	}
1574 
1575 	if (max_linkhdr + sn.sn_len > MHLEN) {
1576 		MCLGETL(m, M_DONTWAIT, max_linkhdr + sn.sn_len);
1577 		if (!ISSET(m->m_flags, M_EXT)) {
1578 			m_free(m);
1579 			sc->sc_if.if_oerrors++;
1580 			pfsyncstat_inc(pfsyncs_onomem);
1581 			pfsync_drop_snapshot(&sn);
1582 			return;
1583 		}
1584 	}
1585 	m->m_data += max_linkhdr;
1586 	m->m_len = m->m_pkthdr.len = sn.sn_len;
1587 
1588 	/* build the ip header */
1589 	ip = mtod(m, struct ip *);
1590 	bcopy(&sc->sc_template, ip, sizeof(*ip));
1591 	offset = sizeof(*ip);
1592 
1593 	ip->ip_len = htons(m->m_pkthdr.len);
1594 	ip->ip_id = htons(ip_randomid());
1595 
1596 	/* build the pfsync header */
1597 	ph = (struct pfsync_header *)(m->m_data + offset);
1598 	bzero(ph, sizeof(*ph));
1599 	offset += sizeof(*ph);
1600 
1601 	ph->version = PFSYNC_VERSION;
1602 	ph->len = htons(sn.sn_len - sizeof(*ip));
1603 	bcopy(pf_status.pf_chksum, ph->pfcksum, PF_MD5_DIGEST_LENGTH);
1604 
1605 	if (!TAILQ_EMPTY(&sn.sn_upd_req_list)) {
1606 		subh = (struct pfsync_subheader *)(m->m_data + offset);
1607 		offset += sizeof(*subh);
1608 
1609 		count = 0;
1610 		while ((ur = TAILQ_FIRST(&sn.sn_upd_req_list)) != NULL) {
1611 			TAILQ_REMOVE(&sn.sn_upd_req_list, ur, ur_snap);
1612 
1613 			bcopy(&ur->ur_msg, m->m_data + offset,
1614 			    sizeof(ur->ur_msg));
1615 			offset += sizeof(ur->ur_msg);
1616 
1617 			pool_put(&sc->sc_pool, ur);
1618 
1619 			count++;
1620 		}
1621 
1622 		bzero(subh, sizeof(*subh));
1623 		subh->len = sizeof(ur->ur_msg) >> 2;
1624 		subh->action = PFSYNC_ACT_UPD_REQ;
1625 		subh->count = htons(count);
1626 	}
1627 
1628 	/* has someone built a custom region for us to add? */
1629 	if (sn.sn_plus != NULL) {
1630 		bcopy(sn.sn_plus, m->m_data + offset, sn.sn_pluslen);
1631 		offset += sn.sn_pluslen;
1632 		sn.sn_plus = NULL;	/* XXX memory leak ? */
1633 	}
1634 
1635 #if defined(IPSEC)
1636 	if (!TAILQ_EMPTY(&sn.sn_tdb_q)) {
1637 		struct tdb *t;
1638 
1639 		subh = (struct pfsync_subheader *)(m->m_data + offset);
1640 		offset += sizeof(*subh);
1641 
1642 		count = 0;
1643 		while ((t = TAILQ_FIRST(&sn.sn_tdb_q)) != NULL) {
1644 			TAILQ_REMOVE(&sn.sn_tdb_q, t, tdb_sync_snap);
1645 			pfsync_out_tdb(t, m->m_data + offset);
1646 			offset += sizeof(struct pfsync_tdb);
1647 			mtx_enter(&t->tdb_mtx);
1648 			KASSERT(ISSET(t->tdb_flags, TDBF_PFSYNC_SNAPPED));
1649 			CLR(t->tdb_flags, TDBF_PFSYNC_SNAPPED);
1650 			CLR(t->tdb_flags, TDBF_PFSYNC);
1651 			mtx_leave(&t->tdb_mtx);
1652 			tdb_unref(t);
1653 			count++;
1654 		}
1655 
1656 		bzero(subh, sizeof(*subh));
1657 		subh->action = PFSYNC_ACT_TDB;
1658 		subh->len = sizeof(struct pfsync_tdb) >> 2;
1659 		subh->count = htons(count);
1660 	}
1661 #endif
1662 
1663 	/* walk the queues */
1664 	for (q = 0; q < PFSYNC_S_COUNT; q++) {
1665 		if (TAILQ_EMPTY(&sn.sn_qs[q]))
1666 			continue;
1667 
1668 		subh = (struct pfsync_subheader *)(m->m_data + offset);
1669 		offset += sizeof(*subh);
1670 
1671 		count = 0;
1672 		while ((st = TAILQ_FIRST(&sn.sn_qs[q])) != NULL) {
1673 			mtx_enter(&st->mtx);
1674 			TAILQ_REMOVE(&sn.sn_qs[q], st, sync_snap);
1675 			KASSERT(st->sync_state == q);
1676 			KASSERT(st->snapped == 1);
1677 			st->sync_state = PFSYNC_S_NONE;
1678 			st->snapped = 0;
1679 			pfsync_qs[q].write(st, m->m_data + offset);
1680 			offset += pfsync_qs[q].len;
1681 			mtx_leave(&st->mtx);
1682 
1683 			pf_state_unref(st);
1684 			count++;
1685 		}
1686 
1687 		bzero(subh, sizeof(*subh));
1688 		subh->action = pfsync_qs[q].action;
1689 		subh->len = pfsync_qs[q].len >> 2;
1690 		subh->count = htons(count);
1691 	}
1692 
1693 	/* we're done, let's put it on the wire */
1694 #if NBPFILTER > 0
1695 	if (ifp->if_bpf) {
1696 		m->m_data += sizeof(*ip);
1697 		m->m_len = m->m_pkthdr.len = sn.sn_len - sizeof(*ip);
1698 		bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
1699 		m->m_data -= sizeof(*ip);
1700 		m->m_len = m->m_pkthdr.len = sn.sn_len;
1701 	}
1702 
1703 	if (sc->sc_sync_ifidx == 0) {
1704 		sc->sc_len = PFSYNC_MINPKT;
1705 		m_freem(m);
1706 		return;
1707 	}
1708 #endif
1709 
1710 	sc->sc_if.if_opackets++;
1711 	sc->sc_if.if_obytes += m->m_pkthdr.len;
1712 
1713 	m->m_pkthdr.ph_rtableid = sc->sc_if.if_rdomain;
1714 
1715 	pfsync_send_pkt(m);
1716 }
1717 
1718 void
1719 pfsync_insert_state(struct pf_state *st)
1720 {
1721 	struct pfsync_softc *sc = pfsyncif;
1722 
1723 	NET_ASSERT_LOCKED();
1724 
1725 	if (ISSET(st->rule.ptr->rule_flag, PFRULE_NOSYNC) ||
1726 	    st->key[PF_SK_WIRE]->proto == IPPROTO_PFSYNC) {
1727 		SET(st->state_flags, PFSTATE_NOSYNC);
1728 		return;
1729 	}
1730 
1731 	if (sc == NULL || !ISSET(sc->sc_if.if_flags, IFF_RUNNING) ||
1732 	    ISSET(st->state_flags, PFSTATE_NOSYNC))
1733 		return;
1734 
1735 	if (sc->sc_len == PFSYNC_MINPKT)
1736 		timeout_add_sec(&sc->sc_tmo, 1);
1737 
1738 	pfsync_q_ins(st, PFSYNC_S_INS);
1739 
1740 	st->sync_updates = 0;
1741 }
1742 
1743 int
1744 pfsync_defer(struct pf_state *st, struct mbuf *m, struct pfsync_deferral **ppd)
1745 {
1746 	struct pfsync_softc *sc = pfsyncif;
1747 	struct pfsync_deferral *pd;
1748 	unsigned int sched;
1749 
1750 	NET_ASSERT_LOCKED();
1751 
1752 	if (!sc->sc_defer ||
1753 	    ISSET(st->state_flags, PFSTATE_NOSYNC) ||
1754 	    m->m_flags & (M_BCAST|M_MCAST))
1755 		return (0);
1756 
1757 	pd = pool_get(&sc->sc_pool, M_NOWAIT);
1758 	if (pd == NULL)
1759 		return (0);
1760 
1761 	/*
1762 	 * deferral queue grows faster, than timeout can consume,
1763 	 * we have to ask packet (caller) to help timer and dispatch
1764 	 * one deferral for us.
1765 	 *
1766 	 * We wish to call pfsync_undefer() here. Unfortunately we can't,
1767 	 * because pfsync_undefer() will be calling to ip_output(),
1768 	 * which in turn will call to pf_test(), which would then attempt
1769 	 * to grab PF_LOCK() we currently hold.
1770 	 */
1771 	if (sc->sc_deferred >= 128) {
1772 		mtx_enter(&sc->sc_deferrals_mtx);
1773 		*ppd = TAILQ_FIRST(&sc->sc_deferrals);
1774 		if (*ppd != NULL) {
1775 			TAILQ_REMOVE(&sc->sc_deferrals, *ppd, pd_entry);
1776 			sc->sc_deferred--;
1777 		}
1778 		mtx_leave(&sc->sc_deferrals_mtx);
1779 	} else
1780 		*ppd = NULL;
1781 
1782 	m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
1783 	SET(st->state_flags, PFSTATE_ACK);
1784 
1785 	pd->pd_st = pf_state_ref(st);
1786 	pd->pd_m = m;
1787 
1788 	pd->pd_deadline = getnsecuptime() + PFSYNC_DEFER_NSEC;
1789 
1790 	mtx_enter(&sc->sc_deferrals_mtx);
1791 	sched = TAILQ_EMPTY(&sc->sc_deferrals);
1792 
1793 	TAILQ_INSERT_TAIL(&sc->sc_deferrals, pd, pd_entry);
1794 	sc->sc_deferred++;
1795 	mtx_leave(&sc->sc_deferrals_mtx);
1796 
1797 	if (sched)
1798 		timeout_add_nsec(&sc->sc_deferrals_tmo, PFSYNC_DEFER_NSEC);
1799 
1800 	schednetisr(NETISR_PFSYNC);
1801 
1802 	return (1);
1803 }
1804 
1805 void
1806 pfsync_undefer_notify(struct pfsync_deferral *pd)
1807 {
1808 	struct pf_pdesc pdesc;
1809 	struct pf_state *st = pd->pd_st;
1810 
1811 	/*
1812 	 * pf_remove_state removes the state keys and sets st->timeout
1813 	 * to PFTM_UNLINKED. this is done under NET_LOCK which should
1814 	 * be held here, so we can use PFTM_UNLINKED as a test for
1815 	 * whether the state keys are set for the address family
1816 	 * lookup.
1817 	 */
1818 
1819 	if (st->timeout == PFTM_UNLINKED)
1820 		return;
1821 
1822 	if (st->rt == PF_ROUTETO) {
1823 		if (pf_setup_pdesc(&pdesc, st->key[PF_SK_WIRE]->af,
1824 		    st->direction, st->kif, pd->pd_m, NULL) != PF_PASS)
1825 			return;
1826 		switch (st->key[PF_SK_WIRE]->af) {
1827 		case AF_INET:
1828 			pf_route(&pdesc, st);
1829 			break;
1830 #ifdef INET6
1831 		case AF_INET6:
1832 			pf_route6(&pdesc, st);
1833 			break;
1834 #endif /* INET6 */
1835 		default:
1836 			unhandled_af(st->key[PF_SK_WIRE]->af);
1837 		}
1838 		pd->pd_m = pdesc.m;
1839 	} else {
1840 		switch (st->key[PF_SK_WIRE]->af) {
1841 		case AF_INET:
1842 			ip_output(pd->pd_m, NULL, NULL, 0, NULL, NULL, 0);
1843 			break;
1844 #ifdef INET6
1845 		case AF_INET6:
1846 			ip6_output(pd->pd_m, NULL, NULL, 0, NULL, NULL);
1847 			break;
1848 #endif /* INET6 */
1849 		default:
1850 			unhandled_af(st->key[PF_SK_WIRE]->af);
1851 		}
1852 
1853 		pd->pd_m = NULL;
1854 	}
1855 }
1856 
1857 void
1858 pfsync_free_deferral(struct pfsync_deferral *pd)
1859 {
1860 	struct pfsync_softc *sc = pfsyncif;
1861 
1862 	pf_state_unref(pd->pd_st);
1863 	m_freem(pd->pd_m);
1864 	pool_put(&sc->sc_pool, pd);
1865 }
1866 
1867 void
1868 pfsync_undefer(struct pfsync_deferral *pd, int drop)
1869 {
1870 	struct pfsync_softc *sc = pfsyncif;
1871 
1872 	NET_ASSERT_LOCKED();
1873 
1874 	if (sc == NULL)
1875 		return;
1876 
1877 	CLR(pd->pd_st->state_flags, PFSTATE_ACK);
1878 	if (!drop)
1879 		pfsync_undefer_notify(pd);
1880 
1881 	pfsync_free_deferral(pd);
1882 }
1883 
1884 void
1885 pfsync_deferrals_tmo(void *arg)
1886 {
1887 	struct pfsync_softc *sc = arg;
1888 	struct pfsync_deferral *pd;
1889 	uint64_t now, nsec = 0;
1890 	struct pfsync_deferrals pds = TAILQ_HEAD_INITIALIZER(pds);
1891 
1892 	now = getnsecuptime();
1893 
1894 	mtx_enter(&sc->sc_deferrals_mtx);
1895 	for (;;) {
1896 		pd = TAILQ_FIRST(&sc->sc_deferrals);
1897 		if (pd == NULL)
1898 			break;
1899 
1900 		if (now < pd->pd_deadline) {
1901 			nsec = pd->pd_deadline - now;
1902 			break;
1903 		}
1904 
1905 		TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
1906 		sc->sc_deferred--;
1907 		TAILQ_INSERT_TAIL(&pds, pd, pd_entry);
1908 	}
1909 	mtx_leave(&sc->sc_deferrals_mtx);
1910 
1911 	if (nsec > 0) {
1912 		/* we were looking at a pd, but it wasn't old enough */
1913 		timeout_add_nsec(&sc->sc_deferrals_tmo, nsec);
1914 	}
1915 
1916 	if (TAILQ_EMPTY(&pds))
1917 		return;
1918 
1919 	NET_LOCK();
1920 	while ((pd = TAILQ_FIRST(&pds)) != NULL) {
1921 		TAILQ_REMOVE(&pds, pd, pd_entry);
1922 
1923 		pfsync_undefer(pd, 0);
1924 	}
1925 	NET_UNLOCK();
1926 }
1927 
1928 void
1929 pfsync_deferred(struct pf_state *st, int drop)
1930 {
1931 	struct pfsync_softc *sc = pfsyncif;
1932 	struct pfsync_deferral *pd;
1933 
1934 	NET_ASSERT_LOCKED();
1935 
1936 	mtx_enter(&sc->sc_deferrals_mtx);
1937 	TAILQ_FOREACH(pd, &sc->sc_deferrals, pd_entry) {
1938 		 if (pd->pd_st == st) {
1939 			TAILQ_REMOVE(&sc->sc_deferrals, pd, pd_entry);
1940 			sc->sc_deferred--;
1941 			break;
1942 		}
1943 	}
1944 	mtx_leave(&sc->sc_deferrals_mtx);
1945 
1946 	if (pd != NULL)
1947 		pfsync_undefer(pd, drop);
1948 }
1949 
1950 void
1951 pfsync_update_state(struct pf_state *st)
1952 {
1953 	struct pfsync_softc *sc = pfsyncif;
1954 	int sync = 0;
1955 
1956 	NET_ASSERT_LOCKED();
1957 
1958 	if (sc == NULL || !ISSET(sc->sc_if.if_flags, IFF_RUNNING))
1959 		return;
1960 
1961 	if (ISSET(st->state_flags, PFSTATE_ACK))
1962 		pfsync_deferred(st, 0);
1963 	if (ISSET(st->state_flags, PFSTATE_NOSYNC)) {
1964 		if (st->sync_state != PFSYNC_S_NONE)
1965 			pfsync_q_del(st);
1966 		return;
1967 	}
1968 
1969 	if (sc->sc_len == PFSYNC_MINPKT)
1970 		timeout_add_sec(&sc->sc_tmo, 1);
1971 
1972 	switch (st->sync_state) {
1973 	case PFSYNC_S_UPD_C:
1974 	case PFSYNC_S_UPD:
1975 	case PFSYNC_S_INS:
1976 		/* we're already handling it */
1977 
1978 		if (st->key[PF_SK_WIRE]->proto == IPPROTO_TCP) {
1979 			st->sync_updates++;
1980 			if (st->sync_updates >= sc->sc_maxupdates)
1981 				sync = 1;
1982 		}
1983 		break;
1984 
1985 	case PFSYNC_S_IACK:
1986 		pfsync_q_del(st);
1987 	case PFSYNC_S_NONE:
1988 		pfsync_q_ins(st, PFSYNC_S_UPD_C);
1989 		st->sync_updates = 0;
1990 		break;
1991 
1992 	default:
1993 		panic("pfsync_update_state: unexpected sync state %d",
1994 		    st->sync_state);
1995 	}
1996 
1997 	if (sync || (getuptime() - st->pfsync_time) < 2)
1998 		schednetisr(NETISR_PFSYNC);
1999 }
2000 
2001 void
2002 pfsync_cancel_full_update(struct pfsync_softc *sc)
2003 {
2004 	if (timeout_pending(&sc->sc_bulkfail_tmo) ||
2005 	    timeout_pending(&sc->sc_bulk_tmo)) {
2006 #if NCARP > 0
2007 		if (!pfsync_sync_ok)
2008 			carp_group_demote_adj(&sc->sc_if, -1,
2009 			    "pfsync bulk cancelled");
2010 		if (sc->sc_initial_bulk) {
2011 			carp_group_demote_adj(&sc->sc_if, -32,
2012 			    "pfsync init");
2013 			sc->sc_initial_bulk = 0;
2014 		}
2015 #endif
2016 		pfsync_sync_ok = 1;
2017 		DPFPRINTF(LOG_INFO, "cancelling bulk update");
2018 	}
2019 	timeout_del(&sc->sc_bulkfail_tmo);
2020 	timeout_del(&sc->sc_bulk_tmo);
2021 	sc->sc_bulk_next = NULL;
2022 	sc->sc_bulk_last = NULL;
2023 	sc->sc_ureq_sent = 0;
2024 	sc->sc_bulk_tries = 0;
2025 }
2026 
2027 void
2028 pfsync_request_full_update(struct pfsync_softc *sc)
2029 {
2030 	if (sc->sc_sync_ifidx != 0 && ISSET(sc->sc_if.if_flags, IFF_RUNNING)) {
2031 		/* Request a full state table update. */
2032 		sc->sc_ureq_sent = getuptime();
2033 #if NCARP > 0
2034 		if (!sc->sc_link_demoted && pfsync_sync_ok)
2035 			carp_group_demote_adj(&sc->sc_if, 1,
2036 			    "pfsync bulk start");
2037 #endif
2038 		pfsync_sync_ok = 0;
2039 		DPFPRINTF(LOG_INFO, "requesting bulk update");
2040 		timeout_add(&sc->sc_bulkfail_tmo, 4 * hz +
2041 		    pf_pool_limits[PF_LIMIT_STATES].limit /
2042 		    ((sc->sc_if.if_mtu - PFSYNC_MINPKT) /
2043 		    sizeof(struct pfsync_state)));
2044 		pfsync_request_update(0, 0);
2045 	}
2046 }
2047 
2048 void
2049 pfsync_request_update(u_int32_t creatorid, u_int64_t id)
2050 {
2051 	struct pfsync_softc *sc = pfsyncif;
2052 	struct pfsync_upd_req_item *item;
2053 	size_t nlen, sclen;
2054 	int retry;
2055 
2056 	/*
2057 	 * this code does nothing to prevent multiple update requests for the
2058 	 * same state being generated.
2059 	 */
2060 
2061 	item = pool_get(&sc->sc_pool, PR_NOWAIT);
2062 	if (item == NULL) {
2063 		/* XXX stats */
2064 		return;
2065 	}
2066 
2067 	item->ur_msg.id = id;
2068 	item->ur_msg.creatorid = creatorid;
2069 
2070 	for (;;) {
2071 		mtx_enter(&sc->sc_upd_req_mtx);
2072 
2073 		nlen = sizeof(struct pfsync_upd_req);
2074 		if (TAILQ_EMPTY(&sc->sc_upd_req_list))
2075 			nlen += sizeof(struct pfsync_subheader);
2076 
2077 		sclen = atomic_add_long_nv(&sc->sc_len, nlen);
2078 		retry = (sclen > sc->sc_if.if_mtu);
2079 		if (retry)
2080 			atomic_sub_long(&sc->sc_len, nlen);
2081 		else
2082 			TAILQ_INSERT_TAIL(&sc->sc_upd_req_list, item, ur_entry);
2083 
2084 		mtx_leave(&sc->sc_upd_req_mtx);
2085 
2086 		if (!retry)
2087 			break;
2088 
2089 		pfsync_sendout();
2090 	}
2091 
2092 	schednetisr(NETISR_PFSYNC);
2093 }
2094 
2095 void
2096 pfsync_update_state_req(struct pf_state *st)
2097 {
2098 	struct pfsync_softc *sc = pfsyncif;
2099 
2100 	if (sc == NULL)
2101 		panic("pfsync_update_state_req: nonexistent instance");
2102 
2103 	if (ISSET(st->state_flags, PFSTATE_NOSYNC)) {
2104 		if (st->sync_state != PFSYNC_S_NONE)
2105 			pfsync_q_del(st);
2106 		return;
2107 	}
2108 
2109 	switch (st->sync_state) {
2110 	case PFSYNC_S_UPD_C:
2111 	case PFSYNC_S_IACK:
2112 		pfsync_q_del(st);
2113 	case PFSYNC_S_NONE:
2114 		pfsync_q_ins(st, PFSYNC_S_UPD);
2115 		schednetisr(NETISR_PFSYNC);
2116 		return;
2117 
2118 	case PFSYNC_S_INS:
2119 	case PFSYNC_S_UPD:
2120 	case PFSYNC_S_DEL:
2121 		/* we're already handling it */
2122 		return;
2123 
2124 	default:
2125 		panic("pfsync_update_state_req: unexpected sync state %d",
2126 		    st->sync_state);
2127 	}
2128 }
2129 
2130 void
2131 pfsync_delete_state(struct pf_state *st)
2132 {
2133 	struct pfsync_softc *sc = pfsyncif;
2134 
2135 	NET_ASSERT_LOCKED();
2136 
2137 	if (sc == NULL || !ISSET(sc->sc_if.if_flags, IFF_RUNNING))
2138 		return;
2139 
2140 	if (ISSET(st->state_flags, PFSTATE_ACK))
2141 		pfsync_deferred(st, 1);
2142 	if (ISSET(st->state_flags, PFSTATE_NOSYNC)) {
2143 		if (st->sync_state != PFSYNC_S_NONE)
2144 			pfsync_q_del(st);
2145 		return;
2146 	}
2147 
2148 	if (sc->sc_len == PFSYNC_MINPKT)
2149 		timeout_add_sec(&sc->sc_tmo, 1);
2150 
2151 	switch (st->sync_state) {
2152 	case PFSYNC_S_INS:
2153 		/* we never got to tell the world so just forget about it */
2154 		pfsync_q_del(st);
2155 		return;
2156 
2157 	case PFSYNC_S_UPD_C:
2158 	case PFSYNC_S_UPD:
2159 	case PFSYNC_S_IACK:
2160 		pfsync_q_del(st);
2161 		/*
2162 		 * FALLTHROUGH to putting it on the del list
2163 		 * Note on reference count bookkeeping:
2164 		 *	pfsync_q_del() drops reference for queue
2165 		 *	ownership. But the st entry survives, because
2166 		 *	our caller still holds a reference.
2167 		 */
2168 
2169 	case PFSYNC_S_NONE:
2170 		/*
2171 		 * We either fall through here, or there is no reference to
2172 		 * st owned by pfsync queues at this point.
2173 		 *
2174 		 * Calling pfsync_q_ins() puts st to del queue. The pfsync_q_ins()
2175 		 * grabs a reference for delete queue.
2176 		 */
2177 		pfsync_q_ins(st, PFSYNC_S_DEL);
2178 		return;
2179 
2180 	default:
2181 		panic("pfsync_delete_state: unexpected sync state %d",
2182 		    st->sync_state);
2183 	}
2184 }
2185 
2186 void
2187 pfsync_clear_states(u_int32_t creatorid, const char *ifname)
2188 {
2189 	struct pfsync_softc *sc = pfsyncif;
2190 	struct {
2191 		struct pfsync_subheader subh;
2192 		struct pfsync_clr clr;
2193 	} __packed r;
2194 
2195 	NET_ASSERT_LOCKED();
2196 
2197 	if (sc == NULL || !ISSET(sc->sc_if.if_flags, IFF_RUNNING))
2198 		return;
2199 
2200 	bzero(&r, sizeof(r));
2201 
2202 	r.subh.action = PFSYNC_ACT_CLR;
2203 	r.subh.len = sizeof(struct pfsync_clr) >> 2;
2204 	r.subh.count = htons(1);
2205 
2206 	strlcpy(r.clr.ifname, ifname, sizeof(r.clr.ifname));
2207 	r.clr.creatorid = creatorid;
2208 
2209 	pfsync_send_plus(&r, sizeof(r));
2210 }
2211 
2212 void
2213 pfsync_iack(struct pf_state *st)
2214 {
2215 	pfsync_q_ins(st, PFSYNC_S_IACK);
2216 	schednetisr(NETISR_PFSYNC);
2217 }
2218 
2219 void
2220 pfsync_q_ins(struct pf_state *st, int q)
2221 {
2222 	struct pfsync_softc *sc = pfsyncif;
2223 	size_t nlen, sclen;
2224 
2225 	if (sc->sc_len < PFSYNC_MINPKT)
2226 		panic("pfsync pkt len is too low %zd", sc->sc_len);
2227 	do {
2228 		mtx_enter(&sc->sc_st_mtx);
2229 		mtx_enter(&st->mtx);
2230 
2231 		/*
2232 		 * There are either two threads trying to update the
2233 		 * the same state, or the state is just being processed
2234 		 * (is on snapshot queue).
2235 		 */
2236 		if (st->sync_state != PFSYNC_S_NONE) {
2237 			mtx_leave(&st->mtx);
2238 			mtx_leave(&sc->sc_st_mtx);
2239 			break;
2240 		}
2241 
2242 		nlen = pfsync_qs[q].len;
2243 
2244 		if (TAILQ_EMPTY(&sc->sc_qs[q]))
2245 			nlen += sizeof(struct pfsync_subheader);
2246 
2247 		sclen = atomic_add_long_nv(&sc->sc_len, nlen);
2248 		if (sclen > sc->sc_if.if_mtu) {
2249 			atomic_sub_long(&sc->sc_len, nlen);
2250 			mtx_leave(&st->mtx);
2251 			mtx_leave(&sc->sc_st_mtx);
2252 			pfsync_sendout();
2253 			continue;
2254 		}
2255 
2256 		pf_state_ref(st);
2257 
2258 		TAILQ_INSERT_TAIL(&sc->sc_qs[q], st, sync_list);
2259 		st->sync_state = q;
2260 		mtx_leave(&st->mtx);
2261 		mtx_leave(&sc->sc_st_mtx);
2262 	} while (0);
2263 }
2264 
2265 void
2266 pfsync_q_del(struct pf_state *st)
2267 {
2268 	struct pfsync_softc *sc = pfsyncif;
2269 	int q;
2270 
2271 	mtx_enter(&sc->sc_st_mtx);
2272 	mtx_enter(&st->mtx);
2273 	q = st->sync_state;
2274 	/*
2275 	 * re-check under mutex
2276 	 * if state is snapped already, then just bail out, because we came
2277 	 * too late, the state is being just processed/dispatched to peer.
2278 	 */
2279 	if ((q == PFSYNC_S_NONE) || (st->snapped)) {
2280 		mtx_leave(&st->mtx);
2281 		mtx_leave(&sc->sc_st_mtx);
2282 		return;
2283 	}
2284 	atomic_sub_long(&sc->sc_len, pfsync_qs[q].len);
2285 	TAILQ_REMOVE(&sc->sc_qs[q], st, sync_list);
2286 	if (TAILQ_EMPTY(&sc->sc_qs[q]))
2287 		atomic_sub_long(&sc->sc_len, sizeof (struct pfsync_subheader));
2288 	st->sync_state = PFSYNC_S_NONE;
2289 	mtx_leave(&st->mtx);
2290 	mtx_leave(&sc->sc_st_mtx);
2291 
2292 	pf_state_unref(st);
2293 }
2294 
2295 #if defined(IPSEC)
2296 void
2297 pfsync_update_tdb(struct tdb *t, int output)
2298 {
2299 	struct pfsync_softc *sc = pfsyncif;
2300 	size_t nlen, sclen;
2301 
2302 	if (sc == NULL)
2303 		return;
2304 
2305 	if (!ISSET(t->tdb_flags, TDBF_PFSYNC)) {
2306 		do {
2307 			mtx_enter(&sc->sc_tdb_mtx);
2308 			nlen = sizeof(struct pfsync_tdb);
2309 
2310 			mtx_enter(&t->tdb_mtx);
2311 			if (ISSET(t->tdb_flags, TDBF_PFSYNC)) {
2312 				/* we've lost race, no action for us then */
2313 				mtx_leave(&t->tdb_mtx);
2314 				mtx_leave(&sc->sc_tdb_mtx);
2315 				break;
2316 			}
2317 
2318 			if (TAILQ_EMPTY(&sc->sc_tdb_q))
2319 				nlen += sizeof(struct pfsync_subheader);
2320 
2321 			sclen = atomic_add_long_nv(&sc->sc_len, nlen);
2322 			if (sclen > sc->sc_if.if_mtu) {
2323 				atomic_sub_long(&sc->sc_len, nlen);
2324 				mtx_leave(&t->tdb_mtx);
2325 				mtx_leave(&sc->sc_tdb_mtx);
2326 				pfsync_sendout();
2327 				continue;
2328 			}
2329 
2330 			TAILQ_INSERT_TAIL(&sc->sc_tdb_q, t, tdb_sync_entry);
2331 			tdb_ref(t);
2332 			SET(t->tdb_flags, TDBF_PFSYNC);
2333 			mtx_leave(&t->tdb_mtx);
2334 
2335 			mtx_leave(&sc->sc_tdb_mtx);
2336 			t->tdb_updates = 0;
2337 		} while (0);
2338 	} else {
2339 		if (++t->tdb_updates >= sc->sc_maxupdates)
2340 			schednetisr(NETISR_PFSYNC);
2341 	}
2342 
2343 	mtx_enter(&t->tdb_mtx);
2344 	if (output)
2345 		SET(t->tdb_flags, TDBF_PFSYNC_RPL);
2346 	else
2347 		CLR(t->tdb_flags, TDBF_PFSYNC_RPL);
2348 	mtx_leave(&t->tdb_mtx);
2349 }
2350 #endif
2351 
2352 #if defined(IPSEC)
2353 void
2354 pfsync_delete_tdb(struct tdb *t)
2355 {
2356 	struct pfsync_softc *sc = pfsyncif;
2357 	size_t nlen;
2358 
2359 	if (sc == NULL || !ISSET(t->tdb_flags, TDBF_PFSYNC))
2360 		return;
2361 
2362 	mtx_enter(&sc->sc_tdb_mtx);
2363 
2364 	/*
2365 	 * if tdb entry is just being processed (found in snapshot),
2366 	 * then it can not be deleted. we just came too late
2367 	 */
2368 	if (ISSET(t->tdb_flags, TDBF_PFSYNC_SNAPPED)) {
2369 		mtx_leave(&sc->sc_tdb_mtx);
2370 		return;
2371 	}
2372 
2373 	TAILQ_REMOVE(&sc->sc_tdb_q, t, tdb_sync_entry);
2374 
2375 	mtx_enter(&t->tdb_mtx);
2376 	CLR(t->tdb_flags, TDBF_PFSYNC);
2377 	mtx_leave(&t->tdb_mtx);
2378 
2379 	nlen = sizeof(struct pfsync_tdb);
2380 	if (TAILQ_EMPTY(&sc->sc_tdb_q))
2381 		nlen += sizeof(struct pfsync_subheader);
2382 	atomic_sub_long(&sc->sc_len, nlen);
2383 
2384 	mtx_leave(&sc->sc_tdb_mtx);
2385 
2386 	tdb_unref(t);
2387 }
2388 #endif
2389 
2390 void
2391 pfsync_out_tdb(struct tdb *t, void *buf)
2392 {
2393 	struct pfsync_tdb *ut = buf;
2394 
2395 	bzero(ut, sizeof(*ut));
2396 	ut->spi = t->tdb_spi;
2397 	bcopy(&t->tdb_dst, &ut->dst, sizeof(ut->dst));
2398 	/*
2399 	 * When a failover happens, the master's rpl is probably above
2400 	 * what we see here (we may be up to a second late), so
2401 	 * increase it a bit for outbound tdbs to manage most such
2402 	 * situations.
2403 	 *
2404 	 * For now, just add an offset that is likely to be larger
2405 	 * than the number of packets we can see in one second. The RFC
2406 	 * just says the next packet must have a higher seq value.
2407 	 *
2408 	 * XXX What is a good algorithm for this? We could use
2409 	 * a rate-determined increase, but to know it, we would have
2410 	 * to extend struct tdb.
2411 	 * XXX pt->rpl can wrap over MAXINT, but if so the real tdb
2412 	 * will soon be replaced anyway. For now, just don't handle
2413 	 * this edge case.
2414 	 */
2415 #define RPL_INCR 16384
2416 	ut->rpl = htobe64(t->tdb_rpl + (ISSET(t->tdb_flags, TDBF_PFSYNC_RPL) ?
2417 	    RPL_INCR : 0));
2418 	ut->cur_bytes = htobe64(t->tdb_cur_bytes);
2419 	ut->sproto = t->tdb_sproto;
2420 	ut->rdomain = htons(t->tdb_rdomain);
2421 }
2422 
2423 void
2424 pfsync_bulk_start(void)
2425 {
2426 	struct pfsync_softc *sc = pfsyncif;
2427 
2428 	NET_ASSERT_LOCKED();
2429 
2430 	/*
2431 	 * pf gc via pfsync_state_in_use reads sc_bulk_next and
2432 	 * sc_bulk_last while exclusively holding the pf_state_list
2433 	 * rwlock. make sure it can't race with us setting these
2434 	 * pointers. they basically act as hazards, and borrow the
2435 	 * lists state reference count.
2436 	 */
2437 	rw_enter_read(&pf_state_list.pfs_rwl);
2438 
2439 	/* get a consistent view of the list pointers */
2440 	mtx_enter(&pf_state_list.pfs_mtx);
2441 	if (sc->sc_bulk_next == NULL)
2442 		sc->sc_bulk_next = TAILQ_FIRST(&pf_state_list.pfs_list);
2443 
2444 	sc->sc_bulk_last = TAILQ_LAST(&pf_state_list.pfs_list, pf_state_queue);
2445 	mtx_leave(&pf_state_list.pfs_mtx);
2446 
2447 	rw_exit_read(&pf_state_list.pfs_rwl);
2448 
2449 	DPFPRINTF(LOG_INFO, "received bulk update request");
2450 
2451 	if (sc->sc_bulk_last == NULL)
2452 		pfsync_bulk_status(PFSYNC_BUS_END);
2453 	else {
2454 		sc->sc_ureq_received = getuptime();
2455 
2456 		pfsync_bulk_status(PFSYNC_BUS_START);
2457 		timeout_add(&sc->sc_bulk_tmo, 0);
2458 	}
2459 }
2460 
2461 void
2462 pfsync_bulk_update(void *arg)
2463 {
2464 	struct pfsync_softc *sc;
2465 	struct pf_state *st;
2466 	int i = 0;
2467 
2468 	NET_LOCK();
2469 	sc = pfsyncif;
2470 	if (sc == NULL)
2471 		goto out;
2472 
2473 	rw_enter_read(&pf_state_list.pfs_rwl);
2474 	st = sc->sc_bulk_next;
2475 	sc->sc_bulk_next = NULL;
2476 
2477 	if (st == NULL) {
2478 		rw_exit_read(&pf_state_list.pfs_rwl);
2479 		goto out;
2480 	}
2481 
2482 	for (;;) {
2483 		if (st->sync_state == PFSYNC_S_NONE &&
2484 		    st->timeout < PFTM_MAX &&
2485 		    st->pfsync_time <= sc->sc_ureq_received) {
2486 			pfsync_update_state_req(st);
2487 			i++;
2488 		}
2489 
2490 		st = TAILQ_NEXT(st, entry_list);
2491 		if ((st == NULL) || (st == sc->sc_bulk_last)) {
2492 			/* we're done */
2493 			sc->sc_bulk_last = NULL;
2494 			pfsync_bulk_status(PFSYNC_BUS_END);
2495 			break;
2496 		}
2497 
2498 		if (i > 1 && (sc->sc_if.if_mtu - sc->sc_len) <
2499 		    sizeof(struct pfsync_state)) {
2500 			/* we've filled a packet */
2501 			sc->sc_bulk_next = st;
2502 			timeout_add(&sc->sc_bulk_tmo, 1);
2503 			break;
2504 		}
2505 	}
2506 
2507 	rw_exit_read(&pf_state_list.pfs_rwl);
2508  out:
2509 	NET_UNLOCK();
2510 }
2511 
2512 void
2513 pfsync_bulk_status(u_int8_t status)
2514 {
2515 	struct {
2516 		struct pfsync_subheader subh;
2517 		struct pfsync_bus bus;
2518 	} __packed r;
2519 
2520 	struct pfsync_softc *sc = pfsyncif;
2521 
2522 	bzero(&r, sizeof(r));
2523 
2524 	r.subh.action = PFSYNC_ACT_BUS;
2525 	r.subh.len = sizeof(struct pfsync_bus) >> 2;
2526 	r.subh.count = htons(1);
2527 
2528 	r.bus.creatorid = pf_status.hostid;
2529 	r.bus.endtime = htonl(getuptime() - sc->sc_ureq_received);
2530 	r.bus.status = status;
2531 
2532 	pfsync_send_plus(&r, sizeof(r));
2533 }
2534 
2535 void
2536 pfsync_bulk_fail(void *arg)
2537 {
2538 	struct pfsync_softc *sc;
2539 
2540 	NET_LOCK();
2541 	sc = pfsyncif;
2542 	if (sc == NULL)
2543 		goto out;
2544 	if (sc->sc_bulk_tries++ < PFSYNC_MAX_BULKTRIES) {
2545 		/* Try again */
2546 		timeout_add_sec(&sc->sc_bulkfail_tmo, 5);
2547 		pfsync_request_update(0, 0);
2548 	} else {
2549 		/* Pretend like the transfer was ok */
2550 		sc->sc_ureq_sent = 0;
2551 		sc->sc_bulk_tries = 0;
2552 #if NCARP > 0
2553 		if (!pfsync_sync_ok)
2554 			carp_group_demote_adj(&sc->sc_if, -1,
2555 			    sc->sc_link_demoted ?
2556 			    "pfsync link state up" :
2557 			    "pfsync bulk fail");
2558 		if (sc->sc_initial_bulk) {
2559 			carp_group_demote_adj(&sc->sc_if, -32,
2560 			    "pfsync init");
2561 			sc->sc_initial_bulk = 0;
2562 		}
2563 #endif
2564 		pfsync_sync_ok = 1;
2565 		sc->sc_link_demoted = 0;
2566 		DPFPRINTF(LOG_ERR, "failed to receive bulk update");
2567 	}
2568  out:
2569 	NET_UNLOCK();
2570 }
2571 
2572 void
2573 pfsync_send_plus(void *plus, size_t pluslen)
2574 {
2575 	struct pfsync_softc *sc = pfsyncif;
2576 
2577 	if (sc->sc_len + pluslen > sc->sc_if.if_mtu)
2578 		pfsync_sendout();
2579 
2580 	sc->sc_plus = plus;
2581 	sc->sc_pluslen = pluslen;
2582 	atomic_add_long(&sc->sc_len, pluslen);
2583 
2584 	pfsync_sendout();
2585 }
2586 
2587 int
2588 pfsync_is_up(void)
2589 {
2590 	struct pfsync_softc *sc = pfsyncif;
2591 
2592 	if (sc == NULL || !ISSET(sc->sc_if.if_flags, IFF_RUNNING))
2593 		return (0);
2594 
2595 	return (1);
2596 }
2597 
2598 int
2599 pfsync_state_in_use(struct pf_state *st)
2600 {
2601 	struct pfsync_softc *sc = pfsyncif;
2602 
2603 	if (sc == NULL)
2604 		return (0);
2605 
2606 	rw_assert_wrlock(&pf_state_list.pfs_rwl);
2607 
2608 	if (st->sync_state != PFSYNC_S_NONE ||
2609 	    st == sc->sc_bulk_next ||
2610 	    st == sc->sc_bulk_last)
2611 		return (1);
2612 
2613 	return (0);
2614 }
2615 
2616 void
2617 pfsync_timeout(void *arg)
2618 {
2619 	NET_LOCK();
2620 	pfsync_sendout();
2621 	NET_UNLOCK();
2622 }
2623 
2624 /* this is a softnet/netisr handler */
2625 void
2626 pfsyncintr(void)
2627 {
2628 	pfsync_sendout();
2629 }
2630 
2631 int
2632 pfsync_sysctl_pfsyncstat(void *oldp, size_t *oldlenp, void *newp)
2633 {
2634 	struct pfsyncstats pfsyncstat;
2635 
2636 	CTASSERT(sizeof(pfsyncstat) == (pfsyncs_ncounters * sizeof(uint64_t)));
2637 	memset(&pfsyncstat, 0, sizeof pfsyncstat);
2638 	counters_read(pfsynccounters, (uint64_t *)&pfsyncstat,
2639 	    pfsyncs_ncounters);
2640 	return (sysctl_rdstruct(oldp, oldlenp, newp,
2641 	    &pfsyncstat, sizeof(pfsyncstat)));
2642 }
2643 
2644 int
2645 pfsync_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
2646     size_t newlen)
2647 {
2648 	/* All sysctl names at this level are terminal. */
2649 	if (namelen != 1)
2650 		return (ENOTDIR);
2651 
2652 	switch (name[0]) {
2653 	case PFSYNCCTL_STATS:
2654 		return (pfsync_sysctl_pfsyncstat(oldp, oldlenp, newp));
2655 	default:
2656 		return (ENOPROTOOPT);
2657 	}
2658 }
2659