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