xref: /freebsd/sys/netinet/ip_carp.c (revision 47dd1d1b619cc035b82b49a91a25544309ff95ae)
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/if.h>
59 #include <net/if_var.h>
60 #include <net/if_dl.h>
61 #include <net/if_llatbl.h>
62 #include <net/if_types.h>
63 #include <net/route.h>
64 #include <net/vnet.h>
65 
66 #if defined(INET) || defined(INET6)
67 #include <netinet/in.h>
68 #include <netinet/in_var.h>
69 #include <netinet/ip_carp.h>
70 #include <netinet/ip.h>
71 #include <machine/in_cksum.h>
72 #endif
73 #ifdef INET
74 #include <netinet/ip_var.h>
75 #include <netinet/if_ether.h>
76 #endif
77 
78 #ifdef INET6
79 #include <netinet/icmp6.h>
80 #include <netinet/ip6.h>
81 #include <netinet6/in6_var.h>
82 #include <netinet6/ip6_var.h>
83 #include <netinet6/scope6_var.h>
84 #include <netinet6/nd6.h>
85 #endif
86 
87 #include <crypto/sha1.h>
88 
89 static MALLOC_DEFINE(M_CARP, "CARP", "CARP addresses");
90 
91 struct carp_softc {
92 	struct ifnet		*sc_carpdev;	/* Pointer to parent ifnet. */
93 	struct ifaddr		**sc_ifas;	/* Our ifaddrs. */
94 	struct sockaddr_dl	sc_addr;	/* Our link level address. */
95 	struct callout		sc_ad_tmo;	/* Advertising timeout. */
96 #ifdef INET
97 	struct callout		sc_md_tmo;	/* Master down timeout. */
98 #endif
99 #ifdef INET6
100 	struct callout 		sc_md6_tmo;	/* XXX: Master down timeout. */
101 #endif
102 	struct mtx		sc_mtx;
103 
104 	int			sc_vhid;
105 	int			sc_advskew;
106 	int			sc_advbase;
107 
108 	int			sc_naddrs;
109 	int			sc_naddrs6;
110 	int			sc_ifasiz;
111 	enum { INIT = 0, BACKUP, MASTER }	sc_state;
112 	int			sc_suppress;
113 	int			sc_sendad_errors;
114 #define	CARP_SENDAD_MAX_ERRORS	3
115 	int			sc_sendad_success;
116 #define	CARP_SENDAD_MIN_SUCCESS 3
117 
118 	int			sc_init_counter;
119 	uint64_t		sc_counter;
120 
121 	/* authentication */
122 #define	CARP_HMAC_PAD	64
123 	unsigned char sc_key[CARP_KEY_LEN];
124 	unsigned char sc_pad[CARP_HMAC_PAD];
125 	SHA1_CTX sc_sha1;
126 
127 	TAILQ_ENTRY(carp_softc)	sc_list;	/* On the carp_if list. */
128 	LIST_ENTRY(carp_softc)	sc_next;	/* On the global list. */
129 };
130 
131 struct carp_if {
132 #ifdef INET
133 	int	cif_naddrs;
134 #endif
135 #ifdef INET6
136 	int	cif_naddrs6;
137 #endif
138 	TAILQ_HEAD(, carp_softc) cif_vrs;
139 #ifdef INET
140 	struct ip_moptions 	 cif_imo;
141 #endif
142 #ifdef INET6
143 	struct ip6_moptions 	 cif_im6o;
144 #endif
145 	struct ifnet	*cif_ifp;
146 	struct mtx	cif_mtx;
147 	uint32_t	cif_flags;
148 #define	CIF_PROMISC	0x00000001
149 };
150 
151 #define	CARP_INET	0
152 #define	CARP_INET6	1
153 static int proto_reg[] = {-1, -1};
154 
155 /*
156  * Brief design of carp(4).
157  *
158  * Any carp-capable ifnet may have a list of carp softcs hanging off
159  * its ifp->if_carp pointer. Each softc represents one unique virtual
160  * host id, or vhid. The softc has a back pointer to the ifnet. All
161  * softcs are joined in a global list, which has quite limited use.
162  *
163  * Any interface address that takes part in CARP negotiation has a
164  * pointer to the softc of its vhid, ifa->ifa_carp. That could be either
165  * AF_INET or AF_INET6 address.
166  *
167  * Although, one can get the softc's backpointer to ifnet and traverse
168  * through its ifp->if_addrhead queue to find all interface addresses
169  * involved in CARP, we keep a growable array of ifaddr pointers. This
170  * allows us to avoid grabbing the IF_ADDR_LOCK() in many traversals that
171  * do calls into the network stack, thus avoiding LORs.
172  *
173  * Locking:
174  *
175  * Each softc has a lock sc_mtx. It is used to synchronise carp_input_c(),
176  * callout-driven events and ioctl()s.
177  *
178  * To traverse the list of softcs on an ifnet we use CIF_LOCK() or carp_sx.
179  * To traverse the global list we use the mutex carp_mtx.
180  *
181  * Known issues with locking:
182  *
183  * - Sending ad, we put the pointer to the softc in an mtag, and no reference
184  *   counting is done on the softc.
185  * - On module unload we may race (?) with packet processing thread
186  *   dereferencing our function pointers.
187  */
188 
189 /* Accept incoming CARP packets. */
190 static VNET_DEFINE(int, carp_allow) = 1;
191 #define	V_carp_allow	VNET(carp_allow)
192 
193 /* Preempt slower nodes. */
194 static VNET_DEFINE(int, carp_preempt) = 0;
195 #define	V_carp_preempt	VNET(carp_preempt)
196 
197 /* Log level. */
198 static VNET_DEFINE(int, carp_log) = 1;
199 #define	V_carp_log	VNET(carp_log)
200 
201 /* Global advskew demotion. */
202 static VNET_DEFINE(int, carp_demotion) = 0;
203 #define	V_carp_demotion	VNET(carp_demotion)
204 
205 /* Send error demotion factor. */
206 static VNET_DEFINE(int, carp_senderr_adj) = CARP_MAXSKEW;
207 #define	V_carp_senderr_adj	VNET(carp_senderr_adj)
208 
209 /* Iface down demotion factor. */
210 static VNET_DEFINE(int, carp_ifdown_adj) = CARP_MAXSKEW;
211 #define	V_carp_ifdown_adj	VNET(carp_ifdown_adj)
212 
213 static int carp_allow_sysctl(SYSCTL_HANDLER_ARGS);
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_PROC(_net_inet_carp, OID_AUTO, allow,
218     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, 0, 0, carp_allow_sysctl, "I",
219     "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 	    !V_carp_allow)
1298 		return;
1299 
1300 	switch (sc->sc_state) {
1301 	case INIT:
1302 		carp_set_state(sc, BACKUP, "initialization complete");
1303 		carp_setrun(sc, 0);
1304 		break;
1305 	case BACKUP:
1306 		callout_stop(&sc->sc_ad_tmo);
1307 		tv.tv_sec = 3 * sc->sc_advbase;
1308 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1309 		switch (af) {
1310 #ifdef INET
1311 		case AF_INET:
1312 			callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1313 			    carp_master_down, sc);
1314 			break;
1315 #endif
1316 #ifdef INET6
1317 		case AF_INET6:
1318 			callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1319 			    carp_master_down, sc);
1320 			break;
1321 #endif
1322 		default:
1323 #ifdef INET
1324 			if (sc->sc_naddrs)
1325 				callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1326 				    carp_master_down, sc);
1327 #endif
1328 #ifdef INET6
1329 			if (sc->sc_naddrs6)
1330 				callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1331 				    carp_master_down, sc);
1332 #endif
1333 			break;
1334 		}
1335 		break;
1336 	case MASTER:
1337 		tv.tv_sec = sc->sc_advbase;
1338 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1339 		callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1340 		    carp_send_ad, sc);
1341 		break;
1342 	}
1343 }
1344 
1345 /*
1346  * Setup multicast structures.
1347  */
1348 static int
1349 carp_multicast_setup(struct carp_if *cif, sa_family_t sa)
1350 {
1351 	struct ifnet *ifp = cif->cif_ifp;
1352 	int error = 0;
1353 
1354 	switch (sa) {
1355 #ifdef INET
1356 	case AF_INET:
1357 	    {
1358 		struct ip_moptions *imo = &cif->cif_imo;
1359 		struct in_addr addr;
1360 
1361 		if (imo->imo_membership)
1362 			return (0);
1363 
1364 		imo->imo_membership = (struct in_multi **)malloc(
1365 		    (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_CARP,
1366 		    M_WAITOK);
1367 		imo->imo_mfilters = NULL;
1368 		imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1369 		imo->imo_multicast_vif = -1;
1370 
1371 		addr.s_addr = htonl(INADDR_CARP_GROUP);
1372 		if ((error = in_joingroup(ifp, &addr, NULL,
1373 		    &imo->imo_membership[0])) != 0) {
1374 			free(imo->imo_membership, M_CARP);
1375 			break;
1376 		}
1377 		imo->imo_num_memberships++;
1378 		imo->imo_multicast_ifp = ifp;
1379 		imo->imo_multicast_ttl = CARP_DFLTTL;
1380 		imo->imo_multicast_loop = 0;
1381 		break;
1382 	   }
1383 #endif
1384 #ifdef INET6
1385 	case AF_INET6:
1386 	    {
1387 		struct ip6_moptions *im6o = &cif->cif_im6o;
1388 		struct in6_addr in6;
1389 		struct in6_multi *in6m;
1390 
1391 		if (im6o->im6o_membership)
1392 			return (0);
1393 
1394 		im6o->im6o_membership = (struct in6_multi **)malloc(
1395 		    (sizeof(struct in6_multi *) * IPV6_MIN_MEMBERSHIPS), M_CARP,
1396 		    M_ZERO | M_WAITOK);
1397 		im6o->im6o_mfilters = NULL;
1398 		im6o->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
1399 		im6o->im6o_multicast_hlim = CARP_DFLTTL;
1400 		im6o->im6o_multicast_ifp = ifp;
1401 
1402 		/* Join IPv6 CARP multicast group. */
1403 		bzero(&in6, sizeof(in6));
1404 		in6.s6_addr16[0] = htons(0xff02);
1405 		in6.s6_addr8[15] = 0x12;
1406 		if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1407 			free(im6o->im6o_membership, M_CARP);
1408 			break;
1409 		}
1410 		in6m = NULL;
1411 		if ((error = in6_joingroup(ifp, &in6, NULL, &in6m, 0)) != 0) {
1412 			free(im6o->im6o_membership, M_CARP);
1413 			break;
1414 		}
1415 		im6o->im6o_membership[0] = in6m;
1416 		im6o->im6o_num_memberships++;
1417 
1418 		/* Join solicited multicast address. */
1419 		bzero(&in6, sizeof(in6));
1420 		in6.s6_addr16[0] = htons(0xff02);
1421 		in6.s6_addr32[1] = 0;
1422 		in6.s6_addr32[2] = htonl(1);
1423 		in6.s6_addr32[3] = 0;
1424 		in6.s6_addr8[12] = 0xff;
1425 		if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1426 			in6_leavegroup(im6o->im6o_membership[0], NULL);
1427 			free(im6o->im6o_membership, M_CARP);
1428 			break;
1429 		}
1430 		in6m = NULL;
1431 		if ((error = in6_joingroup(ifp, &in6, NULL, &in6m, 0)) != 0) {
1432 			in6_leavegroup(im6o->im6o_membership[0], NULL);
1433 			free(im6o->im6o_membership, M_CARP);
1434 			break;
1435 		}
1436 		im6o->im6o_membership[1] = in6m;
1437 		im6o->im6o_num_memberships++;
1438 		break;
1439 	    }
1440 #endif
1441 	}
1442 
1443 	return (error);
1444 }
1445 
1446 /*
1447  * Free multicast structures.
1448  */
1449 static void
1450 carp_multicast_cleanup(struct carp_if *cif, sa_family_t sa)
1451 {
1452 
1453 	sx_assert(&carp_sx, SA_XLOCKED);
1454 
1455 	switch (sa) {
1456 #ifdef INET
1457 	case AF_INET:
1458 		if (cif->cif_naddrs == 0) {
1459 			struct ip_moptions *imo = &cif->cif_imo;
1460 
1461 			in_leavegroup(imo->imo_membership[0], NULL);
1462 			KASSERT(imo->imo_mfilters == NULL,
1463 			    ("%s: imo_mfilters != NULL", __func__));
1464 			free(imo->imo_membership, M_CARP);
1465 			imo->imo_membership = NULL;
1466 
1467 		}
1468 		break;
1469 #endif
1470 #ifdef INET6
1471 	case AF_INET6:
1472 		if (cif->cif_naddrs6 == 0) {
1473 			struct ip6_moptions *im6o = &cif->cif_im6o;
1474 
1475 			in6_leavegroup(im6o->im6o_membership[0], NULL);
1476 			in6_leavegroup(im6o->im6o_membership[1], NULL);
1477 			KASSERT(im6o->im6o_mfilters == NULL,
1478 			    ("%s: im6o_mfilters != NULL", __func__));
1479 			free(im6o->im6o_membership, M_CARP);
1480 			im6o->im6o_membership = NULL;
1481 		}
1482 		break;
1483 #endif
1484 	}
1485 }
1486 
1487 int
1488 carp_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *sa)
1489 {
1490 	struct m_tag *mtag;
1491 	struct carp_softc *sc;
1492 
1493 	if (!sa)
1494 		return (0);
1495 
1496 	switch (sa->sa_family) {
1497 #ifdef INET
1498 	case AF_INET:
1499 		break;
1500 #endif
1501 #ifdef INET6
1502 	case AF_INET6:
1503 		break;
1504 #endif
1505 	default:
1506 		return (0);
1507 	}
1508 
1509 	mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
1510 	if (mtag == NULL)
1511 		return (0);
1512 
1513 	bcopy(mtag + 1, &sc, sizeof(sc));
1514 
1515 	/* Set the source MAC address to the Virtual Router MAC Address. */
1516 	switch (ifp->if_type) {
1517 	case IFT_ETHER:
1518 	case IFT_BRIDGE:
1519 	case IFT_L2VLAN: {
1520 			struct ether_header *eh;
1521 
1522 			eh = mtod(m, struct ether_header *);
1523 			eh->ether_shost[0] = 0;
1524 			eh->ether_shost[1] = 0;
1525 			eh->ether_shost[2] = 0x5e;
1526 			eh->ether_shost[3] = 0;
1527 			eh->ether_shost[4] = 1;
1528 			eh->ether_shost[5] = sc->sc_vhid;
1529 		}
1530 		break;
1531 	default:
1532 		printf("%s: carp is not supported for the %d interface type\n",
1533 		    ifp->if_xname, ifp->if_type);
1534 		return (EOPNOTSUPP);
1535 	}
1536 
1537 	return (0);
1538 }
1539 
1540 static struct carp_softc*
1541 carp_alloc(struct ifnet *ifp)
1542 {
1543 	struct carp_softc *sc;
1544 	struct carp_if *cif;
1545 
1546 	sx_assert(&carp_sx, SA_XLOCKED);
1547 
1548 	if ((cif = ifp->if_carp) == NULL)
1549 		cif = carp_alloc_if(ifp);
1550 
1551 	sc = malloc(sizeof(*sc), M_CARP, M_WAITOK|M_ZERO);
1552 
1553 	sc->sc_advbase = CARP_DFLTINTV;
1554 	sc->sc_vhid = -1;	/* required setting */
1555 	sc->sc_init_counter = 1;
1556 	sc->sc_state = INIT;
1557 
1558 	sc->sc_ifasiz = sizeof(struct ifaddr *);
1559 	sc->sc_ifas = malloc(sc->sc_ifasiz, M_CARP, M_WAITOK|M_ZERO);
1560 	sc->sc_carpdev = ifp;
1561 
1562 	CARP_LOCK_INIT(sc);
1563 #ifdef INET
1564 	callout_init_mtx(&sc->sc_md_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1565 #endif
1566 #ifdef INET6
1567 	callout_init_mtx(&sc->sc_md6_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1568 #endif
1569 	callout_init_mtx(&sc->sc_ad_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1570 
1571 	CIF_LOCK(cif);
1572 	TAILQ_INSERT_TAIL(&cif->cif_vrs, sc, sc_list);
1573 	CIF_UNLOCK(cif);
1574 
1575 	mtx_lock(&carp_mtx);
1576 	LIST_INSERT_HEAD(&carp_list, sc, sc_next);
1577 	mtx_unlock(&carp_mtx);
1578 
1579 	return (sc);
1580 }
1581 
1582 static void
1583 carp_grow_ifas(struct carp_softc *sc)
1584 {
1585 	struct ifaddr **new;
1586 
1587 	new = malloc(sc->sc_ifasiz * 2, M_CARP, M_WAITOK | M_ZERO);
1588 	CARP_LOCK(sc);
1589 	bcopy(sc->sc_ifas, new, sc->sc_ifasiz);
1590 	free(sc->sc_ifas, M_CARP);
1591 	sc->sc_ifas = new;
1592 	sc->sc_ifasiz *= 2;
1593 	CARP_UNLOCK(sc);
1594 }
1595 
1596 static void
1597 carp_destroy(struct carp_softc *sc)
1598 {
1599 	struct ifnet *ifp = sc->sc_carpdev;
1600 	struct carp_if *cif = ifp->if_carp;
1601 
1602 	sx_assert(&carp_sx, SA_XLOCKED);
1603 
1604 	if (sc->sc_suppress)
1605 		carp_demote_adj(-V_carp_ifdown_adj, "vhid removed");
1606 	CARP_UNLOCK(sc);
1607 
1608 	CIF_LOCK(cif);
1609 	TAILQ_REMOVE(&cif->cif_vrs, sc, sc_list);
1610 	CIF_UNLOCK(cif);
1611 
1612 	mtx_lock(&carp_mtx);
1613 	LIST_REMOVE(sc, sc_next);
1614 	mtx_unlock(&carp_mtx);
1615 
1616 	callout_drain(&sc->sc_ad_tmo);
1617 #ifdef INET
1618 	callout_drain(&sc->sc_md_tmo);
1619 #endif
1620 #ifdef INET6
1621 	callout_drain(&sc->sc_md6_tmo);
1622 #endif
1623 	CARP_LOCK_DESTROY(sc);
1624 
1625 	free(sc->sc_ifas, M_CARP);
1626 	free(sc, M_CARP);
1627 }
1628 
1629 static struct carp_if*
1630 carp_alloc_if(struct ifnet *ifp)
1631 {
1632 	struct carp_if *cif;
1633 	int error;
1634 
1635 	cif = malloc(sizeof(*cif), M_CARP, M_WAITOK|M_ZERO);
1636 
1637 	if ((error = ifpromisc(ifp, 1)) != 0)
1638 		printf("%s: ifpromisc(%s) failed: %d\n",
1639 		    __func__, ifp->if_xname, error);
1640 	else
1641 		cif->cif_flags |= CIF_PROMISC;
1642 
1643 	CIF_LOCK_INIT(cif);
1644 	cif->cif_ifp = ifp;
1645 	TAILQ_INIT(&cif->cif_vrs);
1646 
1647 	IF_ADDR_WLOCK(ifp);
1648 	ifp->if_carp = cif;
1649 	if_ref(ifp);
1650 	IF_ADDR_WUNLOCK(ifp);
1651 
1652 	return (cif);
1653 }
1654 
1655 static void
1656 carp_free_if(struct carp_if *cif)
1657 {
1658 	struct ifnet *ifp = cif->cif_ifp;
1659 
1660 	CIF_LOCK_ASSERT(cif);
1661 	KASSERT(TAILQ_EMPTY(&cif->cif_vrs), ("%s: softc list not empty",
1662 	    __func__));
1663 
1664 	IF_ADDR_WLOCK(ifp);
1665 	ifp->if_carp = NULL;
1666 	IF_ADDR_WUNLOCK(ifp);
1667 
1668 	CIF_LOCK_DESTROY(cif);
1669 
1670 	if (cif->cif_flags & CIF_PROMISC)
1671 		ifpromisc(ifp, 0);
1672 	if_rele(ifp);
1673 
1674 	free(cif, M_CARP);
1675 }
1676 
1677 static void
1678 carp_carprcp(struct carpreq *carpr, struct carp_softc *sc, int priv)
1679 {
1680 
1681 	CARP_LOCK(sc);
1682 	carpr->carpr_state = sc->sc_state;
1683 	carpr->carpr_vhid = sc->sc_vhid;
1684 	carpr->carpr_advbase = sc->sc_advbase;
1685 	carpr->carpr_advskew = sc->sc_advskew;
1686 	if (priv)
1687 		bcopy(sc->sc_key, carpr->carpr_key, sizeof(carpr->carpr_key));
1688 	else
1689 		bzero(carpr->carpr_key, sizeof(carpr->carpr_key));
1690 	CARP_UNLOCK(sc);
1691 }
1692 
1693 int
1694 carp_ioctl(struct ifreq *ifr, u_long cmd, struct thread *td)
1695 {
1696 	struct carpreq carpr;
1697 	struct ifnet *ifp;
1698 	struct carp_softc *sc = NULL;
1699 	int error = 0, locked = 0;
1700 
1701 	if ((error = copyin(ifr_data_get_ptr(ifr), &carpr, sizeof carpr)))
1702 		return (error);
1703 
1704 	ifp = ifunit_ref(ifr->ifr_name);
1705 	if (ifp == NULL)
1706 		return (ENXIO);
1707 
1708 	switch (ifp->if_type) {
1709 	case IFT_ETHER:
1710 	case IFT_L2VLAN:
1711 	case IFT_BRIDGE:
1712 		break;
1713 	default:
1714 		error = EOPNOTSUPP;
1715 		goto out;
1716 	}
1717 
1718 	if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1719 		error = EADDRNOTAVAIL;
1720 		goto out;
1721 	}
1722 
1723 	sx_xlock(&carp_sx);
1724 	switch (cmd) {
1725 	case SIOCSVH:
1726 		if ((error = priv_check(td, PRIV_NETINET_CARP)))
1727 			break;
1728 		if (carpr.carpr_vhid <= 0 || carpr.carpr_vhid > CARP_MAXVHID ||
1729 		    carpr.carpr_advbase < 0 || carpr.carpr_advskew < 0) {
1730 			error = EINVAL;
1731 			break;
1732 		}
1733 
1734 		if (ifp->if_carp) {
1735 			IFNET_FOREACH_CARP(ifp, sc)
1736 				if (sc->sc_vhid == carpr.carpr_vhid)
1737 					break;
1738 		}
1739 		if (sc == NULL) {
1740 			sc = carp_alloc(ifp);
1741 			CARP_LOCK(sc);
1742 			sc->sc_vhid = carpr.carpr_vhid;
1743 			LLADDR(&sc->sc_addr)[0] = 0;
1744 			LLADDR(&sc->sc_addr)[1] = 0;
1745 			LLADDR(&sc->sc_addr)[2] = 0x5e;
1746 			LLADDR(&sc->sc_addr)[3] = 0;
1747 			LLADDR(&sc->sc_addr)[4] = 1;
1748 			LLADDR(&sc->sc_addr)[5] = sc->sc_vhid;
1749 		} else
1750 			CARP_LOCK(sc);
1751 		locked = 1;
1752 		if (carpr.carpr_advbase > 0) {
1753 			if (carpr.carpr_advbase > 255 ||
1754 			    carpr.carpr_advbase < CARP_DFLTINTV) {
1755 				error = EINVAL;
1756 				break;
1757 			}
1758 			sc->sc_advbase = carpr.carpr_advbase;
1759 		}
1760 		if (carpr.carpr_advskew >= 255) {
1761 			error = EINVAL;
1762 			break;
1763 		}
1764 		sc->sc_advskew = carpr.carpr_advskew;
1765 		if (carpr.carpr_key[0] != '\0') {
1766 			bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1767 			carp_hmac_prepare(sc);
1768 		}
1769 		if (sc->sc_state != INIT &&
1770 		    carpr.carpr_state != sc->sc_state) {
1771 			switch (carpr.carpr_state) {
1772 			case BACKUP:
1773 				callout_stop(&sc->sc_ad_tmo);
1774 				carp_set_state(sc, BACKUP,
1775 				    "user requested via ifconfig");
1776 				carp_setrun(sc, 0);
1777 				carp_delroute(sc);
1778 				break;
1779 			case MASTER:
1780 				carp_master_down_locked(sc,
1781 				    "user requested via ifconfig");
1782 				break;
1783 			default:
1784 				break;
1785 			}
1786 		}
1787 		break;
1788 
1789 	case SIOCGVH:
1790 	    {
1791 		int priveleged;
1792 
1793 		if (carpr.carpr_vhid < 0 || carpr.carpr_vhid > CARP_MAXVHID) {
1794 			error = EINVAL;
1795 			break;
1796 		}
1797 		if (carpr.carpr_count < 1) {
1798 			error = EMSGSIZE;
1799 			break;
1800 		}
1801 		if (ifp->if_carp == NULL) {
1802 			error = ENOENT;
1803 			break;
1804 		}
1805 
1806 		priveleged = (priv_check(td, PRIV_NETINET_CARP) == 0);
1807 		if (carpr.carpr_vhid != 0) {
1808 			IFNET_FOREACH_CARP(ifp, sc)
1809 				if (sc->sc_vhid == carpr.carpr_vhid)
1810 					break;
1811 			if (sc == NULL) {
1812 				error = ENOENT;
1813 				break;
1814 			}
1815 			carp_carprcp(&carpr, sc, priveleged);
1816 			error = copyout(&carpr, ifr_data_get_ptr(ifr),
1817 			    sizeof(carpr));
1818 		} else  {
1819 			int i, count;
1820 
1821 			count = 0;
1822 			IFNET_FOREACH_CARP(ifp, sc)
1823 				count++;
1824 
1825 			if (count > carpr.carpr_count) {
1826 				CIF_UNLOCK(ifp->if_carp);
1827 				error = EMSGSIZE;
1828 				break;
1829 			}
1830 
1831 			i = 0;
1832 			IFNET_FOREACH_CARP(ifp, sc) {
1833 				carp_carprcp(&carpr, sc, priveleged);
1834 				carpr.carpr_count = count;
1835 				error = copyout(&carpr,
1836 				    (caddr_t)ifr_data_get_ptr(ifr) +
1837 				    (i * sizeof(carpr)), sizeof(carpr));
1838 				if (error) {
1839 					CIF_UNLOCK(ifp->if_carp);
1840 					break;
1841 				}
1842 				i++;
1843 			}
1844 		}
1845 		break;
1846 	    }
1847 	default:
1848 		error = EINVAL;
1849 	}
1850 	sx_xunlock(&carp_sx);
1851 
1852 out:
1853 	if (locked)
1854 		CARP_UNLOCK(sc);
1855 	if_rele(ifp);
1856 
1857 	return (error);
1858 }
1859 
1860 static int
1861 carp_get_vhid(struct ifaddr *ifa)
1862 {
1863 
1864 	if (ifa == NULL || ifa->ifa_carp == NULL)
1865 		return (0);
1866 
1867 	return (ifa->ifa_carp->sc_vhid);
1868 }
1869 
1870 int
1871 carp_attach(struct ifaddr *ifa, int vhid)
1872 {
1873 	struct ifnet *ifp = ifa->ifa_ifp;
1874 	struct carp_if *cif = ifp->if_carp;
1875 	struct carp_softc *sc;
1876 	int index, error;
1877 
1878 	KASSERT(ifa->ifa_carp == NULL, ("%s: ifa %p attached", __func__, ifa));
1879 
1880 	switch (ifa->ifa_addr->sa_family) {
1881 #ifdef INET
1882 	case AF_INET:
1883 #endif
1884 #ifdef INET6
1885 	case AF_INET6:
1886 #endif
1887 		break;
1888 	default:
1889 		return (EPROTOTYPE);
1890 	}
1891 
1892 	sx_xlock(&carp_sx);
1893 	if (ifp->if_carp == NULL) {
1894 		sx_xunlock(&carp_sx);
1895 		return (ENOPROTOOPT);
1896 	}
1897 
1898 	IFNET_FOREACH_CARP(ifp, sc)
1899 		if (sc->sc_vhid == vhid)
1900 			break;
1901 	if (sc == NULL) {
1902 		sx_xunlock(&carp_sx);
1903 		return (ENOENT);
1904 	}
1905 
1906 	error = carp_multicast_setup(cif, ifa->ifa_addr->sa_family);
1907 	if (error) {
1908 		CIF_FREE(cif);
1909 		sx_xunlock(&carp_sx);
1910 		return (error);
1911 	}
1912 
1913 	index = sc->sc_naddrs + sc->sc_naddrs6 + 1;
1914 	if (index > sc->sc_ifasiz / sizeof(struct ifaddr *))
1915 		carp_grow_ifas(sc);
1916 
1917 	switch (ifa->ifa_addr->sa_family) {
1918 #ifdef INET
1919 	case AF_INET:
1920 		cif->cif_naddrs++;
1921 		sc->sc_naddrs++;
1922 		break;
1923 #endif
1924 #ifdef INET6
1925 	case AF_INET6:
1926 		cif->cif_naddrs6++;
1927 		sc->sc_naddrs6++;
1928 		break;
1929 #endif
1930 	}
1931 
1932 	ifa_ref(ifa);
1933 
1934 	CARP_LOCK(sc);
1935 	sc->sc_ifas[index - 1] = ifa;
1936 	ifa->ifa_carp = sc;
1937 	carp_hmac_prepare(sc);
1938 	carp_sc_state(sc);
1939 	CARP_UNLOCK(sc);
1940 
1941 	sx_xunlock(&carp_sx);
1942 
1943 	return (0);
1944 }
1945 
1946 void
1947 carp_detach(struct ifaddr *ifa, bool keep_cif)
1948 {
1949 	struct ifnet *ifp = ifa->ifa_ifp;
1950 	struct carp_if *cif = ifp->if_carp;
1951 	struct carp_softc *sc = ifa->ifa_carp;
1952 	int i, index;
1953 
1954 	KASSERT(sc != NULL, ("%s: %p not attached", __func__, ifa));
1955 
1956 	sx_xlock(&carp_sx);
1957 
1958 	CARP_LOCK(sc);
1959 	/* Shift array. */
1960 	index = sc->sc_naddrs + sc->sc_naddrs6;
1961 	for (i = 0; i < index; i++)
1962 		if (sc->sc_ifas[i] == ifa)
1963 			break;
1964 	KASSERT(i < index, ("%s: %p no backref", __func__, ifa));
1965 	for (; i < index - 1; i++)
1966 		sc->sc_ifas[i] = sc->sc_ifas[i+1];
1967 	sc->sc_ifas[index - 1] = NULL;
1968 
1969 	switch (ifa->ifa_addr->sa_family) {
1970 #ifdef INET
1971 	case AF_INET:
1972 		cif->cif_naddrs--;
1973 		sc->sc_naddrs--;
1974 		break;
1975 #endif
1976 #ifdef INET6
1977 	case AF_INET6:
1978 		cif->cif_naddrs6--;
1979 		sc->sc_naddrs6--;
1980 		break;
1981 #endif
1982 	}
1983 
1984 	carp_ifa_delroute(ifa);
1985 	carp_multicast_cleanup(cif, ifa->ifa_addr->sa_family);
1986 
1987 	ifa->ifa_carp = NULL;
1988 	ifa_free(ifa);
1989 
1990 	carp_hmac_prepare(sc);
1991 	carp_sc_state(sc);
1992 
1993 	if (!keep_cif && sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0)
1994 		carp_destroy(sc);
1995 	else
1996 		CARP_UNLOCK(sc);
1997 
1998 	if (!keep_cif)
1999 		CIF_FREE(cif);
2000 
2001 	sx_xunlock(&carp_sx);
2002 }
2003 
2004 static void
2005 carp_set_state(struct carp_softc *sc, int state, const char *reason)
2006 {
2007 
2008 	CARP_LOCK_ASSERT(sc);
2009 
2010 	if (sc->sc_state != state) {
2011 		const char *carp_states[] = { CARP_STATES };
2012 		char subsys[IFNAMSIZ+5];
2013 
2014 		snprintf(subsys, IFNAMSIZ+5, "%u@%s", sc->sc_vhid,
2015 		    sc->sc_carpdev->if_xname);
2016 
2017 		CARP_LOG("%s: %s -> %s (%s)\n", subsys,
2018 		    carp_states[sc->sc_state], carp_states[state], reason);
2019 
2020 		sc->sc_state = state;
2021 
2022 		devctl_notify("CARP", subsys, carp_states[state], NULL);
2023 	}
2024 }
2025 
2026 static void
2027 carp_linkstate(struct ifnet *ifp)
2028 {
2029 	struct carp_softc *sc;
2030 
2031 	CIF_LOCK(ifp->if_carp);
2032 	IFNET_FOREACH_CARP(ifp, sc) {
2033 		CARP_LOCK(sc);
2034 		carp_sc_state(sc);
2035 		CARP_UNLOCK(sc);
2036 	}
2037 	CIF_UNLOCK(ifp->if_carp);
2038 }
2039 
2040 static void
2041 carp_sc_state(struct carp_softc *sc)
2042 {
2043 
2044 	CARP_LOCK_ASSERT(sc);
2045 
2046 	if (sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
2047 	    !(sc->sc_carpdev->if_flags & IFF_UP) ||
2048 	    !V_carp_allow) {
2049 		callout_stop(&sc->sc_ad_tmo);
2050 #ifdef INET
2051 		callout_stop(&sc->sc_md_tmo);
2052 #endif
2053 #ifdef INET6
2054 		callout_stop(&sc->sc_md6_tmo);
2055 #endif
2056 		carp_set_state(sc, INIT, "hardware interface down");
2057 		carp_setrun(sc, 0);
2058 		if (!sc->sc_suppress)
2059 			carp_demote_adj(V_carp_ifdown_adj, "interface down");
2060 		sc->sc_suppress = 1;
2061 	} else {
2062 		carp_set_state(sc, INIT, "hardware interface up");
2063 		carp_setrun(sc, 0);
2064 		if (sc->sc_suppress)
2065 			carp_demote_adj(-V_carp_ifdown_adj, "interface up");
2066 		sc->sc_suppress = 0;
2067 	}
2068 }
2069 
2070 static void
2071 carp_demote_adj(int adj, char *reason)
2072 {
2073 	atomic_add_int(&V_carp_demotion, adj);
2074 	CARP_LOG("demoted by %d to %d (%s)\n", adj, V_carp_demotion, reason);
2075 	taskqueue_enqueue(taskqueue_swi, &carp_sendall_task);
2076 }
2077 
2078 static int
2079 carp_allow_sysctl(SYSCTL_HANDLER_ARGS)
2080 {
2081 	int new, error;
2082 	struct carp_softc *sc;
2083 
2084 	new = V_carp_allow;
2085 	error = sysctl_handle_int(oidp, &new, 0, req);
2086 	if (error || !req->newptr)
2087 		return (error);
2088 
2089 	if (V_carp_allow != new) {
2090 		V_carp_allow = new;
2091 
2092 		mtx_lock(&carp_mtx);
2093 		LIST_FOREACH(sc, &carp_list, sc_next) {
2094 			CARP_LOCK(sc);
2095 			if (curvnet == sc->sc_carpdev->if_vnet)
2096 				carp_sc_state(sc);
2097 			CARP_UNLOCK(sc);
2098 		}
2099 		mtx_unlock(&carp_mtx);
2100 	}
2101 
2102 	return (0);
2103 }
2104 
2105 static int
2106 carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS)
2107 {
2108 	int new, error;
2109 
2110 	new = V_carp_demotion;
2111 	error = sysctl_handle_int(oidp, &new, 0, req);
2112 	if (error || !req->newptr)
2113 		return (error);
2114 
2115 	carp_demote_adj(new, "sysctl");
2116 
2117 	return (0);
2118 }
2119 
2120 #ifdef INET
2121 extern  struct domain inetdomain;
2122 static struct protosw in_carp_protosw = {
2123 	.pr_type =		SOCK_RAW,
2124 	.pr_domain =		&inetdomain,
2125 	.pr_protocol =		IPPROTO_CARP,
2126 	.pr_flags =		PR_ATOMIC|PR_ADDR,
2127 	.pr_input =		carp_input,
2128 	.pr_output =		rip_output,
2129 	.pr_ctloutput =		rip_ctloutput,
2130 	.pr_usrreqs =		&rip_usrreqs
2131 };
2132 #endif
2133 
2134 #ifdef INET6
2135 extern	struct domain inet6domain;
2136 static struct protosw in6_carp_protosw = {
2137 	.pr_type =		SOCK_RAW,
2138 	.pr_domain =		&inet6domain,
2139 	.pr_protocol =		IPPROTO_CARP,
2140 	.pr_flags =		PR_ATOMIC|PR_ADDR,
2141 	.pr_input =		carp6_input,
2142 	.pr_output =		rip6_output,
2143 	.pr_ctloutput =		rip6_ctloutput,
2144 	.pr_usrreqs =		&rip6_usrreqs
2145 };
2146 #endif
2147 
2148 static void
2149 carp_mod_cleanup(void)
2150 {
2151 
2152 #ifdef INET
2153 	if (proto_reg[CARP_INET] == 0) {
2154 		(void)ipproto_unregister(IPPROTO_CARP);
2155 		pf_proto_unregister(PF_INET, IPPROTO_CARP, SOCK_RAW);
2156 		proto_reg[CARP_INET] = -1;
2157 	}
2158 	carp_iamatch_p = NULL;
2159 #endif
2160 #ifdef INET6
2161 	if (proto_reg[CARP_INET6] == 0) {
2162 		(void)ip6proto_unregister(IPPROTO_CARP);
2163 		pf_proto_unregister(PF_INET6, IPPROTO_CARP, SOCK_RAW);
2164 		proto_reg[CARP_INET6] = -1;
2165 	}
2166 	carp_iamatch6_p = NULL;
2167 	carp_macmatch6_p = NULL;
2168 #endif
2169 	carp_ioctl_p = NULL;
2170 	carp_attach_p = NULL;
2171 	carp_detach_p = NULL;
2172 	carp_get_vhid_p = NULL;
2173 	carp_linkstate_p = NULL;
2174 	carp_forus_p = NULL;
2175 	carp_output_p = NULL;
2176 	carp_demote_adj_p = NULL;
2177 	carp_master_p = NULL;
2178 	mtx_unlock(&carp_mtx);
2179 	taskqueue_drain(taskqueue_swi, &carp_sendall_task);
2180 	mtx_destroy(&carp_mtx);
2181 	sx_destroy(&carp_sx);
2182 }
2183 
2184 static int
2185 carp_mod_load(void)
2186 {
2187 	int err;
2188 
2189 	mtx_init(&carp_mtx, "carp_mtx", NULL, MTX_DEF);
2190 	sx_init(&carp_sx, "carp_sx");
2191 	LIST_INIT(&carp_list);
2192 	carp_get_vhid_p = carp_get_vhid;
2193 	carp_forus_p = carp_forus;
2194 	carp_output_p = carp_output;
2195 	carp_linkstate_p = carp_linkstate;
2196 	carp_ioctl_p = carp_ioctl;
2197 	carp_attach_p = carp_attach;
2198 	carp_detach_p = carp_detach;
2199 	carp_demote_adj_p = carp_demote_adj;
2200 	carp_master_p = carp_master;
2201 #ifdef INET6
2202 	carp_iamatch6_p = carp_iamatch6;
2203 	carp_macmatch6_p = carp_macmatch6;
2204 	proto_reg[CARP_INET6] = pf_proto_register(PF_INET6,
2205 	    (struct protosw *)&in6_carp_protosw);
2206 	if (proto_reg[CARP_INET6]) {
2207 		printf("carp: error %d attaching to PF_INET6\n",
2208 		    proto_reg[CARP_INET6]);
2209 		carp_mod_cleanup();
2210 		return (proto_reg[CARP_INET6]);
2211 	}
2212 	err = ip6proto_register(IPPROTO_CARP);
2213 	if (err) {
2214 		printf("carp: error %d registering with INET6\n", err);
2215 		carp_mod_cleanup();
2216 		return (err);
2217 	}
2218 #endif
2219 #ifdef INET
2220 	carp_iamatch_p = carp_iamatch;
2221 	proto_reg[CARP_INET] = pf_proto_register(PF_INET, &in_carp_protosw);
2222 	if (proto_reg[CARP_INET]) {
2223 		printf("carp: error %d attaching to PF_INET\n",
2224 		    proto_reg[CARP_INET]);
2225 		carp_mod_cleanup();
2226 		return (proto_reg[CARP_INET]);
2227 	}
2228 	err = ipproto_register(IPPROTO_CARP);
2229 	if (err) {
2230 		printf("carp: error %d registering with INET\n", err);
2231 		carp_mod_cleanup();
2232 		return (err);
2233 	}
2234 #endif
2235 	return (0);
2236 }
2237 
2238 static int
2239 carp_modevent(module_t mod, int type, void *data)
2240 {
2241 	switch (type) {
2242 	case MOD_LOAD:
2243 		return carp_mod_load();
2244 		/* NOTREACHED */
2245 	case MOD_UNLOAD:
2246 		mtx_lock(&carp_mtx);
2247 		if (LIST_EMPTY(&carp_list))
2248 			carp_mod_cleanup();
2249 		else {
2250 			mtx_unlock(&carp_mtx);
2251 			return (EBUSY);
2252 		}
2253 		break;
2254 
2255 	default:
2256 		return (EINVAL);
2257 	}
2258 
2259 	return (0);
2260 }
2261 
2262 static moduledata_t carp_mod = {
2263 	"carp",
2264 	carp_modevent,
2265 	0
2266 };
2267 
2268 DECLARE_MODULE(carp, carp_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);
2269