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