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