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