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