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