xref: /freebsd/sys/netinet/ip_carp.c (revision 0b3105a37d7adcadcb720112fed4dc4e8040be99)
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 	struct in_addr addr;
1013 
1014 	CARP_FOREACH_IFA(sc, ifa) {
1015 		if (ifa->ifa_addr->sa_family != AF_INET)
1016 			continue;
1017 		addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1018 		arp_announce_ifaddr(sc->sc_carpdev, addr, LLADDR(&sc->sc_addr));
1019 	}
1020 }
1021 
1022 int
1023 carp_iamatch(struct ifaddr *ifa, uint8_t **enaddr)
1024 {
1025 	struct carp_softc *sc = ifa->ifa_carp;
1026 
1027 	if (sc->sc_state == MASTER) {
1028 		*enaddr = LLADDR(&sc->sc_addr);
1029 		return (1);
1030 	}
1031 
1032 	return (0);
1033 }
1034 #endif
1035 
1036 #ifdef INET6
1037 static void
1038 carp_send_na(struct carp_softc *sc)
1039 {
1040 	static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1041 	struct ifaddr *ifa;
1042 	struct in6_addr *in6;
1043 
1044 	CARP_FOREACH_IFA(sc, ifa) {
1045 		if (ifa->ifa_addr->sa_family != AF_INET6)
1046 			continue;
1047 
1048 		in6 = IFA_IN6(ifa);
1049 		nd6_na_output(sc->sc_carpdev, &mcast, in6,
1050 		    ND_NA_FLAG_OVERRIDE, 1, NULL);
1051 		DELAY(1000);	/* XXX */
1052 	}
1053 }
1054 
1055 /*
1056  * Returns ifa in case it's a carp address and it is MASTER, or if the address
1057  * matches and is not a carp address.  Returns NULL otherwise.
1058  */
1059 struct ifaddr *
1060 carp_iamatch6(struct ifnet *ifp, struct in6_addr *taddr)
1061 {
1062 	struct ifaddr *ifa;
1063 
1064 	ifa = NULL;
1065 	IF_ADDR_RLOCK(ifp);
1066 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1067 		if (ifa->ifa_addr->sa_family != AF_INET6)
1068 			continue;
1069 		if (!IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa)))
1070 			continue;
1071 		if (ifa->ifa_carp && ifa->ifa_carp->sc_state != MASTER)
1072 			ifa = NULL;
1073 		else
1074 			ifa_ref(ifa);
1075 		break;
1076 	}
1077 	IF_ADDR_RUNLOCK(ifp);
1078 
1079 	return (ifa);
1080 }
1081 
1082 caddr_t
1083 carp_macmatch6(struct ifnet *ifp, struct mbuf *m, const struct in6_addr *taddr)
1084 {
1085 	struct ifaddr *ifa;
1086 
1087 	IF_ADDR_RLOCK(ifp);
1088 	IFNET_FOREACH_IFA(ifp, ifa)
1089 		if (ifa->ifa_addr->sa_family == AF_INET6 &&
1090 		    IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa))) {
1091 			struct carp_softc *sc = ifa->ifa_carp;
1092 			struct m_tag *mtag;
1093 
1094 			IF_ADDR_RUNLOCK(ifp);
1095 
1096 			mtag = m_tag_get(PACKET_TAG_CARP,
1097 			    sizeof(struct carp_softc *), M_NOWAIT);
1098 			if (mtag == NULL)
1099 				/* Better a bit than nothing. */
1100 				return (LLADDR(&sc->sc_addr));
1101 
1102 			bcopy(&sc, mtag + 1, sizeof(sc));
1103 			m_tag_prepend(m, mtag);
1104 
1105 			return (LLADDR(&sc->sc_addr));
1106 		}
1107 	IF_ADDR_RUNLOCK(ifp);
1108 
1109 	return (NULL);
1110 }
1111 #endif /* INET6 */
1112 
1113 int
1114 carp_forus(struct ifnet *ifp, u_char *dhost)
1115 {
1116 	struct carp_softc *sc;
1117 	uint8_t *ena = dhost;
1118 
1119 	if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1120 		return (0);
1121 
1122 	CIF_LOCK(ifp->if_carp);
1123 	IFNET_FOREACH_CARP(ifp, sc) {
1124 		CARP_LOCK(sc);
1125 		if (sc->sc_state == MASTER && !bcmp(dhost, LLADDR(&sc->sc_addr),
1126 		    ETHER_ADDR_LEN)) {
1127 			CARP_UNLOCK(sc);
1128 			CIF_UNLOCK(ifp->if_carp);
1129 			return (1);
1130 		}
1131 		CARP_UNLOCK(sc);
1132 	}
1133 	CIF_UNLOCK(ifp->if_carp);
1134 
1135 	return (0);
1136 }
1137 
1138 /* Master down timeout event, executed in callout context. */
1139 static void
1140 carp_master_down(void *v)
1141 {
1142 	struct carp_softc *sc = v;
1143 
1144 	CARP_LOCK_ASSERT(sc);
1145 
1146 	CURVNET_SET(sc->sc_carpdev->if_vnet);
1147 	if (sc->sc_state == BACKUP) {
1148 		carp_master_down_locked(sc, "master timed out");
1149 	}
1150 	CURVNET_RESTORE();
1151 
1152 	CARP_UNLOCK(sc);
1153 }
1154 
1155 static void
1156 carp_master_down_locked(struct carp_softc *sc, const char *reason)
1157 {
1158 
1159 	CARP_LOCK_ASSERT(sc);
1160 
1161 	switch (sc->sc_state) {
1162 	case BACKUP:
1163 		carp_set_state(sc, MASTER, reason);
1164 		carp_send_ad_locked(sc);
1165 #ifdef INET
1166 		carp_send_arp(sc);
1167 #endif
1168 #ifdef INET6
1169 		carp_send_na(sc);
1170 #endif
1171 		carp_setrun(sc, 0);
1172 		carp_addroute(sc);
1173 		break;
1174 	case INIT:
1175 	case MASTER:
1176 #ifdef INVARIANTS
1177 		panic("carp: VHID %u@%s: master_down event in %s state\n",
1178 		    sc->sc_vhid,
1179 		    sc->sc_carpdev->if_xname,
1180 		    sc->sc_state ? "MASTER" : "INIT");
1181 #endif
1182 		break;
1183 	}
1184 }
1185 
1186 /*
1187  * When in backup state, af indicates whether to reset the master down timer
1188  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1189  */
1190 static void
1191 carp_setrun(struct carp_softc *sc, sa_family_t af)
1192 {
1193 	struct timeval tv;
1194 
1195 	CARP_LOCK_ASSERT(sc);
1196 
1197 	if ((sc->sc_carpdev->if_flags & IFF_UP) == 0 ||
1198 	    sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1199 	    (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0))
1200 		return;
1201 
1202 	switch (sc->sc_state) {
1203 	case INIT:
1204 		carp_set_state(sc, BACKUP, "initialization complete");
1205 		carp_setrun(sc, 0);
1206 		break;
1207 	case BACKUP:
1208 		callout_stop(&sc->sc_ad_tmo);
1209 		tv.tv_sec = 3 * sc->sc_advbase;
1210 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1211 		switch (af) {
1212 #ifdef INET
1213 		case AF_INET:
1214 			callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1215 			    carp_master_down, sc);
1216 			break;
1217 #endif
1218 #ifdef INET6
1219 		case AF_INET6:
1220 			callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1221 			    carp_master_down, sc);
1222 			break;
1223 #endif
1224 		default:
1225 #ifdef INET
1226 			if (sc->sc_naddrs)
1227 				callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1228 				    carp_master_down, sc);
1229 #endif
1230 #ifdef INET6
1231 			if (sc->sc_naddrs6)
1232 				callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1233 				    carp_master_down, sc);
1234 #endif
1235 			break;
1236 		}
1237 		break;
1238 	case MASTER:
1239 		tv.tv_sec = sc->sc_advbase;
1240 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1241 		callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1242 		    carp_send_ad, sc);
1243 		break;
1244 	}
1245 }
1246 
1247 /*
1248  * Setup multicast structures.
1249  */
1250 static int
1251 carp_multicast_setup(struct carp_if *cif, sa_family_t sa)
1252 {
1253 	struct ifnet *ifp = cif->cif_ifp;
1254 	int error = 0;
1255 
1256 	switch (sa) {
1257 #ifdef INET
1258 	case AF_INET:
1259 	    {
1260 		struct ip_moptions *imo = &cif->cif_imo;
1261 		struct in_addr addr;
1262 
1263 		if (imo->imo_membership)
1264 			return (0);
1265 
1266 		imo->imo_membership = (struct in_multi **)malloc(
1267 		    (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_CARP,
1268 		    M_WAITOK);
1269 		imo->imo_mfilters = NULL;
1270 		imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1271 		imo->imo_multicast_vif = -1;
1272 
1273 		addr.s_addr = htonl(INADDR_CARP_GROUP);
1274 		if ((error = in_joingroup(ifp, &addr, NULL,
1275 		    &imo->imo_membership[0])) != 0) {
1276 			free(imo->imo_membership, M_CARP);
1277 			break;
1278 		}
1279 		imo->imo_num_memberships++;
1280 		imo->imo_multicast_ifp = ifp;
1281 		imo->imo_multicast_ttl = CARP_DFLTTL;
1282 		imo->imo_multicast_loop = 0;
1283 		break;
1284 	   }
1285 #endif
1286 #ifdef INET6
1287 	case AF_INET6:
1288 	    {
1289 		struct ip6_moptions *im6o = &cif->cif_im6o;
1290 		struct in6_addr in6;
1291 		struct in6_multi *in6m;
1292 
1293 		if (im6o->im6o_membership)
1294 			return (0);
1295 
1296 		im6o->im6o_membership = (struct in6_multi **)malloc(
1297 		    (sizeof(struct in6_multi *) * IPV6_MIN_MEMBERSHIPS), M_CARP,
1298 		    M_ZERO | M_WAITOK);
1299 		im6o->im6o_mfilters = NULL;
1300 		im6o->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
1301 		im6o->im6o_multicast_hlim = CARP_DFLTTL;
1302 		im6o->im6o_multicast_ifp = ifp;
1303 
1304 		/* Join IPv6 CARP multicast group. */
1305 		bzero(&in6, sizeof(in6));
1306 		in6.s6_addr16[0] = htons(0xff02);
1307 		in6.s6_addr8[15] = 0x12;
1308 		if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1309 			free(im6o->im6o_membership, M_CARP);
1310 			break;
1311 		}
1312 		in6m = NULL;
1313 		if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1314 			free(im6o->im6o_membership, M_CARP);
1315 			break;
1316 		}
1317 		im6o->im6o_membership[0] = in6m;
1318 		im6o->im6o_num_memberships++;
1319 
1320 		/* Join solicited multicast address. */
1321 		bzero(&in6, sizeof(in6));
1322 		in6.s6_addr16[0] = htons(0xff02);
1323 		in6.s6_addr32[1] = 0;
1324 		in6.s6_addr32[2] = htonl(1);
1325 		in6.s6_addr32[3] = 0;
1326 		in6.s6_addr8[12] = 0xff;
1327 		if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1328 			in6_mc_leave(im6o->im6o_membership[0], NULL);
1329 			free(im6o->im6o_membership, M_CARP);
1330 			break;
1331 		}
1332 		in6m = NULL;
1333 		if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1334 			in6_mc_leave(im6o->im6o_membership[0], NULL);
1335 			free(im6o->im6o_membership, M_CARP);
1336 			break;
1337 		}
1338 		im6o->im6o_membership[1] = in6m;
1339 		im6o->im6o_num_memberships++;
1340 		break;
1341 	    }
1342 #endif
1343 	}
1344 
1345 	return (error);
1346 }
1347 
1348 /*
1349  * Free multicast structures.
1350  */
1351 static void
1352 carp_multicast_cleanup(struct carp_if *cif, sa_family_t sa)
1353 {
1354 
1355 	sx_assert(&carp_sx, SA_XLOCKED);
1356 
1357 	switch (sa) {
1358 #ifdef INET
1359 	case AF_INET:
1360 		if (cif->cif_naddrs == 0) {
1361 			struct ip_moptions *imo = &cif->cif_imo;
1362 
1363 			in_leavegroup(imo->imo_membership[0], NULL);
1364 			KASSERT(imo->imo_mfilters == NULL,
1365 			    ("%s: imo_mfilters != NULL", __func__));
1366 			free(imo->imo_membership, M_CARP);
1367 			imo->imo_membership = NULL;
1368 
1369 		}
1370 		break;
1371 #endif
1372 #ifdef INET6
1373 	case AF_INET6:
1374 		if (cif->cif_naddrs6 == 0) {
1375 			struct ip6_moptions *im6o = &cif->cif_im6o;
1376 
1377 			in6_mc_leave(im6o->im6o_membership[0], NULL);
1378 			in6_mc_leave(im6o->im6o_membership[1], NULL);
1379 			KASSERT(im6o->im6o_mfilters == NULL,
1380 			    ("%s: im6o_mfilters != NULL", __func__));
1381 			free(im6o->im6o_membership, M_CARP);
1382 			im6o->im6o_membership = NULL;
1383 		}
1384 		break;
1385 #endif
1386 	}
1387 }
1388 
1389 int
1390 carp_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *sa)
1391 {
1392 	struct m_tag *mtag;
1393 	struct carp_softc *sc;
1394 
1395 	if (!sa)
1396 		return (0);
1397 
1398 	switch (sa->sa_family) {
1399 #ifdef INET
1400 	case AF_INET:
1401 		break;
1402 #endif
1403 #ifdef INET6
1404 	case AF_INET6:
1405 		break;
1406 #endif
1407 	default:
1408 		return (0);
1409 	}
1410 
1411 	mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
1412 	if (mtag == NULL)
1413 		return (0);
1414 
1415 	bcopy(mtag + 1, &sc, sizeof(sc));
1416 
1417 	/* Set the source MAC address to the Virtual Router MAC Address. */
1418 	switch (ifp->if_type) {
1419 	case IFT_ETHER:
1420 	case IFT_BRIDGE:
1421 	case IFT_L2VLAN: {
1422 			struct ether_header *eh;
1423 
1424 			eh = mtod(m, struct ether_header *);
1425 			eh->ether_shost[0] = 0;
1426 			eh->ether_shost[1] = 0;
1427 			eh->ether_shost[2] = 0x5e;
1428 			eh->ether_shost[3] = 0;
1429 			eh->ether_shost[4] = 1;
1430 			eh->ether_shost[5] = sc->sc_vhid;
1431 		}
1432 		break;
1433 	case IFT_FDDI: {
1434 			struct fddi_header *fh;
1435 
1436 			fh = mtod(m, struct fddi_header *);
1437 			fh->fddi_shost[0] = 0;
1438 			fh->fddi_shost[1] = 0;
1439 			fh->fddi_shost[2] = 0x5e;
1440 			fh->fddi_shost[3] = 0;
1441 			fh->fddi_shost[4] = 1;
1442 			fh->fddi_shost[5] = sc->sc_vhid;
1443 		}
1444 		break;
1445 	case IFT_ISO88025: {
1446  			struct iso88025_header *th;
1447  			th = mtod(m, struct iso88025_header *);
1448 			th->iso88025_shost[0] = 3;
1449 			th->iso88025_shost[1] = 0;
1450 			th->iso88025_shost[2] = 0x40 >> (sc->sc_vhid - 1);
1451 			th->iso88025_shost[3] = 0x40000 >> (sc->sc_vhid - 1);
1452 			th->iso88025_shost[4] = 0;
1453 			th->iso88025_shost[5] = 0;
1454 		}
1455 		break;
1456 	default:
1457 		printf("%s: carp is not supported for the %d interface type\n",
1458 		    ifp->if_xname, ifp->if_type);
1459 		return (EOPNOTSUPP);
1460 	}
1461 
1462 	return (0);
1463 }
1464 
1465 static struct carp_softc*
1466 carp_alloc(struct ifnet *ifp)
1467 {
1468 	struct carp_softc *sc;
1469 	struct carp_if *cif;
1470 
1471 	if ((cif = ifp->if_carp) == NULL)
1472 		cif = carp_alloc_if(ifp);
1473 
1474 	sc = malloc(sizeof(*sc), M_CARP, M_WAITOK|M_ZERO);
1475 
1476 	sc->sc_advbase = CARP_DFLTINTV;
1477 	sc->sc_vhid = -1;	/* required setting */
1478 	sc->sc_init_counter = 1;
1479 	sc->sc_state = INIT;
1480 
1481 	sc->sc_ifasiz = sizeof(struct ifaddr *);
1482 	sc->sc_ifas = malloc(sc->sc_ifasiz, M_CARP, M_WAITOK|M_ZERO);
1483 	sc->sc_carpdev = ifp;
1484 
1485 	CARP_LOCK_INIT(sc);
1486 #ifdef INET
1487 	callout_init_mtx(&sc->sc_md_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1488 #endif
1489 #ifdef INET6
1490 	callout_init_mtx(&sc->sc_md6_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1491 #endif
1492 	callout_init_mtx(&sc->sc_ad_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1493 
1494 	CIF_LOCK(cif);
1495 	TAILQ_INSERT_TAIL(&cif->cif_vrs, sc, sc_list);
1496 	CIF_UNLOCK(cif);
1497 
1498 	mtx_lock(&carp_mtx);
1499 	LIST_INSERT_HEAD(&carp_list, sc, sc_next);
1500 	mtx_unlock(&carp_mtx);
1501 
1502 	return (sc);
1503 }
1504 
1505 static void
1506 carp_grow_ifas(struct carp_softc *sc)
1507 {
1508 	struct ifaddr **new;
1509 
1510 	new = malloc(sc->sc_ifasiz * 2, M_CARP, M_WAITOK | M_ZERO);
1511 	CARP_LOCK(sc);
1512 	bcopy(sc->sc_ifas, new, sc->sc_ifasiz);
1513 	free(sc->sc_ifas, M_CARP);
1514 	sc->sc_ifas = new;
1515 	sc->sc_ifasiz *= 2;
1516 	CARP_UNLOCK(sc);
1517 }
1518 
1519 static void
1520 carp_destroy(struct carp_softc *sc)
1521 {
1522 	struct ifnet *ifp = sc->sc_carpdev;
1523 	struct carp_if *cif = ifp->if_carp;
1524 
1525 	sx_assert(&carp_sx, SA_XLOCKED);
1526 
1527 	if (sc->sc_suppress)
1528 		carp_demote_adj(-V_carp_ifdown_adj, "vhid removed");
1529 	CARP_UNLOCK(sc);
1530 
1531 	CIF_LOCK(cif);
1532 	TAILQ_REMOVE(&cif->cif_vrs, sc, sc_list);
1533 	CIF_UNLOCK(cif);
1534 
1535 	mtx_lock(&carp_mtx);
1536 	LIST_REMOVE(sc, sc_next);
1537 	mtx_unlock(&carp_mtx);
1538 
1539 	callout_drain(&sc->sc_ad_tmo);
1540 #ifdef INET
1541 	callout_drain(&sc->sc_md_tmo);
1542 #endif
1543 #ifdef INET6
1544 	callout_drain(&sc->sc_md6_tmo);
1545 #endif
1546 	CARP_LOCK_DESTROY(sc);
1547 
1548 	free(sc->sc_ifas, M_CARP);
1549 	free(sc, M_CARP);
1550 }
1551 
1552 static struct carp_if*
1553 carp_alloc_if(struct ifnet *ifp)
1554 {
1555 	struct carp_if *cif;
1556 	int error;
1557 
1558 	cif = malloc(sizeof(*cif), M_CARP, M_WAITOK|M_ZERO);
1559 
1560 	if ((error = ifpromisc(ifp, 1)) != 0)
1561 		printf("%s: ifpromisc(%s) failed: %d\n",
1562 		    __func__, ifp->if_xname, error);
1563 	else
1564 		cif->cif_flags |= CIF_PROMISC;
1565 
1566 	CIF_LOCK_INIT(cif);
1567 	cif->cif_ifp = ifp;
1568 	TAILQ_INIT(&cif->cif_vrs);
1569 
1570 	IF_ADDR_WLOCK(ifp);
1571 	ifp->if_carp = cif;
1572 	if_ref(ifp);
1573 	IF_ADDR_WUNLOCK(ifp);
1574 
1575 	return (cif);
1576 }
1577 
1578 static void
1579 carp_free_if(struct carp_if *cif)
1580 {
1581 	struct ifnet *ifp = cif->cif_ifp;
1582 
1583 	CIF_LOCK_ASSERT(cif);
1584 	KASSERT(TAILQ_EMPTY(&cif->cif_vrs), ("%s: softc list not empty",
1585 	    __func__));
1586 
1587 	IF_ADDR_WLOCK(ifp);
1588 	ifp->if_carp = NULL;
1589 	IF_ADDR_WUNLOCK(ifp);
1590 
1591 	CIF_LOCK_DESTROY(cif);
1592 
1593 	if (cif->cif_flags & CIF_PROMISC)
1594 		ifpromisc(ifp, 0);
1595 	if_rele(ifp);
1596 
1597 	free(cif, M_CARP);
1598 }
1599 
1600 static void
1601 carp_carprcp(struct carpreq *carpr, struct carp_softc *sc, int priv)
1602 {
1603 
1604 	CARP_LOCK(sc);
1605 	carpr->carpr_state = sc->sc_state;
1606 	carpr->carpr_vhid = sc->sc_vhid;
1607 	carpr->carpr_advbase = sc->sc_advbase;
1608 	carpr->carpr_advskew = sc->sc_advskew;
1609 	if (priv)
1610 		bcopy(sc->sc_key, carpr->carpr_key, sizeof(carpr->carpr_key));
1611 	else
1612 		bzero(carpr->carpr_key, sizeof(carpr->carpr_key));
1613 	CARP_UNLOCK(sc);
1614 }
1615 
1616 int
1617 carp_ioctl(struct ifreq *ifr, u_long cmd, struct thread *td)
1618 {
1619 	struct carpreq carpr;
1620 	struct ifnet *ifp;
1621 	struct carp_softc *sc = NULL;
1622 	int error = 0, locked = 0;
1623 
1624 	if ((error = copyin(ifr->ifr_data, &carpr, sizeof carpr)))
1625 		return (error);
1626 
1627 	ifp = ifunit_ref(ifr->ifr_name);
1628 	if (ifp == NULL)
1629 		return (ENXIO);
1630 
1631 	switch (ifp->if_type) {
1632 	case IFT_ETHER:
1633 	case IFT_L2VLAN:
1634 	case IFT_BRIDGE:
1635 	case IFT_FDDI:
1636 	case IFT_ISO88025:
1637 		break;
1638 	default:
1639 		error = EOPNOTSUPP;
1640 		goto out;
1641 	}
1642 
1643 	if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1644 		error = EADDRNOTAVAIL;
1645 		goto out;
1646 	}
1647 
1648 	sx_xlock(&carp_sx);
1649 	switch (cmd) {
1650 	case SIOCSVH:
1651 		if ((error = priv_check(td, PRIV_NETINET_CARP)))
1652 			break;
1653 		if (carpr.carpr_vhid <= 0 || carpr.carpr_vhid > CARP_MAXVHID ||
1654 		    carpr.carpr_advbase < 0 || carpr.carpr_advskew < 0) {
1655 			error = EINVAL;
1656 			break;
1657 		}
1658 
1659 		if (ifp->if_carp) {
1660 			CIF_LOCK(ifp->if_carp);
1661 			IFNET_FOREACH_CARP(ifp, sc)
1662 				if (sc->sc_vhid == carpr.carpr_vhid)
1663 					break;
1664 			CIF_UNLOCK(ifp->if_carp);
1665 		}
1666 		if (sc == NULL) {
1667 			sc = carp_alloc(ifp);
1668 			CARP_LOCK(sc);
1669 			sc->sc_vhid = carpr.carpr_vhid;
1670 			LLADDR(&sc->sc_addr)[0] = 0;
1671 			LLADDR(&sc->sc_addr)[1] = 0;
1672 			LLADDR(&sc->sc_addr)[2] = 0x5e;
1673 			LLADDR(&sc->sc_addr)[3] = 0;
1674 			LLADDR(&sc->sc_addr)[4] = 1;
1675 			LLADDR(&sc->sc_addr)[5] = sc->sc_vhid;
1676 		} else
1677 			CARP_LOCK(sc);
1678 		locked = 1;
1679 		if (carpr.carpr_advbase > 0) {
1680 			if (carpr.carpr_advbase > 255 ||
1681 			    carpr.carpr_advbase < CARP_DFLTINTV) {
1682 				error = EINVAL;
1683 				break;
1684 			}
1685 			sc->sc_advbase = carpr.carpr_advbase;
1686 		}
1687 		if (carpr.carpr_advskew >= 255) {
1688 			error = EINVAL;
1689 			break;
1690 		}
1691 		sc->sc_advskew = carpr.carpr_advskew;
1692 		if (carpr.carpr_key[0] != '\0') {
1693 			bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1694 			carp_hmac_prepare(sc);
1695 		}
1696 		if (sc->sc_state != INIT &&
1697 		    carpr.carpr_state != sc->sc_state) {
1698 			switch (carpr.carpr_state) {
1699 			case BACKUP:
1700 				callout_stop(&sc->sc_ad_tmo);
1701 				carp_set_state(sc, BACKUP,
1702 				    "user requested via ifconfig");
1703 				carp_setrun(sc, 0);
1704 				carp_delroute(sc);
1705 				break;
1706 			case MASTER:
1707 				carp_master_down_locked(sc,
1708 				    "user requested via ifconfig");
1709 				break;
1710 			default:
1711 				break;
1712 			}
1713 		}
1714 		break;
1715 
1716 	case SIOCGVH:
1717 	    {
1718 		int priveleged;
1719 
1720 		if (carpr.carpr_vhid < 0 || carpr.carpr_vhid > CARP_MAXVHID) {
1721 			error = EINVAL;
1722 			break;
1723 		}
1724 		if (carpr.carpr_count < 1) {
1725 			error = EMSGSIZE;
1726 			break;
1727 		}
1728 		if (ifp->if_carp == NULL) {
1729 			error = ENOENT;
1730 			break;
1731 		}
1732 
1733 		priveleged = (priv_check(td, PRIV_NETINET_CARP) == 0);
1734 		if (carpr.carpr_vhid != 0) {
1735 			CIF_LOCK(ifp->if_carp);
1736 			IFNET_FOREACH_CARP(ifp, sc)
1737 				if (sc->sc_vhid == carpr.carpr_vhid)
1738 					break;
1739 			CIF_UNLOCK(ifp->if_carp);
1740 			if (sc == NULL) {
1741 				error = ENOENT;
1742 				break;
1743 			}
1744 			carp_carprcp(&carpr, sc, priveleged);
1745 			error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
1746 		} else  {
1747 			int i, count;
1748 
1749 			count = 0;
1750 			CIF_LOCK(ifp->if_carp);
1751 			IFNET_FOREACH_CARP(ifp, sc)
1752 				count++;
1753 
1754 			if (count > carpr.carpr_count) {
1755 				CIF_UNLOCK(ifp->if_carp);
1756 				error = EMSGSIZE;
1757 				break;
1758 			}
1759 
1760 			i = 0;
1761 			IFNET_FOREACH_CARP(ifp, sc) {
1762 				carp_carprcp(&carpr, sc, priveleged);
1763 				carpr.carpr_count = count;
1764 				error = copyout(&carpr, ifr->ifr_data +
1765 				    (i * sizeof(carpr)), sizeof(carpr));
1766 				if (error) {
1767 					CIF_UNLOCK(ifp->if_carp);
1768 					break;
1769 				}
1770 				i++;
1771 			}
1772 			CIF_UNLOCK(ifp->if_carp);
1773 		}
1774 		break;
1775 	    }
1776 	default:
1777 		error = EINVAL;
1778 	}
1779 	sx_xunlock(&carp_sx);
1780 
1781 out:
1782 	if (locked)
1783 		CARP_UNLOCK(sc);
1784 	if_rele(ifp);
1785 
1786 	return (error);
1787 }
1788 
1789 static int
1790 carp_get_vhid(struct ifaddr *ifa)
1791 {
1792 
1793 	if (ifa == NULL || ifa->ifa_carp == NULL)
1794 		return (0);
1795 
1796 	return (ifa->ifa_carp->sc_vhid);
1797 }
1798 
1799 int
1800 carp_attach(struct ifaddr *ifa, int vhid)
1801 {
1802 	struct ifnet *ifp = ifa->ifa_ifp;
1803 	struct carp_if *cif = ifp->if_carp;
1804 	struct carp_softc *sc;
1805 	int index, error;
1806 
1807 	KASSERT(ifa->ifa_carp == NULL, ("%s: ifa %p attached", __func__, ifa));
1808 
1809 	switch (ifa->ifa_addr->sa_family) {
1810 #ifdef INET
1811 	case AF_INET:
1812 #endif
1813 #ifdef INET6
1814 	case AF_INET6:
1815 #endif
1816 		break;
1817 	default:
1818 		return (EPROTOTYPE);
1819 	}
1820 
1821 	sx_xlock(&carp_sx);
1822 	if (ifp->if_carp == NULL) {
1823 		sx_xunlock(&carp_sx);
1824 		return (ENOPROTOOPT);
1825 	}
1826 
1827 	CIF_LOCK(cif);
1828 	IFNET_FOREACH_CARP(ifp, sc)
1829 		if (sc->sc_vhid == vhid)
1830 			break;
1831 	CIF_UNLOCK(cif);
1832 	if (sc == NULL) {
1833 		sx_xunlock(&carp_sx);
1834 		return (ENOENT);
1835 	}
1836 
1837 	error = carp_multicast_setup(cif, ifa->ifa_addr->sa_family);
1838 	if (error) {
1839 		CIF_FREE(cif);
1840 		sx_xunlock(&carp_sx);
1841 		return (error);
1842 	}
1843 
1844 	index = sc->sc_naddrs + sc->sc_naddrs6 + 1;
1845 	if (index > sc->sc_ifasiz / sizeof(struct ifaddr *))
1846 		carp_grow_ifas(sc);
1847 
1848 	switch (ifa->ifa_addr->sa_family) {
1849 #ifdef INET
1850 	case AF_INET:
1851 		cif->cif_naddrs++;
1852 		sc->sc_naddrs++;
1853 		break;
1854 #endif
1855 #ifdef INET6
1856 	case AF_INET6:
1857 		cif->cif_naddrs6++;
1858 		sc->sc_naddrs6++;
1859 		break;
1860 #endif
1861 	}
1862 
1863 	ifa_ref(ifa);
1864 
1865 	CARP_LOCK(sc);
1866 	sc->sc_ifas[index - 1] = ifa;
1867 	ifa->ifa_carp = sc;
1868 	carp_hmac_prepare(sc);
1869 	carp_sc_state(sc);
1870 	CARP_UNLOCK(sc);
1871 
1872 	sx_xunlock(&carp_sx);
1873 
1874 	return (0);
1875 }
1876 
1877 void
1878 carp_detach(struct ifaddr *ifa)
1879 {
1880 	struct ifnet *ifp = ifa->ifa_ifp;
1881 	struct carp_if *cif = ifp->if_carp;
1882 	struct carp_softc *sc = ifa->ifa_carp;
1883 	int i, index;
1884 
1885 	KASSERT(sc != NULL, ("%s: %p not attached", __func__, ifa));
1886 
1887 	sx_xlock(&carp_sx);
1888 
1889 	CARP_LOCK(sc);
1890 	/* Shift array. */
1891 	index = sc->sc_naddrs + sc->sc_naddrs6;
1892 	for (i = 0; i < index; i++)
1893 		if (sc->sc_ifas[i] == ifa)
1894 			break;
1895 	KASSERT(i < index, ("%s: %p no backref", __func__, ifa));
1896 	for (; i < index - 1; i++)
1897 		sc->sc_ifas[i] = sc->sc_ifas[i+1];
1898 	sc->sc_ifas[index - 1] = NULL;
1899 
1900 	switch (ifa->ifa_addr->sa_family) {
1901 #ifdef INET
1902 	case AF_INET:
1903 		cif->cif_naddrs--;
1904 		sc->sc_naddrs--;
1905 		break;
1906 #endif
1907 #ifdef INET6
1908 	case AF_INET6:
1909 		cif->cif_naddrs6--;
1910 		sc->sc_naddrs6--;
1911 		break;
1912 #endif
1913 	}
1914 
1915 	carp_ifa_delroute(ifa);
1916 	carp_multicast_cleanup(cif, ifa->ifa_addr->sa_family);
1917 
1918 	ifa->ifa_carp = NULL;
1919 	ifa_free(ifa);
1920 
1921 	carp_hmac_prepare(sc);
1922 	carp_sc_state(sc);
1923 
1924 	if (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0)
1925 		carp_destroy(sc);
1926 	else
1927 		CARP_UNLOCK(sc);
1928 
1929 	CIF_FREE(cif);
1930 
1931 	sx_xunlock(&carp_sx);
1932 }
1933 
1934 static void
1935 carp_set_state(struct carp_softc *sc, int state, const char *reason)
1936 {
1937 
1938 	CARP_LOCK_ASSERT(sc);
1939 
1940 	if (sc->sc_state != state) {
1941 		const char *carp_states[] = { CARP_STATES };
1942 		char subsys[IFNAMSIZ+5];
1943 
1944 		snprintf(subsys, IFNAMSIZ+5, "%u@%s", sc->sc_vhid,
1945 		    sc->sc_carpdev->if_xname);
1946 
1947 		CARP_LOG("%s: %s -> %s (%s)\n", subsys,
1948 		    carp_states[sc->sc_state], carp_states[state], reason);
1949 
1950 		sc->sc_state = state;
1951 
1952 		devctl_notify("CARP", subsys, carp_states[state], NULL);
1953 	}
1954 }
1955 
1956 static void
1957 carp_linkstate(struct ifnet *ifp)
1958 {
1959 	struct carp_softc *sc;
1960 
1961 	CIF_LOCK(ifp->if_carp);
1962 	IFNET_FOREACH_CARP(ifp, sc) {
1963 		CARP_LOCK(sc);
1964 		carp_sc_state(sc);
1965 		CARP_UNLOCK(sc);
1966 	}
1967 	CIF_UNLOCK(ifp->if_carp);
1968 }
1969 
1970 static void
1971 carp_sc_state(struct carp_softc *sc)
1972 {
1973 
1974 	CARP_LOCK_ASSERT(sc);
1975 
1976 	if (sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1977 	    !(sc->sc_carpdev->if_flags & IFF_UP)) {
1978 		callout_stop(&sc->sc_ad_tmo);
1979 #ifdef INET
1980 		callout_stop(&sc->sc_md_tmo);
1981 #endif
1982 #ifdef INET6
1983 		callout_stop(&sc->sc_md6_tmo);
1984 #endif
1985 		carp_set_state(sc, INIT, "hardware interface down");
1986 		carp_setrun(sc, 0);
1987 		if (!sc->sc_suppress)
1988 			carp_demote_adj(V_carp_ifdown_adj, "interface down");
1989 		sc->sc_suppress = 1;
1990 	} else {
1991 		carp_set_state(sc, INIT, "hardware interface up");
1992 		carp_setrun(sc, 0);
1993 		if (sc->sc_suppress)
1994 			carp_demote_adj(-V_carp_ifdown_adj, "interface up");
1995 		sc->sc_suppress = 0;
1996 	}
1997 }
1998 
1999 static void
2000 carp_demote_adj(int adj, char *reason)
2001 {
2002 	atomic_add_int(&V_carp_demotion, adj);
2003 	CARP_LOG("demoted by %d to %d (%s)\n", adj, V_carp_demotion, reason);
2004 	taskqueue_enqueue(taskqueue_swi, &carp_sendall_task);
2005 }
2006 
2007 static int
2008 carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS)
2009 {
2010 	int new, error;
2011 
2012 	new = V_carp_demotion;
2013 	error = sysctl_handle_int(oidp, &new, 0, req);
2014 	if (error || !req->newptr)
2015 		return (error);
2016 
2017 	carp_demote_adj(new, "sysctl");
2018 
2019 	return (0);
2020 }
2021 
2022 #ifdef INET
2023 extern  struct domain inetdomain;
2024 static struct protosw in_carp_protosw = {
2025 	.pr_type =		SOCK_RAW,
2026 	.pr_domain =		&inetdomain,
2027 	.pr_protocol =		IPPROTO_CARP,
2028 	.pr_flags =		PR_ATOMIC|PR_ADDR,
2029 	.pr_input =		carp_input,
2030 	.pr_output =		rip_output,
2031 	.pr_ctloutput =		rip_ctloutput,
2032 	.pr_usrreqs =		&rip_usrreqs
2033 };
2034 #endif
2035 
2036 #ifdef INET6
2037 extern	struct domain inet6domain;
2038 static struct protosw in6_carp_protosw = {
2039 	.pr_type =		SOCK_RAW,
2040 	.pr_domain =		&inet6domain,
2041 	.pr_protocol =		IPPROTO_CARP,
2042 	.pr_flags =		PR_ATOMIC|PR_ADDR,
2043 	.pr_input =		carp6_input,
2044 	.pr_output =		rip6_output,
2045 	.pr_ctloutput =		rip6_ctloutput,
2046 	.pr_usrreqs =		&rip6_usrreqs
2047 };
2048 #endif
2049 
2050 static void
2051 carp_mod_cleanup(void)
2052 {
2053 
2054 #ifdef INET
2055 	if (proto_reg[CARP_INET] == 0) {
2056 		(void)ipproto_unregister(IPPROTO_CARP);
2057 		pf_proto_unregister(PF_INET, IPPROTO_CARP, SOCK_RAW);
2058 		proto_reg[CARP_INET] = -1;
2059 	}
2060 	carp_iamatch_p = NULL;
2061 #endif
2062 #ifdef INET6
2063 	if (proto_reg[CARP_INET6] == 0) {
2064 		(void)ip6proto_unregister(IPPROTO_CARP);
2065 		pf_proto_unregister(PF_INET6, IPPROTO_CARP, SOCK_RAW);
2066 		proto_reg[CARP_INET6] = -1;
2067 	}
2068 	carp_iamatch6_p = NULL;
2069 	carp_macmatch6_p = NULL;
2070 #endif
2071 	carp_ioctl_p = NULL;
2072 	carp_attach_p = NULL;
2073 	carp_detach_p = NULL;
2074 	carp_get_vhid_p = NULL;
2075 	carp_linkstate_p = NULL;
2076 	carp_forus_p = NULL;
2077 	carp_output_p = NULL;
2078 	carp_demote_adj_p = NULL;
2079 	carp_master_p = NULL;
2080 	mtx_unlock(&carp_mtx);
2081 	taskqueue_drain(taskqueue_swi, &carp_sendall_task);
2082 	mtx_destroy(&carp_mtx);
2083 	sx_destroy(&carp_sx);
2084 }
2085 
2086 static int
2087 carp_mod_load(void)
2088 {
2089 	int err;
2090 
2091 	mtx_init(&carp_mtx, "carp_mtx", NULL, MTX_DEF);
2092 	sx_init(&carp_sx, "carp_sx");
2093 	LIST_INIT(&carp_list);
2094 	carp_get_vhid_p = carp_get_vhid;
2095 	carp_forus_p = carp_forus;
2096 	carp_output_p = carp_output;
2097 	carp_linkstate_p = carp_linkstate;
2098 	carp_ioctl_p = carp_ioctl;
2099 	carp_attach_p = carp_attach;
2100 	carp_detach_p = carp_detach;
2101 	carp_demote_adj_p = carp_demote_adj;
2102 	carp_master_p = carp_master;
2103 #ifdef INET6
2104 	carp_iamatch6_p = carp_iamatch6;
2105 	carp_macmatch6_p = carp_macmatch6;
2106 	proto_reg[CARP_INET6] = pf_proto_register(PF_INET6,
2107 	    (struct protosw *)&in6_carp_protosw);
2108 	if (proto_reg[CARP_INET6]) {
2109 		printf("carp: error %d attaching to PF_INET6\n",
2110 		    proto_reg[CARP_INET6]);
2111 		carp_mod_cleanup();
2112 		return (proto_reg[CARP_INET6]);
2113 	}
2114 	err = ip6proto_register(IPPROTO_CARP);
2115 	if (err) {
2116 		printf("carp: error %d registering with INET6\n", err);
2117 		carp_mod_cleanup();
2118 		return (err);
2119 	}
2120 #endif
2121 #ifdef INET
2122 	carp_iamatch_p = carp_iamatch;
2123 	proto_reg[CARP_INET] = pf_proto_register(PF_INET, &in_carp_protosw);
2124 	if (proto_reg[CARP_INET]) {
2125 		printf("carp: error %d attaching to PF_INET\n",
2126 		    proto_reg[CARP_INET]);
2127 		carp_mod_cleanup();
2128 		return (proto_reg[CARP_INET]);
2129 	}
2130 	err = ipproto_register(IPPROTO_CARP);
2131 	if (err) {
2132 		printf("carp: error %d registering with INET\n", err);
2133 		carp_mod_cleanup();
2134 		return (err);
2135 	}
2136 #endif
2137 	return (0);
2138 }
2139 
2140 static int
2141 carp_modevent(module_t mod, int type, void *data)
2142 {
2143 	switch (type) {
2144 	case MOD_LOAD:
2145 		return carp_mod_load();
2146 		/* NOTREACHED */
2147 	case MOD_UNLOAD:
2148 		mtx_lock(&carp_mtx);
2149 		if (LIST_EMPTY(&carp_list))
2150 			carp_mod_cleanup();
2151 		else {
2152 			mtx_unlock(&carp_mtx);
2153 			return (EBUSY);
2154 		}
2155 		break;
2156 
2157 	default:
2158 		return (EINVAL);
2159 	}
2160 
2161 	return (0);
2162 }
2163 
2164 static moduledata_t carp_mod = {
2165 	"carp",
2166 	carp_modevent,
2167 	0
2168 };
2169 
2170 DECLARE_MODULE(carp, carp_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
2171