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