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