ip_carp.c revision 278075
1/*-
2 * Copyright (c) 2002 Michael Shalayeff.
3 * Copyright (c) 2003 Ryan McBride.
4 * Copyright (c) 2011 Gleb Smirnoff <glebius@FreeBSD.org>
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#include <sys/cdefs.h>
30__FBSDID("$FreeBSD: stable/10/sys/netinet/ip_carp.c 278075 2015-02-02 11:42:35Z loos $");
31
32#include "opt_bpf.h"
33#include "opt_inet.h"
34#include "opt_inet6.h"
35
36#include <sys/param.h>
37#include <sys/systm.h>
38#include <sys/bus.h>
39#include <sys/jail.h>
40#include <sys/kernel.h>
41#include <sys/limits.h>
42#include <sys/malloc.h>
43#include <sys/mbuf.h>
44#include <sys/module.h>
45#include <sys/priv.h>
46#include <sys/proc.h>
47#include <sys/protosw.h>
48#include <sys/socket.h>
49#include <sys/sockio.h>
50#include <sys/sysctl.h>
51#include <sys/syslog.h>
52#include <sys/taskqueue.h>
53#include <sys/counter.h>
54
55#include <net/ethernet.h>
56#include <net/fddi.h>
57#include <net/if.h>
58#include <net/if_dl.h>
59#include <net/if_llatbl.h>
60#include <net/if_types.h>
61#include <net/iso88025.h>
62#include <net/route.h>
63#include <net/vnet.h>
64
65#if defined(INET) || defined(INET6)
66#include <netinet/in.h>
67#include <netinet/in_var.h>
68#include <netinet/ip_carp.h>
69#include <netinet/ip.h>
70#include <machine/in_cksum.h>
71#endif
72#ifdef INET
73#include <netinet/ip_var.h>
74#include <netinet/if_ether.h>
75#endif
76
77#ifdef INET6
78#include <netinet/icmp6.h>
79#include <netinet/ip6.h>
80#include <netinet6/ip6protosw.h>
81#include <netinet6/in6_var.h>
82#include <netinet6/ip6_var.h>
83#include <netinet6/scope6_var.h>
84#include <netinet6/nd6.h>
85#endif
86
87#include <crypto/sha1.h>
88
89static MALLOC_DEFINE(M_CARP, "CARP", "CARP addresses");
90
91struct carp_softc {
92	struct ifnet		*sc_carpdev;	/* Pointer to parent ifnet. */
93	struct ifaddr		**sc_ifas;	/* Our ifaddrs. */
94	struct sockaddr_dl	sc_addr;	/* Our link level address. */
95	struct callout		sc_ad_tmo;	/* Advertising timeout. */
96#ifdef INET
97	struct callout		sc_md_tmo;	/* Master down timeout. */
98#endif
99#ifdef INET6
100	struct callout 		sc_md6_tmo;	/* XXX: Master down timeout. */
101#endif
102	struct mtx		sc_mtx;
103
104	int			sc_vhid;
105	int			sc_advskew;
106	int			sc_advbase;
107
108	int			sc_naddrs;
109	int			sc_naddrs6;
110	int			sc_ifasiz;
111	enum { INIT = 0, BACKUP, MASTER }	sc_state;
112	int			sc_suppress;
113	int			sc_sendad_errors;
114#define	CARP_SENDAD_MAX_ERRORS	3
115	int			sc_sendad_success;
116#define	CARP_SENDAD_MIN_SUCCESS 3
117
118	int			sc_init_counter;
119	uint64_t		sc_counter;
120
121	/* authentication */
122#define	CARP_HMAC_PAD	64
123	unsigned char sc_key[CARP_KEY_LEN];
124	unsigned char sc_pad[CARP_HMAC_PAD];
125	SHA1_CTX sc_sha1;
126
127	TAILQ_ENTRY(carp_softc)	sc_list;	/* On the carp_if list. */
128	LIST_ENTRY(carp_softc)	sc_next;	/* On the global list. */
129};
130
131struct carp_if {
132#ifdef INET
133	int	cif_naddrs;
134#endif
135#ifdef INET6
136	int	cif_naddrs6;
137#endif
138	TAILQ_HEAD(, carp_softc) cif_vrs;
139#ifdef INET
140	struct ip_moptions 	 cif_imo;
141#endif
142#ifdef INET6
143	struct ip6_moptions 	 cif_im6o;
144#endif
145	struct ifnet	*cif_ifp;
146	struct mtx	cif_mtx;
147};
148
149#define	CARP_INET	0
150#define	CARP_INET6	1
151static int proto_reg[] = {-1, -1};
152
153/*
154 * Brief design of carp(4).
155 *
156 * Any carp-capable ifnet may have a list of carp softcs hanging off
157 * its ifp->if_carp pointer. Each softc represents one unique virtual
158 * host id, or vhid. The softc has a back pointer to the ifnet. All
159 * softcs are joined in a global list, which has quite limited use.
160 *
161 * Any interface address that takes part in CARP negotiation has a
162 * pointer to the softc of its vhid, ifa->ifa_carp. That could be either
163 * AF_INET or AF_INET6 address.
164 *
165 * Although, one can get the softc's backpointer to ifnet and traverse
166 * through its ifp->if_addrhead queue to find all interface addresses
167 * involved in CARP, we keep a growable array of ifaddr pointers. This
168 * allows us to avoid grabbing the IF_ADDR_LOCK() in many traversals that
169 * do calls into the network stack, thus avoiding LORs.
170 *
171 * Locking:
172 *
173 * Each softc has a lock sc_mtx. It is used to synchronise carp_input_c(),
174 * callout-driven events and ioctl()s.
175 *
176 * To traverse the list of softcs on an ifnet we use CIF_LOCK(), to
177 * traverse the global list we use the mutex carp_mtx.
178 *
179 * Known issues with locking:
180 *
181 * - There is no protection for races between two ioctl() requests,
182 *   neither SIOCSVH, nor SIOCAIFADDR & SIOCAIFADDR_IN6. I think that all
183 *   interface ioctl()s should be serialized right in net/if.c.
184 * - Sending ad, we put the pointer to the softc in an mtag, and no reference
185 *   counting is done on the softc.
186 * - On module unload we may race (?) with packet processing thread
187 *   dereferencing our function pointers.
188 */
189
190/* Accept incoming CARP packets. */
191static VNET_DEFINE(int, carp_allow) = 1;
192#define	V_carp_allow	VNET(carp_allow)
193
194/* Preempt slower nodes. */
195static VNET_DEFINE(int, carp_preempt) = 0;
196#define	V_carp_preempt	VNET(carp_preempt)
197
198/* Log level. */
199static VNET_DEFINE(int, carp_log) = 1;
200#define	V_carp_log	VNET(carp_log)
201
202/* Global advskew demotion. */
203static VNET_DEFINE(int, carp_demotion) = 0;
204#define	V_carp_demotion	VNET(carp_demotion)
205
206/* Send error demotion factor. */
207static VNET_DEFINE(int, carp_senderr_adj) = CARP_MAXSKEW;
208#define	V_carp_senderr_adj	VNET(carp_senderr_adj)
209
210/* Iface down demotion factor. */
211static VNET_DEFINE(int, carp_ifdown_adj) = CARP_MAXSKEW;
212#define	V_carp_ifdown_adj	VNET(carp_ifdown_adj)
213
214static int carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS);
215
216SYSCTL_NODE(_net_inet, IPPROTO_CARP,	carp,	CTLFLAG_RW, 0,	"CARP");
217SYSCTL_VNET_INT(_net_inet_carp, OID_AUTO, allow, CTLFLAG_RW,
218    &VNET_NAME(carp_allow), 0, "Accept incoming CARP packets");
219SYSCTL_VNET_INT(_net_inet_carp, OID_AUTO, preempt, CTLFLAG_RW,
220    &VNET_NAME(carp_preempt), 0, "High-priority backup preemption mode");
221SYSCTL_VNET_INT(_net_inet_carp, OID_AUTO, log, CTLFLAG_RW,
222    &VNET_NAME(carp_log), 0, "CARP log level");
223SYSCTL_VNET_PROC(_net_inet_carp, OID_AUTO, demotion, CTLTYPE_INT|CTLFLAG_RW,
224    0, 0, carp_demote_adj_sysctl, "I",
225    "Adjust demotion factor (skew of advskew)");
226SYSCTL_VNET_INT(_net_inet_carp, OID_AUTO, senderr_demotion_factor, CTLFLAG_RW,
227    &VNET_NAME(carp_senderr_adj), 0, "Send error demotion factor adjustment");
228SYSCTL_VNET_INT(_net_inet_carp, OID_AUTO, ifdown_demotion_factor, CTLFLAG_RW,
229    &VNET_NAME(carp_ifdown_adj), 0,
230    "Interface down demotion factor adjustment");
231
232VNET_PCPUSTAT_DEFINE(struct carpstats, carpstats);
233VNET_PCPUSTAT_SYSINIT(carpstats);
234VNET_PCPUSTAT_SYSUNINIT(carpstats);
235
236#define	CARPSTATS_ADD(name, val)	\
237    counter_u64_add(VNET(carpstats)[offsetof(struct carpstats, name) / \
238	sizeof(uint64_t)], (val))
239#define	CARPSTATS_INC(name)		CARPSTATS_ADD(name, 1)
240
241SYSCTL_VNET_PCPUSTAT(_net_inet_carp, OID_AUTO, stats, struct carpstats,
242    carpstats, "CARP statistics (struct carpstats, netinet/ip_carp.h)");
243
244#define	CARP_LOCK_INIT(sc)	mtx_init(&(sc)->sc_mtx, "carp_softc",   \
245	NULL, MTX_DEF)
246#define	CARP_LOCK_DESTROY(sc)	mtx_destroy(&(sc)->sc_mtx)
247#define	CARP_LOCK_ASSERT(sc)	mtx_assert(&(sc)->sc_mtx, MA_OWNED)
248#define	CARP_LOCK(sc)		mtx_lock(&(sc)->sc_mtx)
249#define	CARP_UNLOCK(sc)		mtx_unlock(&(sc)->sc_mtx)
250#define	CIF_LOCK_INIT(cif)	mtx_init(&(cif)->cif_mtx, "carp_if",   \
251	NULL, MTX_DEF)
252#define	CIF_LOCK_DESTROY(cif)	mtx_destroy(&(cif)->cif_mtx)
253#define	CIF_LOCK_ASSERT(cif)	mtx_assert(&(cif)->cif_mtx, MA_OWNED)
254#define	CIF_LOCK(cif)		mtx_lock(&(cif)->cif_mtx)
255#define	CIF_UNLOCK(cif)		mtx_unlock(&(cif)->cif_mtx)
256#define	CIF_FREE(cif)	do {				\
257		CIF_LOCK_ASSERT(cif);			\
258		if (TAILQ_EMPTY(&(cif)->cif_vrs))	\
259			carp_free_if(cif);		\
260		else					\
261			CIF_UNLOCK(cif);		\
262} while (0)
263
264#define	CARP_LOG(...)	do {				\
265	if (V_carp_log > 0)				\
266		log(LOG_INFO, "carp: " __VA_ARGS__);	\
267} while (0)
268
269#define	CARP_DEBUG(...)	do {				\
270	if (V_carp_log > 1)				\
271		log(LOG_DEBUG, __VA_ARGS__);		\
272} while (0)
273
274#define	IFNET_FOREACH_IFA(ifp, ifa)					\
275	IF_ADDR_LOCK_ASSERT(ifp);					\
276	TAILQ_FOREACH((ifa), &(ifp)->if_addrhead, ifa_link)		\
277		if ((ifa)->ifa_carp != NULL)
278
279#define	CARP_FOREACH_IFA(sc, ifa)					\
280	CARP_LOCK_ASSERT(sc);						\
281	for (int _i = 0;						\
282		_i < (sc)->sc_naddrs + (sc)->sc_naddrs6 &&		\
283		((ifa) = sc->sc_ifas[_i]) != NULL;			\
284		++_i)
285
286#define	IFNET_FOREACH_CARP(ifp, sc)					\
287	CIF_LOCK_ASSERT(ifp->if_carp);					\
288	TAILQ_FOREACH((sc), &(ifp)->if_carp->cif_vrs, sc_list)
289
290#define	DEMOTE_ADVSKEW(sc)					\
291    (((sc)->sc_advskew + V_carp_demotion > CARP_MAXSKEW) ?	\
292    CARP_MAXSKEW : ((sc)->sc_advskew + V_carp_demotion))
293
294static void	carp_input_c(struct mbuf *, struct carp_header *, sa_family_t);
295static struct carp_softc
296		*carp_alloc(struct ifnet *);
297static void	carp_detach_locked(struct ifaddr *);
298static void	carp_destroy(struct carp_softc *);
299static struct carp_if
300		*carp_alloc_if(struct ifnet *);
301static void	carp_free_if(struct carp_if *);
302static void	carp_set_state(struct carp_softc *, int);
303static void	carp_sc_state(struct carp_softc *);
304static void	carp_setrun(struct carp_softc *, sa_family_t);
305static void	carp_master_down(void *);
306static void	carp_master_down_locked(struct carp_softc *);
307static void	carp_send_ad(void *);
308static void	carp_send_ad_locked(struct carp_softc *);
309static void	carp_addroute(struct carp_softc *);
310static void	carp_ifa_addroute(struct ifaddr *);
311static void	carp_delroute(struct carp_softc *);
312static void	carp_ifa_delroute(struct ifaddr *);
313static void	carp_send_ad_all(void *, int);
314static void	carp_demote_adj(int, char *);
315
316static LIST_HEAD(, carp_softc) carp_list;
317static struct mtx carp_mtx;
318static struct task carp_sendall_task =
319    TASK_INITIALIZER(0, carp_send_ad_all, NULL);
320
321static void
322carp_hmac_prepare(struct carp_softc *sc)
323{
324	uint8_t version = CARP_VERSION, type = CARP_ADVERTISEMENT;
325	uint8_t vhid = sc->sc_vhid & 0xff;
326	struct ifaddr *ifa;
327	int i, found;
328#ifdef INET
329	struct in_addr last, cur, in;
330#endif
331#ifdef INET6
332	struct in6_addr last6, cur6, in6;
333#endif
334
335	CARP_LOCK_ASSERT(sc);
336
337	/* Compute ipad from key. */
338	bzero(sc->sc_pad, sizeof(sc->sc_pad));
339	bcopy(sc->sc_key, sc->sc_pad, sizeof(sc->sc_key));
340	for (i = 0; i < sizeof(sc->sc_pad); i++)
341		sc->sc_pad[i] ^= 0x36;
342
343	/* Precompute first part of inner hash. */
344	SHA1Init(&sc->sc_sha1);
345	SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad));
346	SHA1Update(&sc->sc_sha1, (void *)&version, sizeof(version));
347	SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type));
348	SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid));
349#ifdef INET
350	cur.s_addr = 0;
351	do {
352		found = 0;
353		last = cur;
354		cur.s_addr = 0xffffffff;
355		CARP_FOREACH_IFA(sc, ifa) {
356			in.s_addr = ifatoia(ifa)->ia_addr.sin_addr.s_addr;
357			if (ifa->ifa_addr->sa_family == AF_INET &&
358			    ntohl(in.s_addr) > ntohl(last.s_addr) &&
359			    ntohl(in.s_addr) < ntohl(cur.s_addr)) {
360				cur.s_addr = in.s_addr;
361				found++;
362			}
363		}
364		if (found)
365			SHA1Update(&sc->sc_sha1, (void *)&cur, sizeof(cur));
366	} while (found);
367#endif /* INET */
368#ifdef INET6
369	memset(&cur6, 0, sizeof(cur6));
370	do {
371		found = 0;
372		last6 = cur6;
373		memset(&cur6, 0xff, sizeof(cur6));
374		CARP_FOREACH_IFA(sc, ifa) {
375			in6 = ifatoia6(ifa)->ia_addr.sin6_addr;
376			if (IN6_IS_SCOPE_EMBED(&in6))
377				in6.s6_addr16[1] = 0;
378			if (ifa->ifa_addr->sa_family == AF_INET6 &&
379			    memcmp(&in6, &last6, sizeof(in6)) > 0 &&
380			    memcmp(&in6, &cur6, sizeof(in6)) < 0) {
381				cur6 = in6;
382				found++;
383			}
384		}
385		if (found)
386			SHA1Update(&sc->sc_sha1, (void *)&cur6, sizeof(cur6));
387	} while (found);
388#endif /* INET6 */
389
390	/* convert ipad to opad */
391	for (i = 0; i < sizeof(sc->sc_pad); i++)
392		sc->sc_pad[i] ^= 0x36 ^ 0x5c;
393}
394
395static void
396carp_hmac_generate(struct carp_softc *sc, uint32_t counter[2],
397    unsigned char md[20])
398{
399	SHA1_CTX sha1ctx;
400
401	CARP_LOCK_ASSERT(sc);
402
403	/* fetch first half of inner hash */
404	bcopy(&sc->sc_sha1, &sha1ctx, sizeof(sha1ctx));
405
406	SHA1Update(&sha1ctx, (void *)counter, sizeof(sc->sc_counter));
407	SHA1Final(md, &sha1ctx);
408
409	/* outer hash */
410	SHA1Init(&sha1ctx);
411	SHA1Update(&sha1ctx, sc->sc_pad, sizeof(sc->sc_pad));
412	SHA1Update(&sha1ctx, md, 20);
413	SHA1Final(md, &sha1ctx);
414}
415
416static int
417carp_hmac_verify(struct carp_softc *sc, uint32_t counter[2],
418    unsigned char md[20])
419{
420	unsigned char md2[20];
421
422	CARP_LOCK_ASSERT(sc);
423
424	carp_hmac_generate(sc, counter, md2);
425
426	return (bcmp(md, md2, sizeof(md2)));
427}
428
429/*
430 * process input packet.
431 * we have rearranged checks order compared to the rfc,
432 * but it seems more efficient this way or not possible otherwise.
433 */
434#ifdef INET
435void
436carp_input(struct mbuf *m, int hlen)
437{
438	struct ip *ip = mtod(m, struct ip *);
439	struct carp_header *ch;
440	int iplen, len;
441
442	CARPSTATS_INC(carps_ipackets);
443
444	if (!V_carp_allow) {
445		m_freem(m);
446		return;
447	}
448
449	/* verify that the IP TTL is 255.  */
450	if (ip->ip_ttl != CARP_DFLTTL) {
451		CARPSTATS_INC(carps_badttl);
452		CARP_DEBUG("%s: received ttl %d != 255 on %s\n", __func__,
453		    ip->ip_ttl,
454		    m->m_pkthdr.rcvif->if_xname);
455		m_freem(m);
456		return;
457	}
458
459	iplen = ip->ip_hl << 2;
460
461	if (m->m_pkthdr.len < iplen + sizeof(*ch)) {
462		CARPSTATS_INC(carps_badlen);
463		CARP_DEBUG("%s: received len %zd < sizeof(struct carp_header) "
464		    "on %s\n", __func__, m->m_len - sizeof(struct ip),
465		    m->m_pkthdr.rcvif->if_xname);
466		m_freem(m);
467		return;
468	}
469
470	if (iplen + sizeof(*ch) < m->m_len) {
471		if ((m = m_pullup(m, iplen + sizeof(*ch))) == NULL) {
472			CARPSTATS_INC(carps_hdrops);
473			CARP_DEBUG("%s: pullup failed\n", __func__);
474			return;
475		}
476		ip = mtod(m, struct ip *);
477	}
478	ch = (struct carp_header *)((char *)ip + iplen);
479
480	/*
481	 * verify that the received packet length is
482	 * equal to the CARP header
483	 */
484	len = iplen + sizeof(*ch);
485	if (len > m->m_pkthdr.len) {
486		CARPSTATS_INC(carps_badlen);
487		CARP_DEBUG("%s: packet too short %d on %s\n", __func__,
488		    m->m_pkthdr.len,
489		    m->m_pkthdr.rcvif->if_xname);
490		m_freem(m);
491		return;
492	}
493
494	if ((m = m_pullup(m, len)) == NULL) {
495		CARPSTATS_INC(carps_hdrops);
496		return;
497	}
498	ip = mtod(m, struct ip *);
499	ch = (struct carp_header *)((char *)ip + iplen);
500
501	/* verify the CARP checksum */
502	m->m_data += iplen;
503	if (in_cksum(m, len - iplen)) {
504		CARPSTATS_INC(carps_badsum);
505		CARP_DEBUG("%s: checksum failed on %s\n", __func__,
506		    m->m_pkthdr.rcvif->if_xname);
507		m_freem(m);
508		return;
509	}
510	m->m_data -= iplen;
511
512	carp_input_c(m, ch, AF_INET);
513}
514#endif
515
516#ifdef INET6
517int
518carp6_input(struct mbuf **mp, int *offp, int proto)
519{
520	struct mbuf *m = *mp;
521	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
522	struct carp_header *ch;
523	u_int len;
524
525	CARPSTATS_INC(carps_ipackets6);
526
527	if (!V_carp_allow) {
528		m_freem(m);
529		return (IPPROTO_DONE);
530	}
531
532	/* check if received on a valid carp interface */
533	if (m->m_pkthdr.rcvif->if_carp == NULL) {
534		CARPSTATS_INC(carps_badif);
535		CARP_DEBUG("%s: packet received on non-carp interface: %s\n",
536		    __func__, m->m_pkthdr.rcvif->if_xname);
537		m_freem(m);
538		return (IPPROTO_DONE);
539	}
540
541	/* verify that the IP TTL is 255 */
542	if (ip6->ip6_hlim != CARP_DFLTTL) {
543		CARPSTATS_INC(carps_badttl);
544		CARP_DEBUG("%s: received ttl %d != 255 on %s\n", __func__,
545		    ip6->ip6_hlim, m->m_pkthdr.rcvif->if_xname);
546		m_freem(m);
547		return (IPPROTO_DONE);
548	}
549
550	/* verify that we have a complete carp packet */
551	len = m->m_len;
552	IP6_EXTHDR_GET(ch, struct carp_header *, m, *offp, sizeof(*ch));
553	if (ch == NULL) {
554		CARPSTATS_INC(carps_badlen);
555		CARP_DEBUG("%s: packet size %u too small\n", __func__, len);
556		return (IPPROTO_DONE);
557	}
558
559
560	/* verify the CARP checksum */
561	m->m_data += *offp;
562	if (in_cksum(m, sizeof(*ch))) {
563		CARPSTATS_INC(carps_badsum);
564		CARP_DEBUG("%s: checksum failed, on %s\n", __func__,
565		    m->m_pkthdr.rcvif->if_xname);
566		m_freem(m);
567		return (IPPROTO_DONE);
568	}
569	m->m_data -= *offp;
570
571	carp_input_c(m, ch, AF_INET6);
572	return (IPPROTO_DONE);
573}
574#endif /* INET6 */
575
576static void
577carp_input_c(struct mbuf *m, struct carp_header *ch, sa_family_t af)
578{
579	struct ifnet *ifp = m->m_pkthdr.rcvif;
580	struct ifaddr *ifa;
581	struct carp_softc *sc;
582	uint64_t tmp_counter;
583	struct timeval sc_tv, ch_tv;
584
585	/* verify that the VHID is valid on the receiving interface */
586	IF_ADDR_RLOCK(ifp);
587	IFNET_FOREACH_IFA(ifp, ifa)
588		if (ifa->ifa_addr->sa_family == af &&
589		    ifa->ifa_carp->sc_vhid == ch->carp_vhid) {
590			ifa_ref(ifa);
591			break;
592		}
593	IF_ADDR_RUNLOCK(ifp);
594
595	if (ifa == NULL) {
596		CARPSTATS_INC(carps_badvhid);
597		m_freem(m);
598		return;
599	}
600
601	/* verify the CARP version. */
602	if (ch->carp_version != CARP_VERSION) {
603		CARPSTATS_INC(carps_badver);
604		CARP_DEBUG("%s: invalid version %d\n", ifp->if_xname,
605		    ch->carp_version);
606		ifa_free(ifa);
607		m_freem(m);
608		return;
609	}
610
611	sc = ifa->ifa_carp;
612	CARP_LOCK(sc);
613	ifa_free(ifa);
614
615	if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) {
616		CARPSTATS_INC(carps_badauth);
617		CARP_DEBUG("%s: incorrect hash for VHID %u@%s\n", __func__,
618		    sc->sc_vhid, ifp->if_xname);
619		goto out;
620	}
621
622	tmp_counter = ntohl(ch->carp_counter[0]);
623	tmp_counter = tmp_counter<<32;
624	tmp_counter += ntohl(ch->carp_counter[1]);
625
626	/* XXX Replay protection goes here */
627
628	sc->sc_init_counter = 0;
629	sc->sc_counter = tmp_counter;
630
631	sc_tv.tv_sec = sc->sc_advbase;
632	sc_tv.tv_usec = DEMOTE_ADVSKEW(sc) * 1000000 / 256;
633	ch_tv.tv_sec = ch->carp_advbase;
634	ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256;
635
636	switch (sc->sc_state) {
637	case INIT:
638		break;
639	case MASTER:
640		/*
641		 * If we receive an advertisement from a master who's going to
642		 * be more frequent than us, go into BACKUP state.
643		 */
644		if (timevalcmp(&sc_tv, &ch_tv, >) ||
645		    timevalcmp(&sc_tv, &ch_tv, ==)) {
646			callout_stop(&sc->sc_ad_tmo);
647			CARP_LOG("VHID %u@%s: MASTER -> BACKUP "
648			    "(more frequent advertisement received)\n",
649			    sc->sc_vhid,
650			    sc->sc_carpdev->if_xname);
651			carp_set_state(sc, BACKUP);
652			carp_setrun(sc, 0);
653			carp_delroute(sc);
654		}
655		break;
656	case BACKUP:
657		/*
658		 * If we're pre-empting masters who advertise slower than us,
659		 * and this one claims to be slower, treat him as down.
660		 */
661		if (V_carp_preempt && timevalcmp(&sc_tv, &ch_tv, <)) {
662			CARP_LOG("VHID %u@%s: BACKUP -> MASTER "
663			    "(preempting a slower master)\n",
664			    sc->sc_vhid,
665			    sc->sc_carpdev->if_xname);
666			carp_master_down_locked(sc);
667			break;
668		}
669
670		/*
671		 *  If the master is going to advertise at such a low frequency
672		 *  that he's guaranteed to time out, we'd might as well just
673		 *  treat him as timed out now.
674		 */
675		sc_tv.tv_sec = sc->sc_advbase * 3;
676		if (timevalcmp(&sc_tv, &ch_tv, <)) {
677			CARP_LOG("VHID %u@%s: BACKUP -> MASTER "
678			    "(master timed out)\n",
679			    sc->sc_vhid,
680			    sc->sc_carpdev->if_xname);
681			carp_master_down_locked(sc);
682			break;
683		}
684
685		/*
686		 * Otherwise, we reset the counter and wait for the next
687		 * advertisement.
688		 */
689		carp_setrun(sc, af);
690		break;
691	}
692
693out:
694	CARP_UNLOCK(sc);
695	m_freem(m);
696}
697
698static int
699carp_prepare_ad(struct mbuf *m, struct carp_softc *sc, struct carp_header *ch)
700{
701	struct m_tag *mtag;
702
703	if (sc->sc_init_counter) {
704		/* this could also be seconds since unix epoch */
705		sc->sc_counter = arc4random();
706		sc->sc_counter = sc->sc_counter << 32;
707		sc->sc_counter += arc4random();
708	} else
709		sc->sc_counter++;
710
711	ch->carp_counter[0] = htonl((sc->sc_counter>>32)&0xffffffff);
712	ch->carp_counter[1] = htonl(sc->sc_counter&0xffffffff);
713
714	carp_hmac_generate(sc, ch->carp_counter, ch->carp_md);
715
716	/* Tag packet for carp_output */
717	if ((mtag = m_tag_get(PACKET_TAG_CARP, sizeof(struct carp_softc *),
718	    M_NOWAIT)) == NULL) {
719		m_freem(m);
720		CARPSTATS_INC(carps_onomem);
721		return (ENOMEM);
722	}
723	bcopy(&sc, mtag + 1, sizeof(sc));
724	m_tag_prepend(m, mtag);
725
726	return (0);
727}
728
729/*
730 * To avoid LORs and possible recursions this function shouldn't
731 * be called directly, but scheduled via taskqueue.
732 */
733static void
734carp_send_ad_all(void *ctx __unused, int pending __unused)
735{
736	struct carp_softc *sc;
737
738	mtx_lock(&carp_mtx);
739	LIST_FOREACH(sc, &carp_list, sc_next)
740		if (sc->sc_state == MASTER) {
741			CARP_LOCK(sc);
742			CURVNET_SET(sc->sc_carpdev->if_vnet);
743			carp_send_ad_locked(sc);
744			CURVNET_RESTORE();
745			CARP_UNLOCK(sc);
746		}
747	mtx_unlock(&carp_mtx);
748}
749
750/* Send a periodic advertisement, executed in callout context. */
751static void
752carp_send_ad(void *v)
753{
754	struct carp_softc *sc = v;
755
756	CARP_LOCK_ASSERT(sc);
757	CURVNET_SET(sc->sc_carpdev->if_vnet);
758	carp_send_ad_locked(sc);
759	CURVNET_RESTORE();
760	CARP_UNLOCK(sc);
761}
762
763static void
764carp_send_ad_error(struct carp_softc *sc, int error)
765{
766
767	if (error) {
768		if (sc->sc_sendad_errors < INT_MAX)
769			sc->sc_sendad_errors++;
770		if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
771			static const char fmt[] = "send error %d on %s";
772			char msg[sizeof(fmt) + IFNAMSIZ];
773
774			sprintf(msg, fmt, error, sc->sc_carpdev->if_xname);
775			carp_demote_adj(V_carp_senderr_adj, msg);
776		}
777		sc->sc_sendad_success = 0;
778	} else {
779		if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS &&
780		    ++sc->sc_sendad_success >= CARP_SENDAD_MIN_SUCCESS) {
781			static const char fmt[] = "send ok on %s";
782			char msg[sizeof(fmt) + IFNAMSIZ];
783
784			sprintf(msg, fmt, sc->sc_carpdev->if_xname);
785			carp_demote_adj(-V_carp_senderr_adj, msg);
786			sc->sc_sendad_errors = 0;
787		} else
788			sc->sc_sendad_errors = 0;
789	}
790}
791
792static void
793carp_send_ad_locked(struct carp_softc *sc)
794{
795	struct carp_header ch;
796	struct timeval tv;
797	struct sockaddr sa;
798	struct ifaddr *ifa;
799	struct carp_header *ch_ptr;
800	struct mbuf *m;
801	int len, advskew;
802
803	CARP_LOCK_ASSERT(sc);
804
805	advskew = DEMOTE_ADVSKEW(sc);
806	tv.tv_sec = sc->sc_advbase;
807	tv.tv_usec = advskew * 1000000 / 256;
808
809	ch.carp_version = CARP_VERSION;
810	ch.carp_type = CARP_ADVERTISEMENT;
811	ch.carp_vhid = sc->sc_vhid;
812	ch.carp_advbase = sc->sc_advbase;
813	ch.carp_advskew = advskew;
814	ch.carp_authlen = 7;	/* XXX DEFINE */
815	ch.carp_pad1 = 0;	/* must be zero */
816	ch.carp_cksum = 0;
817
818	/* XXXGL: OpenBSD picks first ifaddr with needed family. */
819
820#ifdef INET
821	if (sc->sc_naddrs) {
822		struct ip *ip;
823
824		m = m_gethdr(M_NOWAIT, MT_DATA);
825		if (m == NULL) {
826			CARPSTATS_INC(carps_onomem);
827			goto resched;
828		}
829		len = sizeof(*ip) + sizeof(ch);
830		m->m_pkthdr.len = len;
831		m->m_pkthdr.rcvif = NULL;
832		m->m_len = len;
833		MH_ALIGN(m, m->m_len);
834		m->m_flags |= M_MCAST;
835		ip = mtod(m, struct ip *);
836		ip->ip_v = IPVERSION;
837		ip->ip_hl = sizeof(*ip) >> 2;
838		ip->ip_tos = IPTOS_LOWDELAY;
839		ip->ip_len = htons(len);
840		ip->ip_id = ip_newid();
841		ip->ip_off = htons(IP_DF);
842		ip->ip_ttl = CARP_DFLTTL;
843		ip->ip_p = IPPROTO_CARP;
844		ip->ip_sum = 0;
845
846		bzero(&sa, sizeof(sa));
847		sa.sa_family = AF_INET;
848		ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
849		if (ifa != NULL) {
850			ip->ip_src.s_addr =
851			    ifatoia(ifa)->ia_addr.sin_addr.s_addr;
852			ifa_free(ifa);
853		} else
854			ip->ip_src.s_addr = 0;
855		ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP);
856
857		ch_ptr = (struct carp_header *)(&ip[1]);
858		bcopy(&ch, ch_ptr, sizeof(ch));
859		if (carp_prepare_ad(m, sc, ch_ptr))
860			goto resched;
861
862		m->m_data += sizeof(*ip);
863		ch_ptr->carp_cksum = in_cksum(m, len - sizeof(*ip));
864		m->m_data -= sizeof(*ip);
865
866		CARPSTATS_INC(carps_opackets);
867
868		carp_send_ad_error(sc, ip_output(m, NULL, NULL, IP_RAWOUTPUT,
869		    &sc->sc_carpdev->if_carp->cif_imo, NULL));
870	}
871#endif /* INET */
872#ifdef INET6
873	if (sc->sc_naddrs6) {
874		struct ip6_hdr *ip6;
875
876		m = m_gethdr(M_NOWAIT, MT_DATA);
877		if (m == NULL) {
878			CARPSTATS_INC(carps_onomem);
879			goto resched;
880		}
881		len = sizeof(*ip6) + sizeof(ch);
882		m->m_pkthdr.len = len;
883		m->m_pkthdr.rcvif = NULL;
884		m->m_len = len;
885		MH_ALIGN(m, m->m_len);
886		m->m_flags |= M_MCAST;
887		ip6 = mtod(m, struct ip6_hdr *);
888		bzero(ip6, sizeof(*ip6));
889		ip6->ip6_vfc |= IPV6_VERSION;
890		ip6->ip6_hlim = CARP_DFLTTL;
891		ip6->ip6_nxt = IPPROTO_CARP;
892		bzero(&sa, sizeof(sa));
893
894		/* set the source address */
895		sa.sa_family = AF_INET6;
896		ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
897		if (ifa != NULL) {
898			bcopy(IFA_IN6(ifa), &ip6->ip6_src,
899			    sizeof(struct in6_addr));
900			ifa_free(ifa);
901		} else
902			/* This should never happen with IPv6. */
903			bzero(&ip6->ip6_src, sizeof(struct in6_addr));
904
905		/* Set the multicast destination. */
906		ip6->ip6_dst.s6_addr16[0] = htons(0xff02);
907		ip6->ip6_dst.s6_addr8[15] = 0x12;
908		if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) {
909			m_freem(m);
910			CARP_DEBUG("%s: in6_setscope failed\n", __func__);
911			goto resched;
912		}
913
914		ch_ptr = (struct carp_header *)(&ip6[1]);
915		bcopy(&ch, ch_ptr, sizeof(ch));
916		if (carp_prepare_ad(m, sc, ch_ptr))
917			goto resched;
918
919		m->m_data += sizeof(*ip6);
920		ch_ptr->carp_cksum = in_cksum(m, len - sizeof(*ip6));
921		m->m_data -= sizeof(*ip6);
922
923		CARPSTATS_INC(carps_opackets6);
924
925		carp_send_ad_error(sc, ip6_output(m, NULL, NULL, 0,
926		    &sc->sc_carpdev->if_carp->cif_im6o, NULL, NULL));
927	}
928#endif /* INET6 */
929
930resched:
931	callout_reset(&sc->sc_ad_tmo, tvtohz(&tv), carp_send_ad, sc);
932}
933
934static void
935carp_addroute(struct carp_softc *sc)
936{
937	struct ifaddr *ifa;
938
939	CARP_FOREACH_IFA(sc, ifa)
940		carp_ifa_addroute(ifa);
941}
942
943static void
944carp_ifa_addroute(struct ifaddr *ifa)
945{
946
947	switch (ifa->ifa_addr->sa_family) {
948#ifdef INET
949	case AF_INET:
950		in_addprefix(ifatoia(ifa), RTF_UP);
951		ifa_add_loopback_route(ifa,
952		    (struct sockaddr *)&ifatoia(ifa)->ia_addr);
953		break;
954#endif
955#ifdef INET6
956	case AF_INET6:
957		ifa_add_loopback_route(ifa,
958		    (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
959		in6_ifaddloop(ifa);
960		break;
961#endif
962	}
963}
964
965static void
966carp_delroute(struct carp_softc *sc)
967{
968	struct ifaddr *ifa;
969
970	CARP_FOREACH_IFA(sc, ifa)
971		carp_ifa_delroute(ifa);
972}
973
974static void
975carp_ifa_delroute(struct ifaddr *ifa)
976{
977
978	switch (ifa->ifa_addr->sa_family) {
979#ifdef INET
980	case AF_INET:
981		ifa_del_loopback_route(ifa,
982		    (struct sockaddr *)&ifatoia(ifa)->ia_addr);
983		in_scrubprefix(ifatoia(ifa), LLE_STATIC);
984		break;
985#endif
986#ifdef INET6
987	case AF_INET6:
988		ifa_del_loopback_route(ifa,
989		    (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
990		in6_ifremloop(ifa);
991		break;
992#endif
993	}
994}
995
996int
997carp_master(struct ifaddr *ifa)
998{
999	struct carp_softc *sc = ifa->ifa_carp;
1000
1001	return (sc->sc_state == MASTER);
1002}
1003
1004#ifdef INET
1005/*
1006 * Broadcast a gratuitous ARP request containing
1007 * the virtual router MAC address for each IP address
1008 * associated with the virtual router.
1009 */
1010static void
1011carp_send_arp(struct carp_softc *sc)
1012{
1013	struct ifaddr *ifa;
1014
1015	CARP_FOREACH_IFA(sc, ifa)
1016		if (ifa->ifa_addr->sa_family == AF_INET)
1017			arp_ifinit2(sc->sc_carpdev, ifa, LLADDR(&sc->sc_addr));
1018}
1019
1020int
1021carp_iamatch(struct ifaddr *ifa, uint8_t **enaddr)
1022{
1023	struct carp_softc *sc = ifa->ifa_carp;
1024
1025	if (sc->sc_state == MASTER) {
1026		*enaddr = LLADDR(&sc->sc_addr);
1027		return (1);
1028	}
1029
1030	return (0);
1031}
1032#endif
1033
1034#ifdef INET6
1035static void
1036carp_send_na(struct carp_softc *sc)
1037{
1038	static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1039	struct ifaddr *ifa;
1040	struct in6_addr *in6;
1041
1042	CARP_FOREACH_IFA(sc, ifa) {
1043		if (ifa->ifa_addr->sa_family != AF_INET6)
1044			continue;
1045
1046		in6 = IFA_IN6(ifa);
1047		nd6_na_output(sc->sc_carpdev, &mcast, in6,
1048		    ND_NA_FLAG_OVERRIDE, 1, NULL);
1049		DELAY(1000);	/* XXX */
1050	}
1051}
1052
1053/*
1054 * Returns ifa in case it's a carp address and it is MASTER, or if the address
1055 * matches and is not a carp address.  Returns NULL otherwise.
1056 */
1057struct ifaddr *
1058carp_iamatch6(struct ifnet *ifp, struct in6_addr *taddr)
1059{
1060	struct ifaddr *ifa;
1061
1062	ifa = NULL;
1063	IF_ADDR_RLOCK(ifp);
1064	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1065		if (ifa->ifa_addr->sa_family != AF_INET6)
1066			continue;
1067		if (!IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa)))
1068			continue;
1069		if (ifa->ifa_carp && ifa->ifa_carp->sc_state != MASTER)
1070			ifa = NULL;
1071		else
1072			ifa_ref(ifa);
1073		break;
1074	}
1075	IF_ADDR_RUNLOCK(ifp);
1076
1077	return (ifa);
1078}
1079
1080caddr_t
1081carp_macmatch6(struct ifnet *ifp, struct mbuf *m, const struct in6_addr *taddr)
1082{
1083	struct ifaddr *ifa;
1084
1085	IF_ADDR_RLOCK(ifp);
1086	IFNET_FOREACH_IFA(ifp, ifa)
1087		if (ifa->ifa_addr->sa_family == AF_INET6 &&
1088		    IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa))) {
1089			struct carp_softc *sc = ifa->ifa_carp;
1090			struct m_tag *mtag;
1091
1092			IF_ADDR_RUNLOCK(ifp);
1093
1094			mtag = m_tag_get(PACKET_TAG_CARP,
1095			    sizeof(struct carp_softc *), M_NOWAIT);
1096			if (mtag == NULL)
1097				/* Better a bit than nothing. */
1098				return (LLADDR(&sc->sc_addr));
1099
1100			bcopy(&sc, mtag + 1, sizeof(sc));
1101			m_tag_prepend(m, mtag);
1102
1103			return (LLADDR(&sc->sc_addr));
1104		}
1105	IF_ADDR_RUNLOCK(ifp);
1106
1107	return (NULL);
1108}
1109#endif /* INET6 */
1110
1111int
1112carp_forus(struct ifnet *ifp, u_char *dhost)
1113{
1114	struct carp_softc *sc;
1115	uint8_t *ena = dhost;
1116
1117	if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1118		return (0);
1119
1120	CIF_LOCK(ifp->if_carp);
1121	IFNET_FOREACH_CARP(ifp, sc) {
1122		CARP_LOCK(sc);
1123		if (sc->sc_state == MASTER && !bcmp(dhost, LLADDR(&sc->sc_addr),
1124		    ETHER_ADDR_LEN)) {
1125			CARP_UNLOCK(sc);
1126			CIF_UNLOCK(ifp->if_carp);
1127			return (1);
1128		}
1129		CARP_UNLOCK(sc);
1130	}
1131	CIF_UNLOCK(ifp->if_carp);
1132
1133	return (0);
1134}
1135
1136/* Master down timeout event, executed in callout context. */
1137static void
1138carp_master_down(void *v)
1139{
1140	struct carp_softc *sc = v;
1141
1142	CARP_LOCK_ASSERT(sc);
1143
1144	CURVNET_SET(sc->sc_carpdev->if_vnet);
1145	if (sc->sc_state == BACKUP) {
1146		CARP_LOG("VHID %u@%s: BACKUP -> MASTER (master down)\n",
1147		    sc->sc_vhid,
1148		    sc->sc_carpdev->if_xname);
1149		carp_master_down_locked(sc);
1150	}
1151	CURVNET_RESTORE();
1152
1153	CARP_UNLOCK(sc);
1154}
1155
1156static void
1157carp_master_down_locked(struct carp_softc *sc)
1158{
1159
1160	CARP_LOCK_ASSERT(sc);
1161
1162	switch (sc->sc_state) {
1163	case BACKUP:
1164		carp_set_state(sc, MASTER);
1165		carp_send_ad_locked(sc);
1166#ifdef INET
1167		carp_send_arp(sc);
1168#endif
1169#ifdef INET6
1170		carp_send_na(sc);
1171#endif
1172		carp_setrun(sc, 0);
1173		carp_addroute(sc);
1174		break;
1175	case INIT:
1176	case MASTER:
1177#ifdef INVARIANTS
1178		panic("carp: VHID %u@%s: master_down event in %s state\n",
1179		    sc->sc_vhid,
1180		    sc->sc_carpdev->if_xname,
1181		    sc->sc_state ? "MASTER" : "INIT");
1182#endif
1183		break;
1184	}
1185}
1186
1187/*
1188 * When in backup state, af indicates whether to reset the master down timer
1189 * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1190 */
1191static void
1192carp_setrun(struct carp_softc *sc, sa_family_t af)
1193{
1194	struct timeval tv;
1195
1196	CARP_LOCK_ASSERT(sc);
1197
1198	if ((sc->sc_carpdev->if_flags & IFF_UP) == 0 ||
1199	    sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1200	    (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0))
1201		return;
1202
1203	switch (sc->sc_state) {
1204	case INIT:
1205		CARP_LOG("VHID %u@%s: INIT -> BACKUP\n",
1206		    sc->sc_vhid,
1207		    sc->sc_carpdev->if_xname);
1208		carp_set_state(sc, BACKUP);
1209		carp_setrun(sc, 0);
1210		break;
1211	case BACKUP:
1212		callout_stop(&sc->sc_ad_tmo);
1213		tv.tv_sec = 3 * sc->sc_advbase;
1214		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1215		switch (af) {
1216#ifdef INET
1217		case AF_INET:
1218			callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1219			    carp_master_down, sc);
1220			break;
1221#endif
1222#ifdef INET6
1223		case AF_INET6:
1224			callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1225			    carp_master_down, sc);
1226			break;
1227#endif
1228		default:
1229#ifdef INET
1230			if (sc->sc_naddrs)
1231				callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1232				    carp_master_down, sc);
1233#endif
1234#ifdef INET6
1235			if (sc->sc_naddrs6)
1236				callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1237				    carp_master_down, sc);
1238#endif
1239			break;
1240		}
1241		break;
1242	case MASTER:
1243		tv.tv_sec = sc->sc_advbase;
1244		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1245		callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1246		    carp_send_ad, sc);
1247		break;
1248	}
1249}
1250
1251/*
1252 * Setup multicast structures.
1253 */
1254static int
1255carp_multicast_setup(struct carp_if *cif, sa_family_t sa)
1256{
1257	struct ifnet *ifp = cif->cif_ifp;
1258	int error = 0;
1259
1260	CIF_LOCK_ASSERT(cif);
1261
1262	switch (sa) {
1263#ifdef INET
1264	case AF_INET:
1265	    {
1266		struct ip_moptions *imo = &cif->cif_imo;
1267		struct in_addr addr;
1268
1269		if (imo->imo_membership)
1270			return (0);
1271
1272		imo->imo_membership = (struct in_multi **)malloc(
1273		    (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_CARP,
1274		    M_NOWAIT);
1275		if (imo->imo_membership == NULL)
1276			return (ENOMEM);
1277		imo->imo_mfilters = NULL;
1278		imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1279		imo->imo_multicast_vif = -1;
1280
1281		addr.s_addr = htonl(INADDR_CARP_GROUP);
1282		if ((error = in_joingroup(ifp, &addr, NULL,
1283		    &imo->imo_membership[0])) != 0) {
1284			free(imo->imo_membership, M_CARP);
1285			break;
1286		}
1287		imo->imo_num_memberships++;
1288		imo->imo_multicast_ifp = ifp;
1289		imo->imo_multicast_ttl = CARP_DFLTTL;
1290		imo->imo_multicast_loop = 0;
1291		break;
1292	   }
1293#endif
1294#ifdef INET6
1295	case AF_INET6:
1296	    {
1297		struct ip6_moptions *im6o = &cif->cif_im6o;
1298		struct in6_addr in6;
1299		struct in6_multi *in6m;
1300
1301		if (im6o->im6o_membership)
1302			return (0);
1303
1304		im6o->im6o_membership = (struct in6_multi **)malloc(
1305		    (sizeof(struct in6_multi *) * IPV6_MIN_MEMBERSHIPS), M_CARP,
1306		    M_ZERO | M_NOWAIT);
1307		if (im6o->im6o_membership == NULL)
1308			return (ENOMEM);
1309		im6o->im6o_mfilters = NULL;
1310		im6o->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
1311		im6o->im6o_multicast_hlim = CARP_DFLTTL;
1312		im6o->im6o_multicast_ifp = ifp;
1313
1314		/* Join IPv6 CARP multicast group. */
1315		bzero(&in6, sizeof(in6));
1316		in6.s6_addr16[0] = htons(0xff02);
1317		in6.s6_addr8[15] = 0x12;
1318		if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1319			free(im6o->im6o_membership, M_CARP);
1320			break;
1321		}
1322		in6m = NULL;
1323		if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1324			free(im6o->im6o_membership, M_CARP);
1325			break;
1326		}
1327		im6o->im6o_membership[0] = in6m;
1328		im6o->im6o_num_memberships++;
1329
1330		/* Join solicited multicast address. */
1331		bzero(&in6, sizeof(in6));
1332		in6.s6_addr16[0] = htons(0xff02);
1333		in6.s6_addr32[1] = 0;
1334		in6.s6_addr32[2] = htonl(1);
1335		in6.s6_addr32[3] = 0;
1336		in6.s6_addr8[12] = 0xff;
1337		if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1338			in6_mc_leave(im6o->im6o_membership[0], NULL);
1339			free(im6o->im6o_membership, M_CARP);
1340			break;
1341		}
1342		in6m = NULL;
1343		if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1344			in6_mc_leave(im6o->im6o_membership[0], NULL);
1345			free(im6o->im6o_membership, M_CARP);
1346			break;
1347		}
1348		im6o->im6o_membership[1] = in6m;
1349		im6o->im6o_num_memberships++;
1350		break;
1351	    }
1352#endif
1353	}
1354
1355	return (error);
1356}
1357
1358/*
1359 * Free multicast structures.
1360 */
1361static void
1362carp_multicast_cleanup(struct carp_if *cif, sa_family_t sa)
1363{
1364
1365	CIF_LOCK_ASSERT(cif);
1366	switch (sa) {
1367#ifdef INET
1368	case AF_INET:
1369		if (cif->cif_naddrs == 0) {
1370			struct ip_moptions *imo = &cif->cif_imo;
1371
1372			in_leavegroup(imo->imo_membership[0], NULL);
1373			KASSERT(imo->imo_mfilters == NULL,
1374			    ("%s: imo_mfilters != NULL", __func__));
1375			free(imo->imo_membership, M_CARP);
1376			imo->imo_membership = NULL;
1377
1378		}
1379		break;
1380#endif
1381#ifdef INET6
1382	case AF_INET6:
1383		if (cif->cif_naddrs6 == 0) {
1384			struct ip6_moptions *im6o = &cif->cif_im6o;
1385
1386			in6_mc_leave(im6o->im6o_membership[0], NULL);
1387			in6_mc_leave(im6o->im6o_membership[1], NULL);
1388			KASSERT(im6o->im6o_mfilters == NULL,
1389			    ("%s: im6o_mfilters != NULL", __func__));
1390			free(im6o->im6o_membership, M_CARP);
1391			im6o->im6o_membership = NULL;
1392		}
1393		break;
1394#endif
1395	}
1396}
1397
1398int
1399carp_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *sa)
1400{
1401	struct m_tag *mtag;
1402	struct carp_softc *sc;
1403
1404	if (!sa)
1405		return (0);
1406
1407	switch (sa->sa_family) {
1408#ifdef INET
1409	case AF_INET:
1410		break;
1411#endif
1412#ifdef INET6
1413	case AF_INET6:
1414		break;
1415#endif
1416	default:
1417		return (0);
1418	}
1419
1420	mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
1421	if (mtag == NULL)
1422		return (0);
1423
1424	bcopy(mtag + 1, &sc, sizeof(sc));
1425
1426	/* Set the source MAC address to the Virtual Router MAC Address. */
1427	switch (ifp->if_type) {
1428	case IFT_ETHER:
1429	case IFT_BRIDGE:
1430	case IFT_L2VLAN: {
1431			struct ether_header *eh;
1432
1433			eh = mtod(m, struct ether_header *);
1434			eh->ether_shost[0] = 0;
1435			eh->ether_shost[1] = 0;
1436			eh->ether_shost[2] = 0x5e;
1437			eh->ether_shost[3] = 0;
1438			eh->ether_shost[4] = 1;
1439			eh->ether_shost[5] = sc->sc_vhid;
1440		}
1441		break;
1442	case IFT_FDDI: {
1443			struct fddi_header *fh;
1444
1445			fh = mtod(m, struct fddi_header *);
1446			fh->fddi_shost[0] = 0;
1447			fh->fddi_shost[1] = 0;
1448			fh->fddi_shost[2] = 0x5e;
1449			fh->fddi_shost[3] = 0;
1450			fh->fddi_shost[4] = 1;
1451			fh->fddi_shost[5] = sc->sc_vhid;
1452		}
1453		break;
1454	case IFT_ISO88025: {
1455 			struct iso88025_header *th;
1456 			th = mtod(m, struct iso88025_header *);
1457			th->iso88025_shost[0] = 3;
1458			th->iso88025_shost[1] = 0;
1459			th->iso88025_shost[2] = 0x40 >> (sc->sc_vhid - 1);
1460			th->iso88025_shost[3] = 0x40000 >> (sc->sc_vhid - 1);
1461			th->iso88025_shost[4] = 0;
1462			th->iso88025_shost[5] = 0;
1463		}
1464		break;
1465	default:
1466		printf("%s: carp is not supported for the %d interface type\n",
1467		    ifp->if_xname, ifp->if_type);
1468		return (EOPNOTSUPP);
1469	}
1470
1471	return (0);
1472}
1473
1474static struct carp_softc*
1475carp_alloc(struct ifnet *ifp)
1476{
1477	struct carp_softc *sc;
1478	struct carp_if *cif;
1479
1480	if ((cif = ifp->if_carp) == NULL) {
1481		cif = carp_alloc_if(ifp);
1482		if (cif == NULL)
1483			return (NULL);
1484	}
1485
1486	sc = malloc(sizeof(*sc), M_CARP, M_WAITOK|M_ZERO);
1487
1488	sc->sc_advbase = CARP_DFLTINTV;
1489	sc->sc_vhid = -1;	/* required setting */
1490	sc->sc_init_counter = 1;
1491	sc->sc_state = INIT;
1492
1493	sc->sc_ifasiz = sizeof(struct ifaddr *);
1494	sc->sc_ifas = malloc(sc->sc_ifasiz, M_CARP, M_WAITOK|M_ZERO);
1495	sc->sc_carpdev = ifp;
1496
1497	CARP_LOCK_INIT(sc);
1498#ifdef INET
1499	callout_init_mtx(&sc->sc_md_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1500#endif
1501#ifdef INET6
1502	callout_init_mtx(&sc->sc_md6_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1503#endif
1504	callout_init_mtx(&sc->sc_ad_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1505
1506	CIF_LOCK(cif);
1507	TAILQ_INSERT_TAIL(&cif->cif_vrs, sc, sc_list);
1508	CIF_UNLOCK(cif);
1509
1510	mtx_lock(&carp_mtx);
1511	LIST_INSERT_HEAD(&carp_list, sc, sc_next);
1512	mtx_unlock(&carp_mtx);
1513
1514	return (sc);
1515}
1516
1517static int
1518carp_grow_ifas(struct carp_softc *sc)
1519{
1520	struct ifaddr **new;
1521
1522	CARP_LOCK_ASSERT(sc);
1523
1524	new = malloc(sc->sc_ifasiz * 2, M_CARP, M_NOWAIT|M_ZERO);
1525	if (new == NULL)
1526		return (ENOMEM);
1527	bcopy(sc->sc_ifas, new, sc->sc_ifasiz);
1528	free(sc->sc_ifas, M_CARP);
1529	sc->sc_ifas = new;
1530	sc->sc_ifasiz *= 2;
1531
1532	return (0);
1533}
1534
1535static void
1536carp_destroy(struct carp_softc *sc)
1537{
1538	struct ifnet *ifp = sc->sc_carpdev;
1539	struct carp_if *cif = ifp->if_carp;
1540
1541	CIF_LOCK_ASSERT(cif);
1542
1543	TAILQ_REMOVE(&cif->cif_vrs, sc, sc_list);
1544
1545	mtx_lock(&carp_mtx);
1546	LIST_REMOVE(sc, sc_next);
1547	mtx_unlock(&carp_mtx);
1548
1549	CARP_LOCK(sc);
1550	if (sc->sc_suppress)
1551		carp_demote_adj(-V_carp_ifdown_adj, "vhid removed");
1552	callout_drain(&sc->sc_ad_tmo);
1553#ifdef INET
1554	callout_drain(&sc->sc_md_tmo);
1555#endif
1556#ifdef INET6
1557	callout_drain(&sc->sc_md6_tmo);
1558#endif
1559	CARP_LOCK_DESTROY(sc);
1560
1561	free(sc->sc_ifas, M_CARP);
1562	free(sc, M_CARP);
1563}
1564
1565static struct carp_if*
1566carp_alloc_if(struct ifnet *ifp)
1567{
1568	struct carp_if *cif;
1569
1570	cif = malloc(sizeof(*cif), M_CARP, M_WAITOK|M_ZERO);
1571
1572	if (ifpromisc(ifp, 1) != 0)
1573		goto cleanup;
1574
1575	CIF_LOCK_INIT(cif);
1576	cif->cif_ifp = ifp;
1577	TAILQ_INIT(&cif->cif_vrs);
1578
1579	IF_ADDR_WLOCK(ifp);
1580	ifp->if_carp = cif;
1581	if_ref(ifp);
1582	IF_ADDR_WUNLOCK(ifp);
1583
1584	return (cif);
1585
1586cleanup:
1587	free(cif, M_CARP);
1588
1589	return (NULL);
1590}
1591
1592static void
1593carp_free_if(struct carp_if *cif)
1594{
1595	struct ifnet *ifp = cif->cif_ifp;
1596
1597	CIF_LOCK_ASSERT(cif);
1598	KASSERT(TAILQ_EMPTY(&cif->cif_vrs), ("%s: softc list not empty",
1599	    __func__));
1600
1601	IF_ADDR_WLOCK(ifp);
1602	ifp->if_carp = NULL;
1603	IF_ADDR_WUNLOCK(ifp);
1604
1605	CIF_LOCK_DESTROY(cif);
1606
1607	ifpromisc(ifp, 0);
1608	if_rele(ifp);
1609
1610	free(cif, M_CARP);
1611}
1612
1613static void
1614carp_carprcp(struct carpreq *carpr, struct carp_softc *sc, int priv)
1615{
1616
1617	CARP_LOCK(sc);
1618	carpr->carpr_state = sc->sc_state;
1619	carpr->carpr_vhid = sc->sc_vhid;
1620	carpr->carpr_advbase = sc->sc_advbase;
1621	carpr->carpr_advskew = sc->sc_advskew;
1622	if (priv)
1623		bcopy(sc->sc_key, carpr->carpr_key, sizeof(carpr->carpr_key));
1624	else
1625		bzero(carpr->carpr_key, sizeof(carpr->carpr_key));
1626	CARP_UNLOCK(sc);
1627}
1628
1629int
1630carp_ioctl(struct ifreq *ifr, u_long cmd, struct thread *td)
1631{
1632	struct carpreq carpr;
1633	struct ifnet *ifp;
1634	struct carp_softc *sc = NULL;
1635	int error = 0, locked = 0;
1636
1637	if ((error = copyin(ifr->ifr_data, &carpr, sizeof carpr)))
1638		return (error);
1639
1640	ifp = ifunit_ref(ifr->ifr_name);
1641	if (ifp == NULL)
1642		return (ENXIO);
1643
1644	switch (ifp->if_type) {
1645	case IFT_ETHER:
1646	case IFT_L2VLAN:
1647	case IFT_BRIDGE:
1648	case IFT_FDDI:
1649	case IFT_ISO88025:
1650		break;
1651	default:
1652		error = EOPNOTSUPP;
1653		goto out;
1654	}
1655
1656	if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1657		error = EADDRNOTAVAIL;
1658		goto out;
1659	}
1660
1661	switch (cmd) {
1662	case SIOCSVH:
1663		if ((error = priv_check(td, PRIV_NETINET_CARP)))
1664			break;
1665		if (carpr.carpr_vhid <= 0 || carpr.carpr_vhid > CARP_MAXVHID ||
1666		    carpr.carpr_advbase < 0 || carpr.carpr_advskew < 0) {
1667			error = EINVAL;
1668			break;
1669		}
1670
1671		if (ifp->if_carp) {
1672			CIF_LOCK(ifp->if_carp);
1673			IFNET_FOREACH_CARP(ifp, sc)
1674				if (sc->sc_vhid == carpr.carpr_vhid)
1675					break;
1676			CIF_UNLOCK(ifp->if_carp);
1677		}
1678		if (sc == NULL) {
1679			sc = carp_alloc(ifp);
1680			if (sc == NULL) {
1681				error = EINVAL; /* XXX: ifpromisc failed */
1682				break;
1683			}
1684
1685			CARP_LOCK(sc);
1686			sc->sc_vhid = carpr.carpr_vhid;
1687			LLADDR(&sc->sc_addr)[0] = 0;
1688			LLADDR(&sc->sc_addr)[1] = 0;
1689			LLADDR(&sc->sc_addr)[2] = 0x5e;
1690			LLADDR(&sc->sc_addr)[3] = 0;
1691			LLADDR(&sc->sc_addr)[4] = 1;
1692			LLADDR(&sc->sc_addr)[5] = sc->sc_vhid;
1693		} else
1694			CARP_LOCK(sc);
1695		locked = 1;
1696		if (carpr.carpr_advbase > 0) {
1697			if (carpr.carpr_advbase > 255 ||
1698			    carpr.carpr_advbase < CARP_DFLTINTV) {
1699				error = EINVAL;
1700				break;
1701			}
1702			sc->sc_advbase = carpr.carpr_advbase;
1703		}
1704		if (carpr.carpr_advskew >= 255) {
1705			error = EINVAL;
1706			break;
1707		}
1708		sc->sc_advskew = carpr.carpr_advskew;
1709		if (carpr.carpr_key[0] != '\0') {
1710			bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1711			carp_hmac_prepare(sc);
1712		}
1713		if (sc->sc_state != INIT &&
1714		    carpr.carpr_state != sc->sc_state) {
1715			switch (carpr.carpr_state) {
1716			case BACKUP:
1717				callout_stop(&sc->sc_ad_tmo);
1718				carp_set_state(sc, BACKUP);
1719				carp_setrun(sc, 0);
1720				carp_delroute(sc);
1721				break;
1722			case MASTER:
1723				carp_master_down_locked(sc);
1724				break;
1725			default:
1726				break;
1727			}
1728		}
1729		break;
1730
1731	case SIOCGVH:
1732	    {
1733		int priveleged;
1734
1735		if (carpr.carpr_vhid < 0 || carpr.carpr_vhid > CARP_MAXVHID) {
1736			error = EINVAL;
1737			break;
1738		}
1739		if (carpr.carpr_count < 1) {
1740			error = EMSGSIZE;
1741			break;
1742		}
1743		if (ifp->if_carp == NULL) {
1744			error = ENOENT;
1745			break;
1746		}
1747
1748		priveleged = (priv_check(td, PRIV_NETINET_CARP) == 0);
1749		if (carpr.carpr_vhid != 0) {
1750			CIF_LOCK(ifp->if_carp);
1751			IFNET_FOREACH_CARP(ifp, sc)
1752				if (sc->sc_vhid == carpr.carpr_vhid)
1753					break;
1754			CIF_UNLOCK(ifp->if_carp);
1755			if (sc == NULL) {
1756				error = ENOENT;
1757				break;
1758			}
1759			carp_carprcp(&carpr, sc, priveleged);
1760			error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
1761		} else  {
1762			int i, count;
1763
1764			count = 0;
1765			CIF_LOCK(ifp->if_carp);
1766			IFNET_FOREACH_CARP(ifp, sc)
1767				count++;
1768
1769			if (count > carpr.carpr_count) {
1770				CIF_UNLOCK(ifp->if_carp);
1771				error = EMSGSIZE;
1772				break;
1773			}
1774
1775			i = 0;
1776			IFNET_FOREACH_CARP(ifp, sc) {
1777				carp_carprcp(&carpr, sc, priveleged);
1778				carpr.carpr_count = count;
1779				error = copyout(&carpr, ifr->ifr_data +
1780				    (i * sizeof(carpr)), sizeof(carpr));
1781				if (error) {
1782					CIF_UNLOCK(ifp->if_carp);
1783					break;
1784				}
1785				i++;
1786			}
1787			CIF_UNLOCK(ifp->if_carp);
1788		}
1789		break;
1790	    }
1791	default:
1792		error = EINVAL;
1793	}
1794
1795out:
1796	if (locked)
1797		CARP_UNLOCK(sc);
1798	if_rele(ifp);
1799
1800	return (error);
1801}
1802
1803static int
1804carp_get_vhid(struct ifaddr *ifa)
1805{
1806
1807	if (ifa == NULL || ifa->ifa_carp == NULL)
1808		return (0);
1809
1810	return (ifa->ifa_carp->sc_vhid);
1811}
1812
1813int
1814carp_attach(struct ifaddr *ifa, int vhid)
1815{
1816	struct ifnet *ifp = ifa->ifa_ifp;
1817	struct carp_if *cif = ifp->if_carp;
1818	struct carp_softc *sc;
1819	int index, error;
1820
1821	if (ifp->if_carp == NULL)
1822		return (ENOPROTOOPT);
1823
1824	switch (ifa->ifa_addr->sa_family) {
1825#ifdef INET
1826	case AF_INET:
1827#endif
1828#ifdef INET6
1829	case AF_INET6:
1830#endif
1831		break;
1832	default:
1833		return (EPROTOTYPE);
1834	}
1835
1836	CIF_LOCK(cif);
1837	IFNET_FOREACH_CARP(ifp, sc)
1838		if (sc->sc_vhid == vhid)
1839			break;
1840	if (sc == NULL) {
1841		CIF_UNLOCK(cif);
1842		return (ENOENT);
1843	}
1844
1845	if (ifa->ifa_carp) {
1846		if (ifa->ifa_carp->sc_vhid != vhid)
1847			carp_detach_locked(ifa);
1848		else {
1849			CIF_UNLOCK(cif);
1850			return (0);
1851		}
1852	}
1853
1854	error = carp_multicast_setup(cif, ifa->ifa_addr->sa_family);
1855	if (error) {
1856		CIF_FREE(cif);
1857		return (error);
1858	}
1859
1860	CARP_LOCK(sc);
1861	index = sc->sc_naddrs + sc->sc_naddrs6 + 1;
1862	if (index > sc->sc_ifasiz / sizeof(struct ifaddr *))
1863		if ((error = carp_grow_ifas(sc)) != 0) {
1864			carp_multicast_cleanup(cif,
1865			    ifa->ifa_addr->sa_family);
1866			CARP_UNLOCK(sc);
1867			CIF_FREE(cif);
1868			return (error);
1869		}
1870
1871	switch (ifa->ifa_addr->sa_family) {
1872#ifdef INET
1873	case AF_INET:
1874		cif->cif_naddrs++;
1875		sc->sc_naddrs++;
1876		break;
1877#endif
1878#ifdef INET6
1879	case AF_INET6:
1880		cif->cif_naddrs6++;
1881		sc->sc_naddrs6++;
1882		break;
1883#endif
1884	}
1885
1886	ifa_ref(ifa);
1887	sc->sc_ifas[index - 1] = ifa;
1888	ifa->ifa_carp = sc;
1889
1890	carp_hmac_prepare(sc);
1891	carp_sc_state(sc);
1892
1893	CARP_UNLOCK(sc);
1894	CIF_UNLOCK(cif);
1895
1896	return (0);
1897}
1898
1899void
1900carp_detach(struct ifaddr *ifa)
1901{
1902	struct ifnet *ifp = ifa->ifa_ifp;
1903	struct carp_if *cif = ifp->if_carp;
1904
1905	CIF_LOCK(cif);
1906	carp_detach_locked(ifa);
1907	CIF_FREE(cif);
1908}
1909
1910static void
1911carp_detach_locked(struct ifaddr *ifa)
1912{
1913	struct ifnet *ifp = ifa->ifa_ifp;
1914	struct carp_if *cif = ifp->if_carp;
1915	struct carp_softc *sc = ifa->ifa_carp;
1916	int i, index;
1917
1918	KASSERT(sc != NULL, ("%s: %p not attached", __func__, ifa));
1919
1920	CIF_LOCK_ASSERT(cif);
1921	CARP_LOCK(sc);
1922
1923	/* Shift array. */
1924	index = sc->sc_naddrs + sc->sc_naddrs6;
1925	for (i = 0; i < index; i++)
1926		if (sc->sc_ifas[i] == ifa)
1927			break;
1928	KASSERT(i < index, ("%s: %p no backref", __func__, ifa));
1929	for (; i < index - 1; i++)
1930		sc->sc_ifas[i] = sc->sc_ifas[i+1];
1931	sc->sc_ifas[index - 1] = NULL;
1932
1933	switch (ifa->ifa_addr->sa_family) {
1934#ifdef INET
1935	case AF_INET:
1936		cif->cif_naddrs--;
1937		sc->sc_naddrs--;
1938		break;
1939#endif
1940#ifdef INET6
1941	case AF_INET6:
1942		cif->cif_naddrs6--;
1943		sc->sc_naddrs6--;
1944		break;
1945#endif
1946	}
1947
1948	carp_ifa_delroute(ifa);
1949	carp_multicast_cleanup(cif, ifa->ifa_addr->sa_family);
1950
1951	ifa->ifa_carp = NULL;
1952	ifa_free(ifa);
1953
1954	carp_hmac_prepare(sc);
1955	carp_sc_state(sc);
1956
1957	if (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0) {
1958		CARP_UNLOCK(sc);
1959		carp_destroy(sc);
1960	} else
1961		CARP_UNLOCK(sc);
1962}
1963
1964static void
1965carp_set_state(struct carp_softc *sc, int state)
1966{
1967
1968	CARP_LOCK_ASSERT(sc);
1969
1970	if (sc->sc_state != state) {
1971		const char *carp_states[] = { CARP_STATES };
1972		char subsys[IFNAMSIZ+5];
1973
1974		sc->sc_state = state;
1975
1976		snprintf(subsys, IFNAMSIZ+5, "%u@%s", sc->sc_vhid,
1977		    sc->sc_carpdev->if_xname);
1978		devctl_notify("CARP", subsys, carp_states[state], NULL);
1979	}
1980}
1981
1982static void
1983carp_linkstate(struct ifnet *ifp)
1984{
1985	struct carp_softc *sc;
1986
1987	CIF_LOCK(ifp->if_carp);
1988	IFNET_FOREACH_CARP(ifp, sc) {
1989		CARP_LOCK(sc);
1990		carp_sc_state(sc);
1991		CARP_UNLOCK(sc);
1992	}
1993	CIF_UNLOCK(ifp->if_carp);
1994}
1995
1996static void
1997carp_sc_state(struct carp_softc *sc)
1998{
1999
2000	CARP_LOCK_ASSERT(sc);
2001
2002	if (sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
2003	    !(sc->sc_carpdev->if_flags & IFF_UP)) {
2004		callout_stop(&sc->sc_ad_tmo);
2005#ifdef INET
2006		callout_stop(&sc->sc_md_tmo);
2007#endif
2008#ifdef INET6
2009		callout_stop(&sc->sc_md6_tmo);
2010#endif
2011		carp_set_state(sc, INIT);
2012		carp_setrun(sc, 0);
2013		if (!sc->sc_suppress)
2014			carp_demote_adj(V_carp_ifdown_adj, "interface down");
2015		sc->sc_suppress = 1;
2016	} else {
2017		carp_set_state(sc, INIT);
2018		carp_setrun(sc, 0);
2019		if (sc->sc_suppress)
2020			carp_demote_adj(-V_carp_ifdown_adj, "interface up");
2021		sc->sc_suppress = 0;
2022	}
2023}
2024
2025static void
2026carp_demote_adj(int adj, char *reason)
2027{
2028	atomic_add_int(&V_carp_demotion, adj);
2029	CARP_LOG("demoted by %d to %d (%s)\n", adj, V_carp_demotion, reason);
2030	taskqueue_enqueue(taskqueue_swi, &carp_sendall_task);
2031}
2032
2033static int
2034carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS)
2035{
2036	int new, error;
2037
2038	new = V_carp_demotion;
2039	error = sysctl_handle_int(oidp, &new, 0, req);
2040	if (error || !req->newptr)
2041		return (error);
2042
2043	carp_demote_adj(new, "sysctl");
2044
2045	return (0);
2046}
2047
2048#ifdef INET
2049extern  struct domain inetdomain;
2050static struct protosw in_carp_protosw = {
2051	.pr_type =		SOCK_RAW,
2052	.pr_domain =		&inetdomain,
2053	.pr_protocol =		IPPROTO_CARP,
2054	.pr_flags =		PR_ATOMIC|PR_ADDR,
2055	.pr_input =		carp_input,
2056	.pr_output =		(pr_output_t *)rip_output,
2057	.pr_ctloutput =		rip_ctloutput,
2058	.pr_usrreqs =		&rip_usrreqs
2059};
2060#endif
2061
2062#ifdef INET6
2063extern	struct domain inet6domain;
2064static struct ip6protosw in6_carp_protosw = {
2065	.pr_type =		SOCK_RAW,
2066	.pr_domain =		&inet6domain,
2067	.pr_protocol =		IPPROTO_CARP,
2068	.pr_flags =		PR_ATOMIC|PR_ADDR,
2069	.pr_input =		carp6_input,
2070	.pr_output =		rip6_output,
2071	.pr_ctloutput =		rip6_ctloutput,
2072	.pr_usrreqs =		&rip6_usrreqs
2073};
2074#endif
2075
2076static void
2077carp_mod_cleanup(void)
2078{
2079
2080#ifdef INET
2081	if (proto_reg[CARP_INET] == 0) {
2082		(void)ipproto_unregister(IPPROTO_CARP);
2083		pf_proto_unregister(PF_INET, IPPROTO_CARP, SOCK_RAW);
2084		proto_reg[CARP_INET] = -1;
2085	}
2086	carp_iamatch_p = NULL;
2087#endif
2088#ifdef INET6
2089	if (proto_reg[CARP_INET6] == 0) {
2090		(void)ip6proto_unregister(IPPROTO_CARP);
2091		pf_proto_unregister(PF_INET6, IPPROTO_CARP, SOCK_RAW);
2092		proto_reg[CARP_INET6] = -1;
2093	}
2094	carp_iamatch6_p = NULL;
2095	carp_macmatch6_p = NULL;
2096#endif
2097	carp_ioctl_p = NULL;
2098	carp_attach_p = NULL;
2099	carp_detach_p = NULL;
2100	carp_get_vhid_p = NULL;
2101	carp_linkstate_p = NULL;
2102	carp_forus_p = NULL;
2103	carp_output_p = NULL;
2104	carp_demote_adj_p = NULL;
2105	carp_master_p = NULL;
2106	mtx_unlock(&carp_mtx);
2107	taskqueue_drain(taskqueue_swi, &carp_sendall_task);
2108	mtx_destroy(&carp_mtx);
2109}
2110
2111static int
2112carp_mod_load(void)
2113{
2114	int err;
2115
2116	mtx_init(&carp_mtx, "carp_mtx", NULL, MTX_DEF);
2117	LIST_INIT(&carp_list);
2118	carp_get_vhid_p = carp_get_vhid;
2119	carp_forus_p = carp_forus;
2120	carp_output_p = carp_output;
2121	carp_linkstate_p = carp_linkstate;
2122	carp_ioctl_p = carp_ioctl;
2123	carp_attach_p = carp_attach;
2124	carp_detach_p = carp_detach;
2125	carp_demote_adj_p = carp_demote_adj;
2126	carp_master_p = carp_master;
2127#ifdef INET6
2128	carp_iamatch6_p = carp_iamatch6;
2129	carp_macmatch6_p = carp_macmatch6;
2130	proto_reg[CARP_INET6] = pf_proto_register(PF_INET6,
2131	    (struct protosw *)&in6_carp_protosw);
2132	if (proto_reg[CARP_INET6]) {
2133		printf("carp: error %d attaching to PF_INET6\n",
2134		    proto_reg[CARP_INET6]);
2135		carp_mod_cleanup();
2136		return (proto_reg[CARP_INET6]);
2137	}
2138	err = ip6proto_register(IPPROTO_CARP);
2139	if (err) {
2140		printf("carp: error %d registering with INET6\n", err);
2141		carp_mod_cleanup();
2142		return (err);
2143	}
2144#endif
2145#ifdef INET
2146	carp_iamatch_p = carp_iamatch;
2147	proto_reg[CARP_INET] = pf_proto_register(PF_INET, &in_carp_protosw);
2148	if (proto_reg[CARP_INET]) {
2149		printf("carp: error %d attaching to PF_INET\n",
2150		    proto_reg[CARP_INET]);
2151		carp_mod_cleanup();
2152		return (proto_reg[CARP_INET]);
2153	}
2154	err = ipproto_register(IPPROTO_CARP);
2155	if (err) {
2156		printf("carp: error %d registering with INET\n", err);
2157		carp_mod_cleanup();
2158		return (err);
2159	}
2160#endif
2161	return (0);
2162}
2163
2164static int
2165carp_modevent(module_t mod, int type, void *data)
2166{
2167	switch (type) {
2168	case MOD_LOAD:
2169		return carp_mod_load();
2170		/* NOTREACHED */
2171	case MOD_UNLOAD:
2172		mtx_lock(&carp_mtx);
2173		if (LIST_EMPTY(&carp_list))
2174			carp_mod_cleanup();
2175		else {
2176			mtx_unlock(&carp_mtx);
2177			return (EBUSY);
2178		}
2179		break;
2180
2181	default:
2182		return (EINVAL);
2183	}
2184
2185	return (0);
2186}
2187
2188static moduledata_t carp_mod = {
2189	"carp",
2190	carp_modevent,
2191	0
2192};
2193
2194DECLARE_MODULE(carp, carp_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
2195