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