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