xref: /freebsd/sys/netinet/ip_carp.c (revision b7c60aadbbd5c846a250c05791fe7406d6d78bf4)
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 			carp_send_ad_locked(sc);
711 			CARP_UNLOCK(sc);
712 		}
713 	mtx_unlock(&carp_mtx);
714 }
715 
716 static void
717 carp_send_ad(void *v)
718 {
719 	struct carp_softc *sc = v;
720 
721 	CARP_LOCK_ASSERT(sc);
722 	carp_send_ad_locked(sc);
723 	CARP_UNLOCK(sc);
724 }
725 
726 static void
727 carp_send_ad_locked(struct carp_softc *sc)
728 {
729 	struct carp_header ch;
730 	struct timeval tv;
731 	struct sockaddr sa;
732 	struct ifaddr *ifa;
733 	struct carp_header *ch_ptr;
734 	struct mbuf *m;
735 	int len, advskew;
736 
737 	CARP_LOCK_ASSERT(sc);
738 
739 	advskew = DEMOTE_ADVSKEW(sc);
740 	tv.tv_sec = sc->sc_advbase;
741 	tv.tv_usec = advskew * 1000000 / 256;
742 
743 	ch.carp_version = CARP_VERSION;
744 	ch.carp_type = CARP_ADVERTISEMENT;
745 	ch.carp_vhid = sc->sc_vhid;
746 	ch.carp_advbase = sc->sc_advbase;
747 	ch.carp_advskew = advskew;
748 	ch.carp_authlen = 7;	/* XXX DEFINE */
749 	ch.carp_pad1 = 0;	/* must be zero */
750 	ch.carp_cksum = 0;
751 
752 	/* XXXGL: OpenBSD picks first ifaddr with needed family. */
753 
754 #ifdef INET
755 	if (sc->sc_naddrs) {
756 		struct ip *ip;
757 
758 		MGETHDR(m, M_NOWAIT, MT_HEADER);
759 		if (m == NULL) {
760 			CARPSTATS_INC(carps_onomem);
761 			/* XXX maybe less ? */
762 			callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
763 			    carp_send_ad, sc);
764 			return;
765 		}
766 		len = sizeof(*ip) + sizeof(ch);
767 		m->m_pkthdr.len = len;
768 		m->m_pkthdr.rcvif = NULL;
769 		m->m_len = len;
770 		MH_ALIGN(m, m->m_len);
771 		m->m_flags |= M_MCAST;
772 		ip = mtod(m, struct ip *);
773 		ip->ip_v = IPVERSION;
774 		ip->ip_hl = sizeof(*ip) >> 2;
775 		ip->ip_tos = IPTOS_LOWDELAY;
776 		ip->ip_len = len;
777 		ip->ip_id = ip_newid();
778 		ip->ip_off = IP_DF;
779 		ip->ip_ttl = CARP_DFLTTL;
780 		ip->ip_p = IPPROTO_CARP;
781 		ip->ip_sum = 0;
782 
783 		bzero(&sa, sizeof(sa));
784 		sa.sa_family = AF_INET;
785 		ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
786 		if (ifa != NULL) {
787 			ip->ip_src.s_addr =
788 			    ifatoia(ifa)->ia_addr.sin_addr.s_addr;
789 			ifa_free(ifa);
790 		} else
791 			ip->ip_src.s_addr = 0;
792 		ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP);
793 
794 		ch_ptr = (struct carp_header *)(&ip[1]);
795 		bcopy(&ch, ch_ptr, sizeof(ch));
796 		if (carp_prepare_ad(m, sc, ch_ptr))
797 			return;
798 
799 		m->m_data += sizeof(*ip);
800 		ch_ptr->carp_cksum = carp_cksum(m, len - sizeof(*ip));
801 		m->m_data -= sizeof(*ip);
802 
803 		CARPSTATS_INC(carps_opackets);
804 
805 		if (ip_output(m, NULL, NULL, IP_RAWOUTPUT,
806 		    &sc->sc_carpdev->if_carp->cif_imo, NULL)) {
807 			if (sc->sc_sendad_errors < INT_MAX)
808 				sc->sc_sendad_errors++;
809 			if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS)
810 				carp_demote_adj(carp_senderr_adj, "send error");
811 			sc->sc_sendad_success = 0;
812 		} else {
813 			if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
814 				if (++sc->sc_sendad_success >=
815 				    CARP_SENDAD_MIN_SUCCESS) {
816 					carp_demote_adj(-carp_senderr_adj,
817 					    "send ok");
818 					sc->sc_sendad_errors = 0;
819 				}
820 			} else
821 				sc->sc_sendad_errors = 0;
822 		}
823 	}
824 #endif /* INET */
825 #ifdef INET6
826 	if (sc->sc_naddrs6) {
827 		struct ip6_hdr *ip6;
828 
829 		MGETHDR(m, M_NOWAIT, MT_HEADER);
830 		if (m == NULL) {
831 			CARPSTATS_INC(carps_onomem);
832 			/* XXX maybe less ? */
833 			callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
834 			    carp_send_ad, sc);
835 			return;
836 		}
837 		len = sizeof(*ip6) + sizeof(ch);
838 		m->m_pkthdr.len = len;
839 		m->m_pkthdr.rcvif = NULL;
840 		m->m_len = len;
841 		MH_ALIGN(m, m->m_len);
842 		m->m_flags |= M_MCAST;
843 		ip6 = mtod(m, struct ip6_hdr *);
844 		bzero(ip6, sizeof(*ip6));
845 		ip6->ip6_vfc |= IPV6_VERSION;
846 		ip6->ip6_hlim = CARP_DFLTTL;
847 		ip6->ip6_nxt = IPPROTO_CARP;
848 		bzero(&sa, sizeof(sa));
849 
850 		/* set the source address */
851 		sa.sa_family = AF_INET6;
852 		ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
853 		if (ifa != NULL) {
854 			bcopy(IFA_IN6(ifa), &ip6->ip6_src,
855 			    sizeof(struct in6_addr));
856 			ifa_free(ifa);
857 		} else
858 			/* This should never happen with IPv6. */
859 			bzero(&ip6->ip6_src, sizeof(struct in6_addr));
860 
861 		/* Set the multicast destination. */
862 		ip6->ip6_dst.s6_addr16[0] = htons(0xff02);
863 		ip6->ip6_dst.s6_addr8[15] = 0x12;
864 		if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) {
865 			m_freem(m);
866 			CARP_DEBUG("%s: in6_setscope failed\n", __func__);
867 			return;
868 		}
869 
870 		ch_ptr = (struct carp_header *)(&ip6[1]);
871 		bcopy(&ch, ch_ptr, sizeof(ch));
872 		if (carp_prepare_ad(m, sc, ch_ptr))
873 			return;
874 
875 		m->m_data += sizeof(*ip6);
876 		ch_ptr->carp_cksum = carp_cksum(m, len - sizeof(*ip6));
877 		m->m_data -= sizeof(*ip6);
878 
879 		CARPSTATS_INC(carps_opackets6);
880 
881 		if (ip6_output(m, NULL, NULL, 0,
882 		    &sc->sc_carpdev->if_carp->cif_im6o, NULL, NULL)) {
883 			if (sc->sc_sendad_errors < INT_MAX)
884 				sc->sc_sendad_errors++;
885 			if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS)
886 				carp_demote_adj(carp_senderr_adj,
887 				    "send6 error");
888 			sc->sc_sendad_success = 0;
889 		} else {
890 			if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
891 				if (++sc->sc_sendad_success >=
892 				    CARP_SENDAD_MIN_SUCCESS) {
893 					carp_demote_adj(-carp_senderr_adj,
894 					    "send6 ok");
895 					sc->sc_sendad_errors = 0;
896 				}
897 			} else
898 				sc->sc_sendad_errors = 0;
899 		}
900 	}
901 #endif /* INET6 */
902 
903 	callout_reset(&sc->sc_ad_tmo, tvtohz(&tv), carp_send_ad, sc);
904 }
905 
906 static void
907 carp_addroute(struct carp_softc *sc)
908 {
909 	struct ifaddr *ifa;
910 
911 	CARP_FOREACH_IFA(sc, ifa)
912 		carp_ifa_addroute(ifa);
913 }
914 
915 static void
916 carp_ifa_addroute(struct ifaddr *ifa)
917 {
918 
919 	switch (ifa->ifa_addr->sa_family) {
920 #ifdef INET
921 	case AF_INET:
922 		in_addprefix(ifatoia(ifa), RTF_UP);
923 		ifa_add_loopback_route(ifa,
924 		    (struct sockaddr *)&ifatoia(ifa)->ia_addr);
925 		break;
926 #endif
927 #ifdef INET6
928 	case AF_INET6:
929 		ifa_add_loopback_route(ifa,
930 		    (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
931 		in6_ifaddloop(ifa);
932 		break;
933 #endif
934 	}
935 }
936 
937 static void
938 carp_delroute(struct carp_softc *sc)
939 {
940 	struct ifaddr *ifa;
941 
942 	CARP_FOREACH_IFA(sc, ifa)
943 		carp_ifa_delroute(ifa);
944 }
945 
946 static void
947 carp_ifa_delroute(struct ifaddr *ifa)
948 {
949 
950 	switch (ifa->ifa_addr->sa_family) {
951 #ifdef INET
952 	case AF_INET:
953 		ifa_del_loopback_route(ifa,
954 		    (struct sockaddr *)&ifatoia(ifa)->ia_addr);
955 		in_scrubprefix(ifatoia(ifa), LLE_STATIC);
956 		break;
957 #endif
958 #ifdef INET6
959 	case AF_INET6:
960 		ifa_del_loopback_route(ifa,
961 		    (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
962 		in6_ifremloop(ifa);
963 		break;
964 #endif
965 	}
966 }
967 
968 #ifdef INET
969 /*
970  * Broadcast a gratuitous ARP request containing
971  * the virtual router MAC address for each IP address
972  * associated with the virtual router.
973  */
974 static void
975 carp_send_arp(struct carp_softc *sc)
976 {
977 	struct ifaddr *ifa;
978 
979 	CARP_FOREACH_IFA(sc, ifa)
980 		if (ifa->ifa_addr->sa_family == AF_INET)
981 			arp_ifinit2(sc->sc_carpdev, ifa, LLADDR(&sc->sc_addr));
982 }
983 
984 int
985 carp_iamatch(struct ifaddr *ifa, uint8_t **enaddr)
986 {
987 	struct carp_softc *sc = ifa->ifa_carp;
988 
989 	if (sc->sc_state == MASTER) {
990 		*enaddr = LLADDR(&sc->sc_addr);
991 		return (1);
992 	}
993 
994 	return (0);
995 }
996 #endif
997 
998 #ifdef INET6
999 static void
1000 carp_send_na(struct carp_softc *sc)
1001 {
1002 	static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1003 	struct ifaddr *ifa;
1004 	struct in6_addr *in6;
1005 
1006 	CARP_FOREACH_IFA(sc, ifa) {
1007 		if (ifa->ifa_addr->sa_family != AF_INET6)
1008 			continue;
1009 
1010 		in6 = IFA_IN6(ifa);
1011 		nd6_na_output(sc->sc_carpdev, &mcast, in6,
1012 		    ND_NA_FLAG_OVERRIDE, 1, NULL);
1013 		DELAY(1000);	/* XXX */
1014 	}
1015 }
1016 
1017 struct ifaddr *
1018 carp_iamatch6(struct ifnet *ifp, struct in6_addr *taddr)
1019 {
1020 	struct ifaddr *ifa;
1021 
1022 	IF_ADDR_RLOCK(ifp);
1023 	IFNET_FOREACH_IFA(ifp, ifa)
1024 		if (ifa->ifa_addr->sa_family == AF_INET6 &&
1025 		    ifa->ifa_carp->sc_state == MASTER &&
1026 		    IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa))) {
1027 			ifa_ref(ifa);
1028 			IF_ADDR_RUNLOCK(ifp);
1029 			return (ifa);
1030 		}
1031 	IF_ADDR_RUNLOCK(ifp);
1032 
1033 	return (NULL);
1034 }
1035 
1036 caddr_t
1037 carp_macmatch6(struct ifnet *ifp, struct mbuf *m, const struct in6_addr *taddr)
1038 {
1039 	struct ifaddr *ifa;
1040 
1041 	IF_ADDR_RLOCK(ifp);
1042 	IFNET_FOREACH_IFA(ifp, ifa)
1043 		if (ifa->ifa_addr->sa_family == AF_INET6 &&
1044 		    IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa))) {
1045 			struct carp_softc *sc = ifa->ifa_carp;
1046 			struct m_tag *mtag;
1047 
1048 			IF_ADDR_RUNLOCK(ifp);
1049 
1050 			mtag = m_tag_get(PACKET_TAG_CARP,
1051 			    sizeof(struct ifnet *), M_NOWAIT);
1052 			if (mtag == NULL)
1053 				/* Better a bit than nothing. */
1054 				return (LLADDR(&sc->sc_addr));
1055 
1056 			bcopy(&ifp, (caddr_t)(mtag + 1),
1057 			    sizeof(struct ifnet *));
1058 			m_tag_prepend(m, mtag);
1059 
1060 			return (LLADDR(&sc->sc_addr));
1061 		}
1062 	IF_ADDR_RUNLOCK(ifp);
1063 
1064 	return (NULL);
1065 }
1066 #endif /* INET6 */
1067 
1068 int
1069 carp_forus(struct ifnet *ifp, u_char *dhost)
1070 {
1071 	struct carp_softc *sc;
1072 	uint8_t *ena = dhost;
1073 
1074 	if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1075 		return (0);
1076 
1077 	CIF_LOCK(ifp->if_carp);
1078 	IFNET_FOREACH_CARP(ifp, sc) {
1079 		CARP_LOCK(sc);
1080 		if (sc->sc_state == MASTER && !bcmp(dhost, LLADDR(&sc->sc_addr),
1081 		    ETHER_ADDR_LEN)) {
1082 			CARP_UNLOCK(sc);
1083 			CIF_UNLOCK(ifp->if_carp);
1084 			return (1);
1085 		}
1086 		CARP_UNLOCK(sc);
1087 	}
1088 	CIF_UNLOCK(ifp->if_carp);
1089 
1090 	return (0);
1091 }
1092 
1093 static void
1094 carp_master_down(void *v)
1095 {
1096 	struct carp_softc *sc = v;
1097 
1098 	CARP_LOCK_ASSERT(sc);
1099 
1100 	if (sc->sc_state == BACKUP) {
1101 		CARP_LOG("VHID %u@%s: BACKUP -> MASTER (master down)\n",
1102 		    sc->sc_vhid,
1103 		    sc->sc_carpdev->if_xname);
1104 		carp_master_down_locked(sc);
1105 	}
1106 
1107 	CARP_UNLOCK(sc);
1108 }
1109 
1110 static void
1111 carp_master_down_locked(struct carp_softc *sc)
1112 {
1113 
1114 	CARP_LOCK_ASSERT(sc);
1115 
1116 	switch (sc->sc_state) {
1117 	case BACKUP:
1118 		carp_set_state(sc, MASTER);
1119 		carp_send_ad_locked(sc);
1120 #ifdef INET
1121 		carp_send_arp(sc);
1122 #endif
1123 #ifdef INET6
1124 		carp_send_na(sc);
1125 #endif
1126 		carp_setrun(sc, 0);
1127 		carp_addroute(sc);
1128 		break;
1129 	case INIT:
1130 	case MASTER:
1131 #ifdef INVARIANTS
1132 		panic("carp: VHID %u@%s: master_down event in %s state\n",
1133 		    sc->sc_vhid,
1134 		    sc->sc_carpdev->if_xname,
1135 		    sc->sc_state ? "MASTER" : "INIT");
1136 #endif
1137 		break;
1138 	}
1139 }
1140 
1141 /*
1142  * When in backup state, af indicates whether to reset the master down timer
1143  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1144  */
1145 static void
1146 carp_setrun(struct carp_softc *sc, sa_family_t af)
1147 {
1148 	struct timeval tv;
1149 
1150 	CARP_LOCK_ASSERT(sc);
1151 
1152 	if ((sc->sc_carpdev->if_flags & IFF_UP) == 0 ||
1153 	    sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1154 	    (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0))
1155 		return;
1156 
1157 	switch (sc->sc_state) {
1158 	case INIT:
1159 		CARP_LOG("VHID %u@%s: INIT -> BACKUP\n",
1160 		    sc->sc_vhid,
1161 		    sc->sc_carpdev->if_xname);
1162 		carp_set_state(sc, BACKUP);
1163 		carp_setrun(sc, 0);
1164 		break;
1165 	case BACKUP:
1166 		callout_stop(&sc->sc_ad_tmo);
1167 		tv.tv_sec = 3 * sc->sc_advbase;
1168 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1169 		switch (af) {
1170 #ifdef INET
1171 		case AF_INET:
1172 			callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1173 			    carp_master_down, sc);
1174 			break;
1175 #endif
1176 #ifdef INET6
1177 		case AF_INET6:
1178 			callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1179 			    carp_master_down, sc);
1180 			break;
1181 #endif
1182 		default:
1183 #ifdef INET
1184 			if (sc->sc_naddrs)
1185 				callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1186 				    carp_master_down, sc);
1187 #endif
1188 #ifdef INET6
1189 			if (sc->sc_naddrs6)
1190 				callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1191 				    carp_master_down, sc);
1192 #endif
1193 			break;
1194 		}
1195 		break;
1196 	case MASTER:
1197 		tv.tv_sec = sc->sc_advbase;
1198 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1199 		callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1200 		    carp_send_ad, sc);
1201 		break;
1202 	}
1203 }
1204 
1205 /*
1206  * Setup multicast structures.
1207  */
1208 static int
1209 carp_multicast_setup(struct carp_softc *sc, sa_family_t sa)
1210 {
1211 	struct ifnet *ifp = sc->sc_carpdev;
1212 	struct carp_if *cif = ifp->if_carp;
1213 	int error = 0;
1214 
1215 	switch (sa) {
1216 #ifdef INET
1217 	case AF_INET:
1218 	    {
1219 		struct ip_moptions *imo = &cif->cif_imo;
1220 		struct in_addr addr;
1221 
1222 		if (imo->imo_membership)
1223 			return (0);
1224 
1225 		imo->imo_membership = (struct in_multi **)malloc(
1226 		    (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_CARP,
1227 		    M_WAITOK);
1228 		imo->imo_mfilters = NULL;
1229 		imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1230 		imo->imo_multicast_vif = -1;
1231 
1232 		addr.s_addr = htonl(INADDR_CARP_GROUP);
1233 		if ((error = in_joingroup(ifp, &addr, NULL,
1234 		    &imo->imo_membership[0])) != 0) {
1235 			free(imo->imo_membership, M_CARP);
1236 			break;
1237 		}
1238 		imo->imo_num_memberships++;
1239 		imo->imo_multicast_ifp = ifp;
1240 		imo->imo_multicast_ttl = CARP_DFLTTL;
1241 		imo->imo_multicast_loop = 0;
1242 		break;
1243 	   }
1244 #endif
1245 #ifdef INET6
1246 	case AF_INET6:
1247 	    {
1248 		struct ip6_moptions *im6o = &cif->cif_im6o;
1249 		struct in6_addr in6;
1250 		struct in6_multi *in6m;
1251 
1252 		if (im6o->im6o_membership)
1253 			return (0);
1254 
1255 		im6o->im6o_membership = (struct in6_multi **)malloc(
1256 		    (sizeof(struct in6_multi *) * IPV6_MIN_MEMBERSHIPS), M_CARP,
1257 		    M_ZERO|M_WAITOK);
1258 		im6o->im6o_mfilters = NULL;
1259 		im6o->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
1260 		im6o->im6o_multicast_hlim = CARP_DFLTTL;
1261 		im6o->im6o_multicast_ifp = ifp;
1262 
1263 		/* Join IPv6 CARP multicast group. */
1264 		bzero(&in6, sizeof(in6));
1265 		in6.s6_addr16[0] = htons(0xff02);
1266 		in6.s6_addr8[15] = 0x12;
1267 		if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1268 			free(im6o->im6o_membership, M_CARP);
1269 			break;
1270 		}
1271 		in6m = NULL;
1272 		if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1273 			free(im6o->im6o_membership, M_CARP);
1274 			break;
1275 		}
1276 		im6o->im6o_membership[0] = in6m;
1277 		im6o->im6o_num_memberships++;
1278 
1279 		/* Join solicited multicast address. */
1280 		bzero(&in6, sizeof(in6));
1281 		in6.s6_addr16[0] = htons(0xff02);
1282 		in6.s6_addr32[1] = 0;
1283 		in6.s6_addr32[2] = htonl(1);
1284 		in6.s6_addr32[3] = 0;
1285 		in6.s6_addr8[12] = 0xff;
1286 		if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1287 			in6_mc_leave(im6o->im6o_membership[0], NULL);
1288 			free(im6o->im6o_membership, M_CARP);
1289 			break;
1290 		}
1291 		in6m = NULL;
1292 		if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1293 			in6_mc_leave(im6o->im6o_membership[0], NULL);
1294 			free(im6o->im6o_membership, M_CARP);
1295 			break;
1296 		}
1297 		im6o->im6o_membership[1] = in6m;
1298 		im6o->im6o_num_memberships++;
1299 		break;
1300 	    }
1301 #endif
1302 	}
1303 
1304 	return (error);
1305 }
1306 
1307 /*
1308  * Free multicast structures.
1309  */
1310 static void
1311 carp_multicast_cleanup(struct carp_softc *sc, sa_family_t sa)
1312 {
1313 	struct ifnet *ifp = sc->sc_carpdev;
1314 	struct carp_if *cif = ifp->if_carp;
1315 
1316 	switch (sa) {
1317 #ifdef INET
1318 	case AF_INET:
1319 		if (sc->sc_naddrs == 0) {
1320 			struct ip_moptions *imo = &cif->cif_imo;
1321 
1322 			in_leavegroup(imo->imo_membership[0], NULL);
1323 			KASSERT(imo->imo_mfilters == NULL,
1324 			    ("%s: imo_mfilters != NULL", __func__));
1325 			free(imo->imo_membership, M_CARP);
1326 			imo->imo_membership = NULL;
1327 
1328 		}
1329 		break;
1330 #endif
1331 #ifdef INET6
1332 	case AF_INET6:
1333 		if (sc->sc_naddrs6 == 0) {
1334 			struct ip6_moptions *im6o = &cif->cif_im6o;
1335 
1336 			in6_mc_leave(im6o->im6o_membership[0], NULL);
1337 			in6_mc_leave(im6o->im6o_membership[1], NULL);
1338 			KASSERT(im6o->im6o_mfilters == NULL,
1339 			    ("%s: im6o_mfilters != NULL", __func__));
1340 			free(im6o->im6o_membership, M_CARP);
1341 			im6o->im6o_membership = NULL;
1342 		}
1343 		break;
1344 #endif
1345 	}
1346 }
1347 
1348 int
1349 carp_output(struct ifnet *ifp, struct mbuf *m, struct sockaddr *sa)
1350 {
1351 	struct m_tag *mtag;
1352 	struct carp_softc *sc;
1353 
1354 	if (!sa)
1355 		return (0);
1356 
1357 	switch (sa->sa_family) {
1358 #ifdef INET
1359 	case AF_INET:
1360 		break;
1361 #endif
1362 #ifdef INET6
1363 	case AF_INET6:
1364 		break;
1365 #endif
1366 	default:
1367 		return (0);
1368 	}
1369 
1370 	mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
1371 	if (mtag == NULL)
1372 		return (0);
1373 
1374 	bcopy(mtag + 1, &sc, sizeof(struct carp_softc *));
1375 
1376 	/* Set the source MAC address to the Virtual Router MAC Address. */
1377 	switch (ifp->if_type) {
1378 	case IFT_ETHER:
1379 	case IFT_L2VLAN: {
1380 			struct ether_header *eh;
1381 
1382 			eh = mtod(m, struct ether_header *);
1383 			eh->ether_shost[0] = 0;
1384 			eh->ether_shost[1] = 0;
1385 			eh->ether_shost[2] = 0x5e;
1386 			eh->ether_shost[3] = 0;
1387 			eh->ether_shost[4] = 1;
1388 			eh->ether_shost[5] = sc->sc_vhid;
1389 		}
1390 		break;
1391 	case IFT_FDDI: {
1392 			struct fddi_header *fh;
1393 
1394 			fh = mtod(m, struct fddi_header *);
1395 			fh->fddi_shost[0] = 0;
1396 			fh->fddi_shost[1] = 0;
1397 			fh->fddi_shost[2] = 0x5e;
1398 			fh->fddi_shost[3] = 0;
1399 			fh->fddi_shost[4] = 1;
1400 			fh->fddi_shost[5] = sc->sc_vhid;
1401 		}
1402 		break;
1403 	case IFT_ISO88025: {
1404  			struct iso88025_header *th;
1405  			th = mtod(m, struct iso88025_header *);
1406 			th->iso88025_shost[0] = 3;
1407 			th->iso88025_shost[1] = 0;
1408 			th->iso88025_shost[2] = 0x40 >> (sc->sc_vhid - 1);
1409 			th->iso88025_shost[3] = 0x40000 >> (sc->sc_vhid - 1);
1410 			th->iso88025_shost[4] = 0;
1411 			th->iso88025_shost[5] = 0;
1412 		}
1413 		break;
1414 	default:
1415 		printf("%s: carp is not supported for the %d interface type\n",
1416 		    ifp->if_xname, ifp->if_type);
1417 		return (EOPNOTSUPP);
1418 	}
1419 
1420 	return (0);
1421 }
1422 
1423 static struct carp_softc*
1424 carp_alloc(struct ifnet *ifp)
1425 {
1426 	struct carp_softc *sc;
1427 	struct carp_if *cif;
1428 
1429 	if ((cif = ifp->if_carp) == NULL) {
1430 		cif = carp_alloc_if(ifp);
1431 		if (cif == NULL)
1432 			return (NULL);
1433 	}
1434 
1435 	sc = malloc(sizeof(*sc), M_CARP, M_WAITOK|M_ZERO);
1436 
1437 	sc->sc_advbase = CARP_DFLTINTV;
1438 	sc->sc_vhid = -1;	/* required setting */
1439 	sc->sc_init_counter = 1;
1440 	sc->sc_state = INIT;
1441 
1442 	sc->sc_ifasiz = sizeof(struct ifaddr *);
1443 	sc->sc_ifas = malloc(sc->sc_ifasiz, M_CARP, M_WAITOK|M_ZERO);
1444 	sc->sc_carpdev = ifp;
1445 
1446 	CARP_LOCK_INIT(sc);
1447 #ifdef INET
1448 	callout_init_mtx(&sc->sc_md_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1449 #endif
1450 #ifdef INET6
1451 	callout_init_mtx(&sc->sc_md6_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1452 #endif
1453 	callout_init_mtx(&sc->sc_ad_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1454 
1455 	CIF_LOCK(cif);
1456 	TAILQ_INSERT_TAIL(&cif->cif_vrs, sc, sc_list);
1457 	CIF_UNLOCK(cif);
1458 
1459 	mtx_lock(&carp_mtx);
1460 	LIST_INSERT_HEAD(&carp_list, sc, sc_next);
1461 	mtx_unlock(&carp_mtx);
1462 
1463 	return (sc);
1464 }
1465 
1466 static int
1467 carp_grow_ifas(struct carp_softc *sc)
1468 {
1469 	struct ifaddr **new;
1470 
1471 	CARP_LOCK_ASSERT(sc);
1472 
1473 	new = malloc(sc->sc_ifasiz * 2, M_CARP, M_NOWAIT|M_ZERO);
1474 	if (new == NULL)
1475 		return (ENOMEM);
1476 	bcopy(sc->sc_ifas, new, sc->sc_ifasiz);
1477 	free(sc->sc_ifas, M_CARP);
1478 	sc->sc_ifas = new;
1479 	sc->sc_ifasiz *= 2;
1480 
1481 	return (0);
1482 }
1483 
1484 static void
1485 carp_destroy(struct carp_softc *sc)
1486 {
1487 	struct ifnet *ifp = sc->sc_carpdev;
1488 	struct carp_if *cif = ifp->if_carp;
1489 
1490 	CIF_LOCK(cif);
1491 	TAILQ_REMOVE(&cif->cif_vrs, sc, sc_list);
1492 	if (TAILQ_EMPTY(&cif->cif_vrs))
1493 		carp_free_if(cif);
1494 	else
1495 		CIF_UNLOCK(cif);
1496 
1497 	mtx_lock(&carp_mtx);
1498 	LIST_REMOVE(sc, sc_next);
1499 	mtx_unlock(&carp_mtx);
1500 
1501 	CARP_LOCK(sc);
1502 	if (sc->sc_suppress)
1503 		carp_demote_adj(-carp_ifdown_adj, "vhid removed");
1504 	callout_drain(&sc->sc_ad_tmo);
1505 #ifdef INET
1506 	callout_drain(&sc->sc_md_tmo);
1507 #endif
1508 #ifdef INET6
1509 	callout_drain(&sc->sc_md6_tmo);
1510 #endif
1511 	CARP_LOCK_DESTROY(sc);
1512 
1513 	free(sc->sc_ifas, M_CARP);
1514 	free(sc, M_CARP);
1515 }
1516 
1517 static struct carp_if*
1518 carp_alloc_if(struct ifnet *ifp)
1519 {
1520 	struct carp_if *cif;
1521 
1522 	cif = malloc(sizeof(*cif), M_CARP, M_WAITOK|M_ZERO);
1523 
1524 	if (ifpromisc(ifp, 1) != 0)
1525 		goto cleanup;
1526 
1527 	CIF_LOCK_INIT(cif);
1528 	cif->cif_ifp = ifp;
1529 	TAILQ_INIT(&cif->cif_vrs);
1530 
1531 	IF_ADDR_WLOCK(ifp);
1532 	ifp->if_carp = cif;
1533 	if_ref(ifp);
1534 	IF_ADDR_WUNLOCK(ifp);
1535 
1536 	return (cif);
1537 
1538 cleanup:
1539 	free(cif, M_CARP);
1540 
1541 	return (NULL);
1542 }
1543 
1544 static void
1545 carp_free_if(struct carp_if *cif)
1546 {
1547 	struct ifnet *ifp = cif->cif_ifp;
1548 
1549 	CIF_LOCK_ASSERT(cif);
1550 	KASSERT(TAILQ_EMPTY(&cif->cif_vrs), ("%s: softc list not empty",
1551 	    __func__));
1552 
1553 	IF_ADDR_WLOCK(ifp);
1554 	ifp->if_carp = NULL;
1555 	if_rele(ifp);
1556 	IF_ADDR_WUNLOCK(ifp);
1557 
1558 	CIF_LOCK_DESTROY(cif);
1559 
1560 	ifpromisc(ifp, 0);
1561 
1562 	free(cif, M_CARP);
1563 }
1564 
1565 static void
1566 carp_carprcp(struct carpreq *carpr, struct carp_softc *sc, int priv)
1567 {
1568 
1569 	CARP_LOCK(sc);
1570 	carpr->carpr_state = sc->sc_state;
1571 	carpr->carpr_vhid = sc->sc_vhid;
1572 	carpr->carpr_advbase = sc->sc_advbase;
1573 	carpr->carpr_advskew = sc->sc_advskew;
1574 	if (priv)
1575 		bcopy(sc->sc_key, carpr->carpr_key, sizeof(carpr->carpr_key));
1576 	else
1577 		bzero(carpr->carpr_key, sizeof(carpr->carpr_key));
1578 	CARP_UNLOCK(sc);
1579 }
1580 
1581 int
1582 carp_ioctl(struct ifreq *ifr, u_long cmd, struct thread *td)
1583 {
1584 	struct carpreq carpr;
1585 	struct ifnet *ifp;
1586 	struct carp_softc *sc = NULL;
1587 	int error = 0, locked = 0;
1588 
1589 	if ((error = copyin(ifr->ifr_data, &carpr, sizeof carpr)))
1590 		return (error);
1591 
1592 	ifp = ifunit_ref(ifr->ifr_name);
1593 	if (ifp == NULL)
1594 		return (ENXIO);
1595 
1596 	switch (ifp->if_type) {
1597 	case IFT_ETHER:
1598 	case IFT_L2VLAN:
1599 	case IFT_FDDI:
1600 	case IFT_ISO88025:
1601 		break;
1602 	default:
1603 		error = EOPNOTSUPP;
1604 		goto out;
1605 	}
1606 
1607 	if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1608 		error = EADDRNOTAVAIL;
1609 		goto out;
1610 	}
1611 
1612 	switch (cmd) {
1613 	case SIOCSVH:
1614 		if ((error = priv_check(td, PRIV_NETINET_CARP)))
1615 			break;
1616 		if (carpr.carpr_vhid <= 0 || carpr.carpr_vhid > CARP_MAXVHID ||
1617 		    carpr.carpr_advbase < 0 || carpr.carpr_advskew < 0) {
1618 			error = EINVAL;
1619 			break;
1620 		}
1621 
1622 		if (ifp->if_carp) {
1623 			CIF_LOCK(ifp->if_carp);
1624 			IFNET_FOREACH_CARP(ifp, sc)
1625 				if (sc->sc_vhid == carpr.carpr_vhid)
1626 					break;
1627 			CIF_UNLOCK(ifp->if_carp);
1628 		}
1629 		if (sc == NULL) {
1630 			sc = carp_alloc(ifp);
1631 			if (sc == NULL) {
1632 				error = EINVAL; /* XXX: ifpromisc failed */
1633 				break;
1634 			}
1635 
1636 			CARP_LOCK(sc);
1637 			sc->sc_vhid = carpr.carpr_vhid;
1638 			LLADDR(&sc->sc_addr)[0] = 0;
1639 			LLADDR(&sc->sc_addr)[1] = 0;
1640 			LLADDR(&sc->sc_addr)[2] = 0x5e;
1641 			LLADDR(&sc->sc_addr)[3] = 0;
1642 			LLADDR(&sc->sc_addr)[4] = 1;
1643 			LLADDR(&sc->sc_addr)[5] = sc->sc_vhid;
1644 		} else
1645 			CARP_LOCK(sc);
1646 		locked = 1;
1647 		if (carpr.carpr_advbase > 0) {
1648 			if (carpr.carpr_advbase > 255 ||
1649 			    carpr.carpr_advbase < CARP_DFLTINTV) {
1650 				error = EINVAL;
1651 				break;
1652 			}
1653 			sc->sc_advbase = carpr.carpr_advbase;
1654 		}
1655 		if (carpr.carpr_advskew > 0) {
1656 			if (carpr.carpr_advskew >= 255) {
1657 				error = EINVAL;
1658 				break;
1659 			}
1660 			sc->sc_advskew = carpr.carpr_advskew;
1661 		}
1662 		if (carpr.carpr_key[0] != '\0') {
1663 			bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1664 			carp_hmac_prepare(sc);
1665 		}
1666 		if (sc->sc_state != INIT &&
1667 		    carpr.carpr_state != sc->sc_state) {
1668 			switch (carpr.carpr_state) {
1669 			case BACKUP:
1670 				callout_stop(&sc->sc_ad_tmo);
1671 				carp_set_state(sc, BACKUP);
1672 				carp_setrun(sc, 0);
1673 				carp_delroute(sc);
1674 				break;
1675 			case MASTER:
1676 				carp_master_down_locked(sc);
1677 				break;
1678 			default:
1679 				break;
1680 			}
1681 		}
1682 		break;
1683 
1684 	case SIOCGVH:
1685 	    {
1686 		int priveleged;
1687 
1688 		if (carpr.carpr_vhid < 0 || carpr.carpr_vhid > CARP_MAXVHID) {
1689 			error = EINVAL;
1690 			break;
1691 		}
1692 		if (carpr.carpr_count < 1) {
1693 			error = EMSGSIZE;
1694 			break;
1695 		}
1696 		if (ifp->if_carp == NULL) {
1697 			error = ENOENT;
1698 			break;
1699 		}
1700 
1701 		priveleged = (priv_check(td, PRIV_NETINET_CARP) == 0);
1702 		if (carpr.carpr_vhid != 0) {
1703 			CIF_LOCK(ifp->if_carp);
1704 			IFNET_FOREACH_CARP(ifp, sc)
1705 				if (sc->sc_vhid == carpr.carpr_vhid)
1706 					break;
1707 			CIF_UNLOCK(ifp->if_carp);
1708 			if (sc == NULL) {
1709 				error = ENOENT;
1710 				break;
1711 			}
1712 			carp_carprcp(&carpr, sc, priveleged);
1713 			error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
1714 		} else  {
1715 			int i, count;
1716 
1717 			count = 0;
1718 			CIF_LOCK(ifp->if_carp);
1719 			IFNET_FOREACH_CARP(ifp, sc)
1720 				count++;
1721 
1722 			if (count > carpr.carpr_count) {
1723 				CIF_UNLOCK(ifp->if_carp);
1724 				error = EMSGSIZE;
1725 				break;
1726 			}
1727 
1728 			i = 0;
1729 			IFNET_FOREACH_CARP(ifp, sc) {
1730 				carp_carprcp(&carpr, sc, priveleged);
1731 				carpr.carpr_count = count;
1732 				error = copyout(&carpr, ifr->ifr_data +
1733 				    (i * sizeof(carpr)), sizeof(carpr));
1734 				if (error) {
1735 					CIF_UNLOCK(ifp->if_carp);
1736 					break;
1737 				}
1738 				i++;
1739 			}
1740 			CIF_UNLOCK(ifp->if_carp);
1741 		}
1742 		break;
1743 	    }
1744 	default:
1745 		error = EINVAL;
1746 	}
1747 
1748 out:
1749 	if (locked)
1750 		CARP_UNLOCK(sc);
1751 	if_rele(ifp);
1752 
1753 	return (error);
1754 }
1755 
1756 static int
1757 carp_get_vhid(struct ifaddr *ifa)
1758 {
1759 
1760 	if (ifa == NULL || ifa->ifa_carp == NULL)
1761 		return (0);
1762 
1763 	return (ifa->ifa_carp->sc_vhid);
1764 }
1765 
1766 int
1767 carp_attach(struct ifaddr *ifa, int vhid)
1768 {
1769 	struct ifnet *ifp = ifa->ifa_ifp;
1770 	struct carp_softc *sc;
1771 	int index, error;
1772 
1773 	if (ifp->if_carp == NULL)
1774 		return (ENOPROTOOPT);
1775 
1776 	switch (ifa->ifa_addr->sa_family) {
1777 #ifdef INET
1778 	case AF_INET:
1779 #endif
1780 #ifdef INET6
1781 	case AF_INET6:
1782 #endif
1783 		break;
1784 	default:
1785 		return (EPROTOTYPE);
1786 	}
1787 
1788 	CIF_LOCK(ifp->if_carp);
1789 	IFNET_FOREACH_CARP(ifp, sc)
1790 		if (sc->sc_vhid == vhid)
1791 			break;
1792 	CIF_UNLOCK(ifp->if_carp);
1793 	if (sc == NULL)
1794 		return (ENOENT);
1795 
1796 	if (ifa->ifa_carp) {
1797 		if (ifa->ifa_carp->sc_vhid != vhid)
1798 			carp_detach(ifa);
1799 		else
1800 			return (0);
1801 	}
1802 
1803 	error = carp_multicast_setup(sc, ifa->ifa_addr->sa_family);
1804 	if (error)
1805 		return (error);
1806 
1807 	CARP_LOCK(sc);
1808 	index = sc->sc_naddrs + sc->sc_naddrs6 + 1;
1809 	if (index > sc->sc_ifasiz / sizeof(struct ifaddr *))
1810 		if ((error = carp_grow_ifas(sc)) != 0) {
1811 			carp_multicast_cleanup(sc,
1812 			    ifa->ifa_addr->sa_family);
1813 			CARP_UNLOCK(sc);
1814 			return (error);
1815 		}
1816 
1817 	switch (ifa->ifa_addr->sa_family) {
1818 #ifdef INET
1819 	case AF_INET:
1820 		sc->sc_naddrs++;
1821 		break;
1822 #endif
1823 #ifdef INET6
1824 	case AF_INET6:
1825 		sc->sc_naddrs6++;
1826 		break;
1827 #endif
1828 	}
1829 
1830 	ifa_ref(ifa);
1831 	sc->sc_ifas[index - 1] = ifa;
1832 	ifa->ifa_carp = sc;
1833 
1834 	carp_hmac_prepare(sc);
1835 	carp_sc_state(sc);
1836 
1837 	CARP_UNLOCK(sc);
1838 
1839 	return (0);
1840 }
1841 
1842 void
1843 carp_detach(struct ifaddr *ifa)
1844 {
1845 	struct carp_softc *sc = ifa->ifa_carp;
1846 	int i, index;
1847 
1848 	KASSERT(sc != NULL, ("%s: %p not attached", __func__, ifa));
1849 
1850 	CARP_LOCK(sc);
1851 
1852 	/* Shift array. */
1853 	index = sc->sc_naddrs + sc->sc_naddrs6;
1854 	for (i = 0; i < index; i++)
1855 		if (sc->sc_ifas[i] == ifa)
1856 			break;
1857 	KASSERT(i < index, ("%s: %p no backref", __func__, ifa));
1858 	for (; i < index - 1; i++)
1859 		sc->sc_ifas[i] = sc->sc_ifas[i+1];
1860 	sc->sc_ifas[index - 1] = NULL;
1861 
1862 	switch (ifa->ifa_addr->sa_family) {
1863 #ifdef INET
1864 	case AF_INET:
1865 		sc->sc_naddrs--;
1866 		break;
1867 #endif
1868 #ifdef INET6
1869 	case AF_INET6:
1870 		sc->sc_naddrs6--;
1871 		break;
1872 #endif
1873 	}
1874 
1875 	carp_ifa_delroute(ifa);
1876 	carp_multicast_cleanup(sc, ifa->ifa_addr->sa_family);
1877 
1878 	ifa->ifa_carp = NULL;
1879 	ifa_free(ifa);
1880 
1881 	carp_hmac_prepare(sc);
1882 	carp_sc_state(sc);
1883 
1884 	if (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0) {
1885 		CARP_UNLOCK(sc);
1886 		carp_destroy(sc);
1887 	} else
1888 		CARP_UNLOCK(sc);
1889 }
1890 
1891 static void
1892 carp_set_state(struct carp_softc *sc, int state)
1893 {
1894 
1895 	CARP_LOCK_ASSERT(sc);
1896 
1897 	if (sc->sc_state != state) {
1898 		const char *carp_states[] = { CARP_STATES };
1899 		char subsys[IFNAMSIZ+5];
1900 
1901 		sc->sc_state = state;
1902 
1903 		snprintf(subsys, IFNAMSIZ+5, "%u@%s", sc->sc_vhid,
1904 		    sc->sc_carpdev->if_xname);
1905 		devctl_notify("CARP", subsys, carp_states[state], NULL);
1906 	}
1907 }
1908 
1909 static void
1910 carp_linkstate(struct ifnet *ifp)
1911 {
1912 	struct carp_softc *sc;
1913 
1914 	CIF_LOCK(ifp->if_carp);
1915 	IFNET_FOREACH_CARP(ifp, sc) {
1916 		CARP_LOCK(sc);
1917 		carp_sc_state(sc);
1918 		CARP_UNLOCK(sc);
1919 	}
1920 	CIF_UNLOCK(ifp->if_carp);
1921 }
1922 
1923 static void
1924 carp_sc_state(struct carp_softc *sc)
1925 {
1926 
1927 	CARP_LOCK_ASSERT(sc);
1928 
1929 	if (sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1930 	    !(sc->sc_carpdev->if_flags & IFF_UP)) {
1931 		callout_stop(&sc->sc_ad_tmo);
1932 #ifdef INET
1933 		callout_stop(&sc->sc_md_tmo);
1934 #endif
1935 #ifdef INET6
1936 		callout_stop(&sc->sc_md6_tmo);
1937 #endif
1938 		carp_set_state(sc, INIT);
1939 		carp_setrun(sc, 0);
1940 		if (!sc->sc_suppress)
1941 			carp_demote_adj(carp_ifdown_adj, "interface down");
1942 		sc->sc_suppress = 1;
1943 	} else {
1944 		carp_set_state(sc, INIT);
1945 		carp_setrun(sc, 0);
1946 		if (sc->sc_suppress)
1947 			carp_demote_adj(-carp_ifdown_adj, "interface up");
1948 		sc->sc_suppress = 0;
1949 	}
1950 }
1951 
1952 static void
1953 carp_demote_adj(int adj, char *reason)
1954 {
1955 	carp_demotion += adj;
1956 	CARP_LOG("demoted by %d to %d (%s)\n", adj, carp_demotion, reason);
1957 	taskqueue_enqueue(taskqueue_swi, &carp_sendall_task);
1958 }
1959 
1960 #ifdef INET
1961 extern  struct domain inetdomain;
1962 static struct protosw in_carp_protosw = {
1963 	.pr_type =		SOCK_RAW,
1964 	.pr_domain =		&inetdomain,
1965 	.pr_protocol =		IPPROTO_CARP,
1966 	.pr_flags =		PR_ATOMIC|PR_ADDR,
1967 	.pr_input =		carp_input,
1968 	.pr_output =		(pr_output_t *)rip_output,
1969 	.pr_ctloutput =		rip_ctloutput,
1970 	.pr_usrreqs =		&rip_usrreqs
1971 };
1972 #endif
1973 
1974 #ifdef INET6
1975 extern	struct domain inet6domain;
1976 static struct ip6protosw in6_carp_protosw = {
1977 	.pr_type =		SOCK_RAW,
1978 	.pr_domain =		&inet6domain,
1979 	.pr_protocol =		IPPROTO_CARP,
1980 	.pr_flags =		PR_ATOMIC|PR_ADDR,
1981 	.pr_input =		carp6_input,
1982 	.pr_output =		rip6_output,
1983 	.pr_ctloutput =		rip6_ctloutput,
1984 	.pr_usrreqs =		&rip6_usrreqs
1985 };
1986 #endif
1987 
1988 static void
1989 carp_mod_cleanup(void)
1990 {
1991 
1992 #ifdef INET
1993 	if (proto_reg[CARP_INET] == 0) {
1994 		(void)ipproto_unregister(IPPROTO_CARP);
1995 		pf_proto_unregister(PF_INET, IPPROTO_CARP, SOCK_RAW);
1996 		proto_reg[CARP_INET] = -1;
1997 	}
1998 	carp_iamatch_p = NULL;
1999 #endif
2000 #ifdef INET6
2001 	if (proto_reg[CARP_INET6] == 0) {
2002 		(void)ip6proto_unregister(IPPROTO_CARP);
2003 		pf_proto_unregister(PF_INET6, IPPROTO_CARP, SOCK_RAW);
2004 		proto_reg[CARP_INET6] = -1;
2005 	}
2006 	carp_iamatch6_p = NULL;
2007 	carp_macmatch6_p = NULL;
2008 #endif
2009 	carp_ioctl_p = NULL;
2010 	carp_attach_p = NULL;
2011 	carp_detach_p = NULL;
2012 	carp_get_vhid_p = NULL;
2013 	carp_linkstate_p = NULL;
2014 	carp_forus_p = NULL;
2015 	carp_output_p = NULL;
2016 	carp_demote_adj_p = NULL;
2017 	mtx_unlock(&carp_mtx);
2018 	taskqueue_drain(taskqueue_swi, &carp_sendall_task);
2019 	mtx_destroy(&carp_mtx);
2020 }
2021 
2022 static int
2023 carp_mod_load(void)
2024 {
2025 	int err;
2026 
2027 	mtx_init(&carp_mtx, "carp_mtx", NULL, MTX_DEF);
2028 	LIST_INIT(&carp_list);
2029 	carp_get_vhid_p = carp_get_vhid;
2030 	carp_forus_p = carp_forus;
2031 	carp_output_p = carp_output;
2032 	carp_linkstate_p = carp_linkstate;
2033 	carp_ioctl_p = carp_ioctl;
2034 	carp_attach_p = carp_attach;
2035 	carp_detach_p = carp_detach;
2036 	carp_demote_adj_p = carp_demote_adj;
2037 #ifdef INET6
2038 	carp_iamatch6_p = carp_iamatch6;
2039 	carp_macmatch6_p = carp_macmatch6;
2040 	proto_reg[CARP_INET6] = pf_proto_register(PF_INET6,
2041 	    (struct protosw *)&in6_carp_protosw);
2042 	if (proto_reg[CARP_INET6]) {
2043 		printf("carp: error %d attaching to PF_INET6\n",
2044 		    proto_reg[CARP_INET6]);
2045 		carp_mod_cleanup();
2046 		return (proto_reg[CARP_INET6]);
2047 	}
2048 	err = ip6proto_register(IPPROTO_CARP);
2049 	if (err) {
2050 		printf("carp: error %d registering with INET6\n", err);
2051 		carp_mod_cleanup();
2052 		return (err);
2053 	}
2054 #endif
2055 #ifdef INET
2056 	carp_iamatch_p = carp_iamatch;
2057 	proto_reg[CARP_INET] = pf_proto_register(PF_INET, &in_carp_protosw);
2058 	if (proto_reg[CARP_INET]) {
2059 		printf("carp: error %d attaching to PF_INET\n",
2060 		    proto_reg[CARP_INET]);
2061 		carp_mod_cleanup();
2062 		return (proto_reg[CARP_INET]);
2063 	}
2064 	err = ipproto_register(IPPROTO_CARP);
2065 	if (err) {
2066 		printf("carp: error %d registering with INET\n", err);
2067 		carp_mod_cleanup();
2068 		return (err);
2069 	}
2070 #endif
2071 	return (0);
2072 }
2073 
2074 static int
2075 carp_modevent(module_t mod, int type, void *data)
2076 {
2077 	switch (type) {
2078 	case MOD_LOAD:
2079 		return carp_mod_load();
2080 		/* NOTREACHED */
2081 	case MOD_UNLOAD:
2082 		mtx_lock(&carp_mtx);
2083 		if (LIST_EMPTY(&carp_list))
2084 			carp_mod_cleanup();
2085 		else {
2086 			mtx_unlock(&carp_mtx);
2087 			return (EBUSY);
2088 		}
2089 		break;
2090 
2091 	default:
2092 		return (EINVAL);
2093 	}
2094 
2095 	return (0);
2096 }
2097 
2098 static moduledata_t carp_mod = {
2099 	"carp",
2100 	carp_modevent,
2101 	0
2102 };
2103 
2104 DECLARE_MODULE(carp, carp_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
2105