xref: /freebsd/sys/netinet/ip_carp.c (revision d429ea332342fcb98d27a350d0c4944bf9aec3f9)
1 /* 	$FreeBSD$ */
2 
3 /*
4  * Copyright (c) 2002 Michael Shalayeff. All rights reserved.
5  * Copyright (c) 2003 Ryan McBride. 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 "opt_carp.h"
30 #include "opt_bpf.h"
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 
34 #include <sys/types.h>
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/conf.h>
38 #include <sys/kernel.h>
39 #include <sys/limits.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/module.h>
43 #include <sys/time.h>
44 #include <sys/proc.h>
45 #include <sys/sysctl.h>
46 #include <sys/syslog.h>
47 #include <sys/signalvar.h>
48 #include <sys/filio.h>
49 #include <sys/sockio.h>
50 
51 #include <sys/socket.h>
52 #include <sys/vnode.h>
53 
54 #include <machine/stdarg.h>
55 
56 #include <net/bpf.h>
57 #include <net/ethernet.h>
58 #include <net/fddi.h>
59 #include <net/iso88025.h>
60 #include <net/if.h>
61 #include <net/if_clone.h>
62 #include <net/if_types.h>
63 #include <net/route.h>
64 
65 #ifdef INET
66 #include <netinet/in.h>
67 #include <netinet/in_var.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/if_ether.h>
72 #include <machine/in_cksum.h>
73 #endif
74 
75 #ifdef INET6
76 #include <netinet/icmp6.h>
77 #include <netinet/ip6.h>
78 #include <netinet6/ip6_var.h>
79 #include <netinet6/nd6.h>
80 #include <net/if_dl.h>
81 #endif
82 
83 #include <crypto/sha1.h>
84 #include <netinet/ip_carp.h>
85 
86 #define	CARP_IFNAME	"carp"
87 static MALLOC_DEFINE(M_CARP, "CARP", "CARP interfaces");
88 SYSCTL_DECL(_net_inet_carp);
89 
90 struct carp_softc {
91 	struct ifnet	 	*sc_ifp;	/* Interface clue */
92 	struct ifnet		*sc_carpdev;	/* Pointer to parent interface */
93 	struct in_ifaddr 	*sc_ia;		/* primary iface address */
94 	struct ip_moptions 	 sc_imo;
95 #ifdef INET6
96 	struct in6_ifaddr 	*sc_ia6;	/* primary iface address v6 */
97 	struct ip6_moptions 	 sc_im6o;
98 #endif /* INET6 */
99 	TAILQ_ENTRY(carp_softc)	 sc_list;
100 
101 	enum { INIT = 0, BACKUP, MASTER }	sc_state;
102 
103 	int			 sc_flags_backup;
104 	int			 sc_suppress;
105 
106 	int			 sc_sendad_errors;
107 #define	CARP_SENDAD_MAX_ERRORS	3
108 	int			 sc_sendad_success;
109 #define	CARP_SENDAD_MIN_SUCCESS 3
110 
111 	int			 sc_vhid;
112 	int			 sc_advskew;
113 	int			 sc_naddrs;
114 	int			 sc_naddrs6;
115 	int			 sc_advbase;	/* seconds */
116 	int			 sc_init_counter;
117 	u_int64_t		 sc_counter;
118 
119 	/* authentication */
120 #define CARP_HMAC_PAD	64
121 	unsigned char sc_key[CARP_KEY_LEN];
122 	unsigned char sc_pad[CARP_HMAC_PAD];
123 	SHA1_CTX sc_sha1;
124 
125 	struct callout		 sc_ad_tmo;	/* advertisement timeout */
126 	struct callout		 sc_md_tmo;	/* master down timeout */
127 	struct callout 		 sc_md6_tmo;	/* master down timeout */
128 
129 	LIST_ENTRY(carp_softc)	 sc_next;	/* Interface clue */
130 };
131 #define	SC2IFP(sc)	((sc)->sc_ifp)
132 
133 int carp_suppress_preempt = 0;
134 int carp_opts[CARPCTL_MAXID] = { 0, 1, 0, 1, 0, 0 };	/* XXX for now */
135 SYSCTL_INT(_net_inet_carp, CARPCTL_ALLOW, allow, CTLFLAG_RW,
136     &carp_opts[CARPCTL_ALLOW], 0, "Accept incoming CARP packets");
137 SYSCTL_INT(_net_inet_carp, CARPCTL_PREEMPT, preempt, CTLFLAG_RW,
138     &carp_opts[CARPCTL_PREEMPT], 0, "high-priority backup preemption mode");
139 SYSCTL_INT(_net_inet_carp, CARPCTL_LOG, log, CTLFLAG_RW,
140     &carp_opts[CARPCTL_LOG], 0, "log bad carp packets");
141 SYSCTL_INT(_net_inet_carp, CARPCTL_ARPBALANCE, arpbalance, CTLFLAG_RW,
142     &carp_opts[CARPCTL_ARPBALANCE], 0, "balance arp responses");
143 SYSCTL_INT(_net_inet_carp, OID_AUTO, suppress_preempt, CTLFLAG_RD,
144     &carp_suppress_preempt, 0, "Preemption is suppressed");
145 
146 struct carpstats carpstats;
147 SYSCTL_STRUCT(_net_inet_carp, CARPCTL_STATS, stats, CTLFLAG_RW,
148     &carpstats, carpstats,
149     "CARP statistics (struct carpstats, netinet/ip_carp.h)");
150 
151 struct carp_if {
152 	TAILQ_HEAD(, carp_softc) vhif_vrs;
153 	int vhif_nvrs;
154 
155 	struct ifnet 	*vhif_ifp;
156 	struct mtx	 vhif_mtx;
157 };
158 
159 /* Get carp_if from softc. Valid after carp_set_addr{,6}. */
160 #define	SC2CIF(sc)		((struct carp_if *)(sc)->sc_carpdev->if_carp)
161 
162 /* lock per carp_if queue */
163 #define	CARP_LOCK_INIT(cif)	mtx_init(&(cif)->vhif_mtx, "carp_if", 	\
164 	NULL, MTX_DEF)
165 #define	CARP_LOCK_DESTROY(cif)	mtx_destroy(&(cif)->vhif_mtx)
166 #define	CARP_LOCK_ASSERT(cif)	mtx_assert(&(cif)->vhif_mtx, MA_OWNED)
167 #define	CARP_LOCK(cif)		mtx_lock(&(cif)->vhif_mtx)
168 #define	CARP_UNLOCK(cif)	mtx_unlock(&(cif)->vhif_mtx)
169 
170 #define	CARP_SCLOCK(sc)		mtx_lock(&SC2CIF(sc)->vhif_mtx)
171 #define	CARP_SCUNLOCK(sc)	mtx_unlock(&SC2CIF(sc)->vhif_mtx)
172 #define	CARP_SCLOCK_ASSERT(sc)	mtx_assert(&SC2CIF(sc)->vhif_mtx, MA_OWNED)
173 
174 #define	CARP_LOG(...)	do {				\
175 	if (carp_opts[CARPCTL_LOG] > 0)			\
176 		log(LOG_INFO, __VA_ARGS__);		\
177 } while (0)
178 
179 #define	CARP_DEBUG(...)	do {				\
180 	if (carp_opts[CARPCTL_LOG] > 1)			\
181 		log(LOG_DEBUG, __VA_ARGS__);		\
182 } while (0)
183 
184 static void	carp_hmac_prepare(struct carp_softc *);
185 static void	carp_hmac_generate(struct carp_softc *, u_int32_t *,
186 		    unsigned char *);
187 static int	carp_hmac_verify(struct carp_softc *, u_int32_t *,
188 		    unsigned char *);
189 static void	carp_setroute(struct carp_softc *, int);
190 static void	carp_input_c(struct mbuf *, struct carp_header *, sa_family_t);
191 static int 	carp_clone_create(struct if_clone *, int);
192 static void 	carp_clone_destroy(struct ifnet *);
193 static void	carpdetach(struct carp_softc *);
194 static int	carp_prepare_ad(struct mbuf *, struct carp_softc *,
195 		    struct carp_header *);
196 static void	carp_send_ad_all(void);
197 static void	carp_send_ad(void *);
198 static void	carp_send_ad_locked(struct carp_softc *);
199 static void	carp_send_arp(struct carp_softc *);
200 static void	carp_master_down(void *);
201 static void	carp_master_down_locked(struct carp_softc *);
202 static int	carp_ioctl(struct ifnet *, u_long, caddr_t);
203 static int	carp_looutput(struct ifnet *, struct mbuf *, struct sockaddr *,
204 		    struct rtentry *);
205 static void	carp_start(struct ifnet *);
206 static void	carp_setrun(struct carp_softc *, sa_family_t);
207 static void	carp_set_state(struct carp_softc *, int);
208 static int	carp_addrcount(struct carp_if *, struct in_ifaddr *, int);
209 enum	{ CARP_COUNT_MASTER, CARP_COUNT_RUNNING };
210 
211 static int	carp_set_addr(struct carp_softc *, struct sockaddr_in *);
212 static int	carp_del_addr(struct carp_softc *, struct sockaddr_in *);
213 static void	carp_carpdev_state_locked(struct carp_if *);
214 static void	carp_sc_state_locked(struct carp_softc *);
215 #ifdef INET6
216 static void	carp_send_na(struct carp_softc *);
217 static int	carp_set_addr6(struct carp_softc *, struct sockaddr_in6 *);
218 static int	carp_del_addr6(struct carp_softc *, struct sockaddr_in6 *);
219 #endif
220 
221 static LIST_HEAD(, carp_softc) carpif_list;
222 static struct mtx carp_mtx;
223 IFC_SIMPLE_DECLARE(carp, 0);
224 
225 static __inline u_int16_t
226 carp_cksum(struct mbuf *m, int len)
227 {
228 	return (in_cksum(m, len));
229 }
230 
231 static void
232 carp_hmac_prepare(struct carp_softc *sc)
233 {
234 	u_int8_t version = CARP_VERSION, type = CARP_ADVERTISEMENT;
235 	u_int8_t vhid = sc->sc_vhid & 0xff;
236 	struct ifaddr *ifa;
237 	int i;
238 #ifdef INET6
239 	struct in6_addr in6;
240 #endif
241 
242 	if (sc->sc_carpdev)
243 		CARP_SCLOCK(sc);
244 
245 	/* XXX: possible race here */
246 
247 	/* compute ipad from key */
248 	bzero(sc->sc_pad, sizeof(sc->sc_pad));
249 	bcopy(sc->sc_key, sc->sc_pad, sizeof(sc->sc_key));
250 	for (i = 0; i < sizeof(sc->sc_pad); i++)
251 		sc->sc_pad[i] ^= 0x36;
252 
253 	/* precompute first part of inner hash */
254 	SHA1Init(&sc->sc_sha1);
255 	SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad));
256 	SHA1Update(&sc->sc_sha1, (void *)&version, sizeof(version));
257 	SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type));
258 	SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid));
259 #ifdef INET
260 	TAILQ_FOREACH(ifa, &SC2IFP(sc)->if_addrlist, ifa_list) {
261 		if (ifa->ifa_addr->sa_family == AF_INET)
262 			SHA1Update(&sc->sc_sha1,
263 			    (void *)&ifatoia(ifa)->ia_addr.sin_addr.s_addr,
264 			    sizeof(struct in_addr));
265 	}
266 #endif /* INET */
267 #ifdef INET6
268 	TAILQ_FOREACH(ifa, &SC2IFP(sc)->if_addrlist, ifa_list) {
269 		if (ifa->ifa_addr->sa_family == AF_INET6) {
270 			in6 = ifatoia6(ifa)->ia_addr.sin6_addr;
271 			if (IN6_IS_ADDR_LINKLOCAL(&in6))
272 				in6.s6_addr16[1] = 0;
273 			SHA1Update(&sc->sc_sha1, (void *)&in6, sizeof(in6));
274 		}
275 	}
276 #endif /* INET6 */
277 
278 	/* convert ipad to opad */
279 	for (i = 0; i < sizeof(sc->sc_pad); i++)
280 		sc->sc_pad[i] ^= 0x36 ^ 0x5c;
281 
282 	if (sc->sc_carpdev)
283 		CARP_SCUNLOCK(sc);
284 }
285 
286 static void
287 carp_hmac_generate(struct carp_softc *sc, u_int32_t counter[2],
288     unsigned char md[20])
289 {
290 	SHA1_CTX sha1ctx;
291 
292 	/* fetch first half of inner hash */
293 	bcopy(&sc->sc_sha1, &sha1ctx, sizeof(sha1ctx));
294 
295 	SHA1Update(&sha1ctx, (void *)counter, sizeof(sc->sc_counter));
296 	SHA1Final(md, &sha1ctx);
297 
298 	/* outer hash */
299 	SHA1Init(&sha1ctx);
300 	SHA1Update(&sha1ctx, sc->sc_pad, sizeof(sc->sc_pad));
301 	SHA1Update(&sha1ctx, md, 20);
302 	SHA1Final(md, &sha1ctx);
303 }
304 
305 static int
306 carp_hmac_verify(struct carp_softc *sc, u_int32_t counter[2],
307     unsigned char md[20])
308 {
309 	unsigned char md2[20];
310 
311 	CARP_SCLOCK_ASSERT(sc);
312 
313 	carp_hmac_generate(sc, counter, md2);
314 
315 	return (bcmp(md, md2, sizeof(md2)));
316 }
317 
318 static void
319 carp_setroute(struct carp_softc *sc, int cmd)
320 {
321 	struct ifaddr *ifa;
322 	int s;
323 
324 	if (sc->sc_carpdev)
325 		CARP_SCLOCK_ASSERT(sc);
326 
327 	s = splnet();
328 	TAILQ_FOREACH(ifa, &SC2IFP(sc)->if_addrlist, ifa_list) {
329 		if (ifa->ifa_addr->sa_family == AF_INET &&
330 		    sc->sc_carpdev != NULL) {
331 			int count = carp_addrcount(
332 			    (struct carp_if *)sc->sc_carpdev->if_carp,
333 			    ifatoia(ifa), CARP_COUNT_MASTER);
334 
335 			if ((cmd == RTM_ADD && count == 1) ||
336 			    (cmd == RTM_DELETE && count == 0))
337 				rtinit(ifa, cmd, RTF_UP | RTF_HOST);
338 		}
339 #ifdef INET6
340 		if (ifa->ifa_addr->sa_family == AF_INET6) {
341 			if (cmd == RTM_ADD)
342 				in6_ifaddloop(ifa);
343 			else
344 				in6_ifremloop(ifa);
345 		}
346 #endif /* INET6 */
347 	}
348 	splx(s);
349 }
350 
351 static int
352 carp_clone_create(struct if_clone *ifc, int unit)
353 {
354 
355 	struct carp_softc *sc;
356 	struct ifnet *ifp;
357 
358 	MALLOC(sc, struct carp_softc *, sizeof(*sc), M_CARP, M_WAITOK|M_ZERO);
359 	ifp = SC2IFP(sc) = if_alloc(IFT_ETHER);
360 	if (ifp == NULL) {
361 		FREE(sc, M_CARP);
362 		return (ENOSPC);
363 	}
364 
365 	sc->sc_flags_backup = 0;
366 	sc->sc_suppress = 0;
367 	sc->sc_advbase = CARP_DFLTINTV;
368 	sc->sc_vhid = -1;	/* required setting */
369 	sc->sc_advskew = 0;
370 	sc->sc_init_counter = 1;
371 	sc->sc_naddrs = sc->sc_naddrs6 = 0; /* M_ZERO? */
372 #ifdef INET6
373 	sc->sc_im6o.im6o_multicast_hlim = CARP_DFLTTL;
374 #endif
375 
376 	callout_init(&sc->sc_ad_tmo, NET_CALLOUT_MPSAFE);
377 	callout_init(&sc->sc_md_tmo, NET_CALLOUT_MPSAFE);
378 	callout_init(&sc->sc_md6_tmo, NET_CALLOUT_MPSAFE);
379 
380 	ifp->if_softc = sc;
381 	if_initname(ifp, CARP_IFNAME, unit);
382 	ifp->if_mtu = ETHERMTU;
383 	ifp->if_flags = 0;
384 	ifp->if_ioctl = carp_ioctl;
385 	ifp->if_output = carp_looutput;
386 	ifp->if_start = carp_start;
387 	ifp->if_type = IFT_CARP;
388 	ifp->if_snd.ifq_maxlen = ifqmaxlen;
389 	ifp->if_hdrlen = 0;
390 	if_attach(ifp);
391 	bpfattach(SC2IFP(sc), DLT_NULL, sizeof(u_int32_t));
392 	mtx_lock(&carp_mtx);
393 	LIST_INSERT_HEAD(&carpif_list, sc, sc_next);
394 	mtx_unlock(&carp_mtx);
395 	return (0);
396 }
397 
398 static void
399 carp_clone_destroy(struct ifnet *ifp)
400 {
401 	struct carp_softc *sc = ifp->if_softc;
402 	struct carp_if *cif;
403 	struct ip_moptions *imo = &sc->sc_imo;
404 #ifdef INET6
405 	struct ip6_moptions *im6o = &sc->sc_im6o;
406 #endif
407 
408 /*	carpdetach(sc); */
409 
410 	/*
411 	 * If an interface is destroyed which is suppressing the preemption,
412 	 * decrease the global counter, otherwise the host will never get
413 	 * out of the carp supressing state.
414 	 */
415 	if (sc->sc_suppress)
416 		carp_suppress_preempt--;
417 	sc->sc_suppress = 0;
418 
419 	callout_stop(&sc->sc_ad_tmo);
420 	callout_stop(&sc->sc_md_tmo);
421 	callout_stop(&sc->sc_md6_tmo);
422 
423 	if (imo->imo_num_memberships) {
424 		in_delmulti(imo->imo_membership[--imo->imo_num_memberships]);
425 		imo->imo_multicast_ifp = NULL;
426 	}
427 #ifdef INET6
428 	while (!LIST_EMPTY(&im6o->im6o_memberships)) {
429 		struct in6_multi_mship *imm =
430 		    LIST_FIRST(&im6o->im6o_memberships);
431 		LIST_REMOVE(imm, i6mm_chain);
432 		in6_leavegroup(imm);
433 	}
434 	im6o->im6o_multicast_ifp = NULL;
435 #endif
436 
437 	/* Remove ourself from parents if_carp queue */
438 	if (sc->sc_carpdev && (cif = sc->sc_carpdev->if_carp)) {
439 		CARP_LOCK(cif);
440 		TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list);
441 		if (!--cif->vhif_nvrs) {
442 			sc->sc_carpdev->if_carp = NULL;
443 			CARP_LOCK_DESTROY(cif);
444 			FREE(cif, M_CARP);
445 			ifpromisc(sc->sc_carpdev, 0);
446 		} else {
447 			CARP_UNLOCK(cif);
448 		}
449 	}
450 
451 	mtx_lock(&carp_mtx);
452 	LIST_REMOVE(sc, sc_next);
453 	mtx_unlock(&carp_mtx);
454 	bpfdetach(ifp);
455 	if_detach(ifp);
456 	if_free_type(ifp, IFT_ETHER);
457 	free(sc, M_CARP);
458 }
459 
460 /*
461  * process input packet.
462  * we have rearranged checks order compared to the rfc,
463  * but it seems more efficient this way or not possible otherwise.
464  */
465 void
466 carp_input(struct mbuf *m, int hlen)
467 {
468 	struct ip *ip = mtod(m, struct ip *);
469 	struct carp_header *ch;
470 	int iplen, len;
471 
472 	carpstats.carps_ipackets++;
473 
474 	if (!carp_opts[CARPCTL_ALLOW]) {
475 		m_freem(m);
476 		return;
477 	}
478 
479 	/* check if received on a valid carp interface */
480 	if (m->m_pkthdr.rcvif->if_carp == NULL) {
481 		carpstats.carps_badif++;
482 		CARP_LOG("carp_input: packet received on non-carp "
483 		    "interface: %s\n",
484 		    m->m_pkthdr.rcvif->if_xname);
485 		m_freem(m);
486 		return;
487 	}
488 
489 	/* verify that the IP TTL is 255.  */
490 	if (ip->ip_ttl != CARP_DFLTTL) {
491 		carpstats.carps_badttl++;
492 		CARP_LOG("carp_input: received ttl %d != 255i on %s\n",
493 		    ip->ip_ttl,
494 		    m->m_pkthdr.rcvif->if_xname);
495 		m_freem(m);
496 		return;
497 	}
498 
499 	iplen = ip->ip_hl << 2;
500 
501 	if (m->m_pkthdr.len < iplen + sizeof(*ch)) {
502 		carpstats.carps_badlen++;
503 		CARP_LOG("carp_input: received len %zd < "
504 		    "sizeof(struct carp_header)\n",
505 		    m->m_len - sizeof(struct ip));
506 		m_freem(m);
507 		return;
508 	}
509 
510 	if (iplen + sizeof(*ch) < m->m_len) {
511 		if ((m = m_pullup(m, iplen + sizeof(*ch))) == NULL) {
512 			carpstats.carps_hdrops++;
513 			CARP_LOG("carp_input: pullup failed\n");
514 			return;
515 		}
516 		ip = mtod(m, struct ip *);
517 	}
518 	ch = (struct carp_header *)((char *)ip + iplen);
519 
520 	/*
521 	 * verify that the received packet length is
522 	 * equal to the CARP header
523 	 */
524 	len = iplen + sizeof(*ch);
525 	if (len > m->m_pkthdr.len) {
526 		carpstats.carps_badlen++;
527 		CARP_LOG("carp_input: packet too short %d on %s\n",
528 		    m->m_pkthdr.len,
529 		    m->m_pkthdr.rcvif->if_xname);
530 		m_freem(m);
531 		return;
532 	}
533 
534 	if ((m = m_pullup(m, len)) == NULL) {
535 		carpstats.carps_hdrops++;
536 		return;
537 	}
538 	ip = mtod(m, struct ip *);
539 	ch = (struct carp_header *)((char *)ip + iplen);
540 
541 	/* verify the CARP checksum */
542 	m->m_data += iplen;
543 	if (carp_cksum(m, len - iplen)) {
544 		carpstats.carps_badsum++;
545 		CARP_LOG("carp_input: checksum failed on %s\n",
546 		    m->m_pkthdr.rcvif->if_xname);
547 		m_freem(m);
548 		return;
549 	}
550 	m->m_data -= iplen;
551 
552 	carp_input_c(m, ch, AF_INET);
553 }
554 
555 #ifdef INET6
556 int
557 carp6_input(struct mbuf **mp, int *offp, int proto)
558 {
559 	struct mbuf *m = *mp;
560 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
561 	struct carp_header *ch;
562 	u_int len;
563 
564 	carpstats.carps_ipackets6++;
565 
566 	if (!carp_opts[CARPCTL_ALLOW]) {
567 		m_freem(m);
568 		return (IPPROTO_DONE);
569 	}
570 
571 	/* check if received on a valid carp interface */
572 	if (m->m_pkthdr.rcvif->if_carp == NULL) {
573 		carpstats.carps_badif++;
574 		CARP_LOG("carp6_input: packet received on non-carp "
575 		    "interface: %s\n",
576 		    m->m_pkthdr.rcvif->if_xname);
577 		m_freem(m);
578 		return (IPPROTO_DONE);
579 	}
580 
581 	/* verify that the IP TTL is 255 */
582 	if (ip6->ip6_hlim != CARP_DFLTTL) {
583 		carpstats.carps_badttl++;
584 		CARP_LOG("carp6_input: received ttl %d != 255 on %s\n",
585 		    ip6->ip6_hlim,
586 		    m->m_pkthdr.rcvif->if_xname);
587 		m_freem(m);
588 		return (IPPROTO_DONE);
589 	}
590 
591 	/* verify that we have a complete carp packet */
592 	len = m->m_len;
593 	IP6_EXTHDR_GET(ch, struct carp_header *, m, *offp, sizeof(*ch));
594 	if (ch == NULL) {
595 		carpstats.carps_badlen++;
596 		CARP_LOG("carp6_input: packet size %u too small\n", len);
597 		return (IPPROTO_DONE);
598 	}
599 
600 
601 	/* verify the CARP checksum */
602 	m->m_data += *offp;
603 	if (carp_cksum(m, sizeof(*ch))) {
604 		carpstats.carps_badsum++;
605 		CARP_LOG("carp6_input: checksum failed, on %s\n",
606 		    m->m_pkthdr.rcvif->if_xname);
607 		m_freem(m);
608 		return (IPPROTO_DONE);
609 	}
610 	m->m_data -= *offp;
611 
612 	carp_input_c(m, ch, AF_INET6);
613 	return (IPPROTO_DONE);
614 }
615 #endif /* INET6 */
616 
617 static void
618 carp_input_c(struct mbuf *m, struct carp_header *ch, sa_family_t af)
619 {
620 	struct ifnet *ifp = m->m_pkthdr.rcvif;
621 	struct carp_softc *sc;
622 	u_int64_t tmp_counter;
623 	struct timeval sc_tv, ch_tv;
624 
625 	/* verify that the VHID is valid on the receiving interface */
626 	CARP_LOCK(ifp->if_carp);
627 	TAILQ_FOREACH(sc, &((struct carp_if *)ifp->if_carp)->vhif_vrs, sc_list)
628 		if (sc->sc_vhid == ch->carp_vhid)
629 			break;
630 
631 	if (!sc || (SC2IFP(sc)->if_flags & (IFF_UP|IFF_RUNNING)) !=
632 	    (IFF_UP|IFF_RUNNING)) {
633 		carpstats.carps_badvhid++;
634 		CARP_UNLOCK(ifp->if_carp);
635 		m_freem(m);
636 		return;
637 	}
638 
639 	getmicrotime(&SC2IFP(sc)->if_lastchange);
640 	SC2IFP(sc)->if_ipackets++;
641 	SC2IFP(sc)->if_ibytes += m->m_pkthdr.len;
642 
643 	if (SC2IFP(sc)->if_bpf) {
644 		struct ip *ip = mtod(m, struct ip *);
645 		uint32_t af1 = af;
646 
647 		/* BPF wants net byte order */
648 		ip->ip_len = htons(ip->ip_len + (ip->ip_hl << 2));
649 		ip->ip_off = htons(ip->ip_off);
650 		bpf_mtap2(SC2IFP(sc)->if_bpf, &af1, sizeof(af1), m);
651 	}
652 
653 	/* verify the CARP version. */
654 	if (ch->carp_version != CARP_VERSION) {
655 		carpstats.carps_badver++;
656 		SC2IFP(sc)->if_ierrors++;
657 		CARP_UNLOCK(ifp->if_carp);
658 		CARP_LOG("%s; invalid version %d\n",
659 		    SC2IFP(sc)->if_xname,
660 		    ch->carp_version);
661 		m_freem(m);
662 		return;
663 	}
664 
665 	/* verify the hash */
666 	if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) {
667 		carpstats.carps_badauth++;
668 		SC2IFP(sc)->if_ierrors++;
669 		CARP_UNLOCK(ifp->if_carp);
670 		CARP_LOG("%s: incorrect hash\n", SC2IFP(sc)->if_xname);
671 		m_freem(m);
672 		return;
673 	}
674 
675 	tmp_counter = ntohl(ch->carp_counter[0]);
676 	tmp_counter = tmp_counter<<32;
677 	tmp_counter += ntohl(ch->carp_counter[1]);
678 
679 	/* XXX Replay protection goes here */
680 
681 	sc->sc_init_counter = 0;
682 	sc->sc_counter = tmp_counter;
683 
684 	sc_tv.tv_sec = sc->sc_advbase;
685 	if (carp_suppress_preempt && sc->sc_advskew <  240)
686 		sc_tv.tv_usec = 240 * 1000000 / 256;
687 	else
688 		sc_tv.tv_usec = sc->sc_advskew * 1000000 / 256;
689 	ch_tv.tv_sec = ch->carp_advbase;
690 	ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256;
691 
692 	switch (sc->sc_state) {
693 	case INIT:
694 		break;
695 	case MASTER:
696 		/*
697 		 * If we receive an advertisement from a master who's going to
698 		 * be more frequent than us, go into BACKUP state.
699 		 */
700 		if (timevalcmp(&sc_tv, &ch_tv, >) ||
701 		    timevalcmp(&sc_tv, &ch_tv, ==)) {
702 			callout_stop(&sc->sc_ad_tmo);
703 			CARP_DEBUG("%s: MASTER -> BACKUP "
704 			   "(more frequent advertisement received)\n",
705 			   SC2IFP(sc)->if_xname);
706 			carp_set_state(sc, BACKUP);
707 			carp_setrun(sc, 0);
708 			carp_setroute(sc, RTM_DELETE);
709 		}
710 		break;
711 	case BACKUP:
712 		/*
713 		 * If we're pre-empting masters who advertise slower than us,
714 		 * and this one claims to be slower, treat him as down.
715 		 */
716 		if (carp_opts[CARPCTL_PREEMPT] &&
717 		    timevalcmp(&sc_tv, &ch_tv, <)) {
718 			CARP_DEBUG("%s: BACKUP -> MASTER "
719 			    "(preempting a slower master)\n",
720 			    SC2IFP(sc)->if_xname);
721 			carp_master_down_locked(sc);
722 			break;
723 		}
724 
725 		/*
726 		 *  If the master is going to advertise at such a low frequency
727 		 *  that he's guaranteed to time out, we'd might as well just
728 		 *  treat him as timed out now.
729 		 */
730 		sc_tv.tv_sec = sc->sc_advbase * 3;
731 		if (timevalcmp(&sc_tv, &ch_tv, <)) {
732 			CARP_DEBUG("%s: BACKUP -> MASTER "
733 			    "(master timed out)\n",
734 			    SC2IFP(sc)->if_xname);
735 			carp_master_down_locked(sc);
736 			break;
737 		}
738 
739 		/*
740 		 * Otherwise, we reset the counter and wait for the next
741 		 * advertisement.
742 		 */
743 		carp_setrun(sc, af);
744 		break;
745 	}
746 
747 	CARP_UNLOCK(ifp->if_carp);
748 
749 	m_freem(m);
750 	return;
751 }
752 
753 static void
754 carpdetach(struct carp_softc *sc)
755 {
756 	struct ifaddr *ifa;
757 
758 	callout_stop(&sc->sc_ad_tmo);
759 	callout_stop(&sc->sc_md_tmo);
760 	callout_stop(&sc->sc_md6_tmo);
761 
762 	while ((ifa = TAILQ_FIRST(&SC2IFP(sc)->if_addrlist)) != NULL)
763 		if (ifa->ifa_addr->sa_family == AF_INET) {
764 			struct in_ifaddr *ia = ifatoia(ifa);
765 
766 			carp_del_addr(sc, &ia->ia_addr);
767 
768 			/* ripped screaming from in_control(SIOCDIFADDR) */
769 			in_ifscrub(SC2IFP(sc), ia);
770 			TAILQ_REMOVE(&SC2IFP(sc)->if_addrlist, ifa, ifa_link);
771 			TAILQ_REMOVE(&in_ifaddrhead, ia, ia_link);
772 			IFAFREE((&ia->ia_ifa));
773 		}
774 }
775 
776 /* Detach an interface from the carp.  */
777 void
778 carp_ifdetach(struct ifnet *ifp)
779 {
780 	struct carp_softc *sc;
781 	struct carp_if *cif = (struct carp_if *)ifp->if_carp;
782 
783 	CARP_LOCK(cif);
784 	TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list)
785 		carpdetach(sc);
786 	CARP_UNLOCK(cif);
787 }
788 
789 static int
790 carp_prepare_ad(struct mbuf *m, struct carp_softc *sc, struct carp_header *ch)
791 {
792 	struct m_tag *mtag;
793 	struct ifnet *ifp = SC2IFP(sc);
794 
795 	if (sc->sc_init_counter) {
796 		/* this could also be seconds since unix epoch */
797 		sc->sc_counter = arc4random();
798 		sc->sc_counter = sc->sc_counter << 32;
799 		sc->sc_counter += arc4random();
800 	} else
801 		sc->sc_counter++;
802 
803 	ch->carp_counter[0] = htonl((sc->sc_counter>>32)&0xffffffff);
804 	ch->carp_counter[1] = htonl(sc->sc_counter&0xffffffff);
805 
806 	carp_hmac_generate(sc, ch->carp_counter, ch->carp_md);
807 
808 	/* Tag packet for carp_output */
809 	mtag = m_tag_get(PACKET_TAG_CARP, sizeof(struct ifnet *), M_NOWAIT);
810 	if (mtag == NULL) {
811 		m_freem(m);
812 		SC2IFP(sc)->if_oerrors++;
813 		return (ENOMEM);
814 	}
815 	bcopy(&ifp, (caddr_t)(mtag + 1), sizeof(struct ifnet *));
816 	m_tag_prepend(m, mtag);
817 
818 	return (0);
819 }
820 
821 static void
822 carp_send_ad_all(void)
823 {
824 	struct carp_softc *sc;
825 
826 	mtx_lock(&carp_mtx);
827 	LIST_FOREACH(sc, &carpif_list, sc_next) {
828 		if (sc->sc_carpdev == NULL)
829 			continue;
830 		CARP_SCLOCK(sc);
831 		if ((SC2IFP(sc)->if_flags & (IFF_UP|IFF_RUNNING)) &&
832 		     sc->sc_state == MASTER)
833 			carp_send_ad_locked(sc);
834 		CARP_SCUNLOCK(sc);
835 	}
836 	mtx_unlock(&carp_mtx);
837 }
838 
839 static void
840 carp_send_ad(void *v)
841 {
842 	struct carp_softc *sc = v;
843 
844 	CARP_SCLOCK(sc);
845 	carp_send_ad_locked(sc);
846 	CARP_SCUNLOCK(sc);
847 }
848 
849 static void
850 carp_send_ad_locked(struct carp_softc *sc)
851 {
852 	struct carp_header ch;
853 	struct timeval tv;
854 	struct carp_header *ch_ptr;
855 	struct mbuf *m;
856 	int len, advbase, advskew;
857 
858 	CARP_SCLOCK_ASSERT(sc);
859 
860 	/* bow out if we've lost our UPness or RUNNINGuiness */
861 	if ((SC2IFP(sc)->if_flags &
862 	    (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING)) {
863 		advbase = 255;
864 		advskew = 255;
865 	} else {
866 		advbase = sc->sc_advbase;
867 		if (!carp_suppress_preempt || sc->sc_advskew > 240)
868 			advskew = sc->sc_advskew;
869 		else
870 			advskew = 240;
871 		tv.tv_sec = advbase;
872 		tv.tv_usec = advskew * 1000000 / 256;
873 	}
874 
875 	ch.carp_version = CARP_VERSION;
876 	ch.carp_type = CARP_ADVERTISEMENT;
877 	ch.carp_vhid = sc->sc_vhid;
878 	ch.carp_advbase = advbase;
879 	ch.carp_advskew = advskew;
880 	ch.carp_authlen = 7;	/* XXX DEFINE */
881 	ch.carp_pad1 = 0;	/* must be zero */
882 	ch.carp_cksum = 0;
883 
884 #ifdef INET
885 	if (sc->sc_ia) {
886 		struct ip *ip;
887 
888 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
889 		if (m == NULL) {
890 			SC2IFP(sc)->if_oerrors++;
891 			carpstats.carps_onomem++;
892 			/* XXX maybe less ? */
893 			if (advbase != 255 || advskew != 255)
894 				callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
895 				    carp_send_ad, sc);
896 			return;
897 		}
898 		len = sizeof(*ip) + sizeof(ch);
899 		m->m_pkthdr.len = len;
900 		m->m_pkthdr.rcvif = NULL;
901 		m->m_len = len;
902 		MH_ALIGN(m, m->m_len);
903 		m->m_flags |= M_MCAST;
904 		ip = mtod(m, struct ip *);
905 		ip->ip_v = IPVERSION;
906 		ip->ip_hl = sizeof(*ip) >> 2;
907 		ip->ip_tos = IPTOS_LOWDELAY;
908 		ip->ip_len = len;
909 		ip->ip_id = ip_newid();
910 		ip->ip_off = IP_DF;
911 		ip->ip_ttl = CARP_DFLTTL;
912 		ip->ip_p = IPPROTO_CARP;
913 		ip->ip_sum = 0;
914 		ip->ip_src.s_addr = sc->sc_ia->ia_addr.sin_addr.s_addr;
915 		ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP);
916 
917 		ch_ptr = (struct carp_header *)(&ip[1]);
918 		bcopy(&ch, ch_ptr, sizeof(ch));
919 		if (carp_prepare_ad(m, sc, ch_ptr))
920 			return;
921 
922 		m->m_data += sizeof(*ip);
923 		ch_ptr->carp_cksum = carp_cksum(m, len - sizeof(*ip));
924 		m->m_data -= sizeof(*ip);
925 
926 		getmicrotime(&SC2IFP(sc)->if_lastchange);
927 		SC2IFP(sc)->if_opackets++;
928 		SC2IFP(sc)->if_obytes += len;
929 		carpstats.carps_opackets++;
930 
931 		if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo, NULL)) {
932 			SC2IFP(sc)->if_oerrors++;
933 			if (sc->sc_sendad_errors < INT_MAX)
934 				sc->sc_sendad_errors++;
935 			if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
936 				carp_suppress_preempt++;
937 				if (carp_suppress_preempt == 1) {
938 					CARP_SCUNLOCK(sc);
939 					carp_send_ad_all();
940 					CARP_SCLOCK(sc);
941 				}
942 			}
943 			sc->sc_sendad_success = 0;
944 		} else {
945 			if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
946 				if (++sc->sc_sendad_success >=
947 				    CARP_SENDAD_MIN_SUCCESS) {
948 					carp_suppress_preempt--;
949 					sc->sc_sendad_errors = 0;
950 				}
951 			} else
952 				sc->sc_sendad_errors = 0;
953 		}
954 	}
955 #endif /* INET */
956 #ifdef INET6
957 	if (sc->sc_ia6) {
958 		struct ip6_hdr *ip6;
959 
960 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
961 		if (m == NULL) {
962 			SC2IFP(sc)->if_oerrors++;
963 			carpstats.carps_onomem++;
964 			/* XXX maybe less ? */
965 			if (advbase != 255 || advskew != 255)
966 				callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
967 				    carp_send_ad, sc);
968 			return;
969 		}
970 		len = sizeof(*ip6) + sizeof(ch);
971 		m->m_pkthdr.len = len;
972 		m->m_pkthdr.rcvif = NULL;
973 		m->m_len = len;
974 		MH_ALIGN(m, m->m_len);
975 		m->m_flags |= M_MCAST;
976 		ip6 = mtod(m, struct ip6_hdr *);
977 		bzero(ip6, sizeof(*ip6));
978 		ip6->ip6_vfc |= IPV6_VERSION;
979 		ip6->ip6_hlim = CARP_DFLTTL;
980 		ip6->ip6_nxt = IPPROTO_CARP;
981 		bcopy(&sc->sc_ia6->ia_addr.sin6_addr, &ip6->ip6_src,
982 		    sizeof(struct in6_addr));
983 		/* set the multicast destination */
984 
985 		ip6->ip6_dst.s6_addr8[0] = 0xff;
986 		ip6->ip6_dst.s6_addr8[1] = 0x02;
987 		ip6->ip6_dst.s6_addr8[15] = 0x12;
988 
989 		ch_ptr = (struct carp_header *)(&ip6[1]);
990 		bcopy(&ch, ch_ptr, sizeof(ch));
991 		if (carp_prepare_ad(m, sc, ch_ptr))
992 			return;
993 
994 		m->m_data += sizeof(*ip6);
995 		ch_ptr->carp_cksum = carp_cksum(m, len - sizeof(*ip6));
996 		m->m_data -= sizeof(*ip6);
997 
998 		getmicrotime(&SC2IFP(sc)->if_lastchange);
999 		SC2IFP(sc)->if_opackets++;
1000 		SC2IFP(sc)->if_obytes += len;
1001 		carpstats.carps_opackets6++;
1002 
1003 		if (ip6_output(m, NULL, NULL, 0, &sc->sc_im6o, NULL, NULL)) {
1004 			SC2IFP(sc)->if_oerrors++;
1005 			if (sc->sc_sendad_errors < INT_MAX)
1006 				sc->sc_sendad_errors++;
1007 			if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
1008 				carp_suppress_preempt++;
1009 				if (carp_suppress_preempt == 1) {
1010 					CARP_SCUNLOCK(sc);
1011 					carp_send_ad_all();
1012 					CARP_SCLOCK(sc);
1013 				}
1014 			}
1015 			sc->sc_sendad_success = 0;
1016 		} else {
1017 			if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
1018 				if (++sc->sc_sendad_success >=
1019 				    CARP_SENDAD_MIN_SUCCESS) {
1020 					carp_suppress_preempt--;
1021 					sc->sc_sendad_errors = 0;
1022 				}
1023 			} else
1024 				sc->sc_sendad_errors = 0;
1025 		}
1026 	}
1027 #endif /* INET6 */
1028 
1029 	if (advbase != 255 || advskew != 255)
1030 		callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1031 		    carp_send_ad, sc);
1032 
1033 }
1034 
1035 /*
1036  * Broadcast a gratuitous ARP request containing
1037  * the virtual router MAC address for each IP address
1038  * associated with the virtual router.
1039  */
1040 static void
1041 carp_send_arp(struct carp_softc *sc)
1042 {
1043 	struct ifaddr *ifa;
1044 
1045 	TAILQ_FOREACH(ifa, &SC2IFP(sc)->if_addrlist, ifa_list) {
1046 
1047 		if (ifa->ifa_addr->sa_family != AF_INET)
1048 			continue;
1049 
1050 /*		arprequest(sc->sc_carpdev, &in, &in, IFP2ENADDR(sc->sc_ifp)); */
1051 		arp_ifinit2(sc->sc_carpdev, ifa, IFP2ENADDR(sc->sc_ifp));
1052 
1053 		DELAY(1000);	/* XXX */
1054 	}
1055 }
1056 
1057 #ifdef INET6
1058 static void
1059 carp_send_na(struct carp_softc *sc)
1060 {
1061 	struct ifaddr *ifa;
1062 	struct in6_addr *in6;
1063 	static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1064 
1065 	TAILQ_FOREACH(ifa, &SC2IFP(sc)->if_addrlist, ifa_list) {
1066 
1067 		if (ifa->ifa_addr->sa_family != AF_INET6)
1068 			continue;
1069 
1070 		in6 = &ifatoia6(ifa)->ia_addr.sin6_addr;
1071 		nd6_na_output(sc->sc_carpdev, &mcast, in6,
1072 		    ND_NA_FLAG_OVERRIDE, 1, NULL);
1073 		DELAY(1000);	/* XXX */
1074 	}
1075 }
1076 #endif /* INET6 */
1077 
1078 static int
1079 carp_addrcount(struct carp_if *cif, struct in_ifaddr *ia, int type)
1080 {
1081 	struct carp_softc *vh;
1082 	struct ifaddr *ifa;
1083 	int count = 0;
1084 
1085 	CARP_LOCK_ASSERT(cif);
1086 
1087 	TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1088 		if ((type == CARP_COUNT_RUNNING &&
1089 		    (SC2IFP(vh)->if_flags & (IFF_UP|IFF_RUNNING)) ==
1090 		    (IFF_UP|IFF_RUNNING)) ||
1091 		    (type == CARP_COUNT_MASTER && vh->sc_state == MASTER)) {
1092 			TAILQ_FOREACH(ifa, &SC2IFP(vh)->if_addrlist,
1093 			    ifa_list) {
1094 				if (ifa->ifa_addr->sa_family == AF_INET &&
1095 				    ia->ia_addr.sin_addr.s_addr ==
1096 				    ifatoia(ifa)->ia_addr.sin_addr.s_addr)
1097 					count++;
1098 			}
1099 		}
1100 	}
1101 	return (count);
1102 }
1103 
1104 int
1105 carp_iamatch(void *v, struct in_ifaddr *ia,
1106     struct in_addr *isaddr, u_int8_t **enaddr)
1107 {
1108 	struct carp_if *cif = v;
1109 	struct carp_softc *vh;
1110 	int index, count = 0;
1111 	struct ifaddr *ifa;
1112 
1113 	CARP_LOCK(cif);
1114 
1115 	if (carp_opts[CARPCTL_ARPBALANCE]) {
1116 		/*
1117 		 * XXX proof of concept implementation.
1118 		 * We use the source ip to decide which virtual host should
1119 		 * handle the request. If we're master of that virtual host,
1120 		 * then we respond, otherwise, just drop the arp packet on
1121 		 * the floor.
1122 		 */
1123 		count = carp_addrcount(cif, ia, CARP_COUNT_RUNNING);
1124 		if (count == 0) {
1125 			/* should never reach this */
1126 			CARP_UNLOCK(cif);
1127 			return (0);
1128 		}
1129 
1130 		/* this should be a hash, like pf_hash() */
1131 		index = isaddr->s_addr % count;
1132 		count = 0;
1133 
1134 		TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1135 			if ((SC2IFP(vh)->if_flags & (IFF_UP|IFF_RUNNING)) ==
1136 			    (IFF_UP|IFF_RUNNING)) {
1137 				TAILQ_FOREACH(ifa, &SC2IFP(vh)->if_addrlist,
1138 				    ifa_list) {
1139 					if (ifa->ifa_addr->sa_family ==
1140 					    AF_INET &&
1141 					    ia->ia_addr.sin_addr.s_addr ==
1142 					    ifatoia(ifa)->ia_addr.sin_addr.s_addr) {
1143 						if (count == index) {
1144 							if (vh->sc_state ==
1145 							    MASTER) {
1146 								*enaddr = IFP2ENADDR(vh->sc_ifp);
1147 								CARP_UNLOCK(cif);
1148 								return (1);
1149 							} else {
1150 								CARP_UNLOCK(cif);
1151 								return (0);
1152 							}
1153 						}
1154 						count++;
1155 					}
1156 				}
1157 			}
1158 		}
1159 	} else {
1160 		TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1161 			if ((SC2IFP(vh)->if_flags & (IFF_UP|IFF_RUNNING)) ==
1162 			    (IFF_UP|IFF_RUNNING) && ia->ia_ifp ==
1163 			    SC2IFP(vh)) {
1164 				*enaddr = IFP2ENADDR(vh->sc_ifp);
1165 				CARP_UNLOCK(cif);
1166 				return (1);
1167 			}
1168 		}
1169 	}
1170 	CARP_UNLOCK(cif);
1171 	return (0);
1172 }
1173 
1174 #ifdef INET6
1175 struct ifaddr *
1176 carp_iamatch6(void *v, struct in6_addr *taddr)
1177 {
1178 	struct carp_if *cif = v;
1179 	struct carp_softc *vh;
1180 	struct ifaddr *ifa;
1181 
1182 	CARP_LOCK(cif);
1183 	TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1184 		TAILQ_FOREACH(ifa, &SC2IFP(vh)->if_addrlist, ifa_list) {
1185 			if (IN6_ARE_ADDR_EQUAL(taddr,
1186 			    &ifatoia6(ifa)->ia_addr.sin6_addr) &&
1187  			    ((SC2IFP(vh)->if_flags &
1188 			    (IFF_UP|IFF_RUNNING)) == (IFF_UP|IFF_RUNNING))) {
1189 			    	CARP_UNLOCK(cif);
1190 				return (ifa);
1191 			}
1192 		}
1193 	}
1194 	CARP_UNLOCK(cif);
1195 
1196 	return (NULL);
1197 }
1198 
1199 void *
1200 carp_macmatch6(void *v, struct mbuf *m, const struct in6_addr *taddr)
1201 {
1202 	struct m_tag *mtag;
1203 	struct carp_if *cif = v;
1204 	struct carp_softc *sc;
1205 	struct ifaddr *ifa;
1206 
1207 	CARP_LOCK(cif);
1208 	TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) {
1209 		TAILQ_FOREACH(ifa, &SC2IFP(sc)->if_addrlist, ifa_list) {
1210 			if (IN6_ARE_ADDR_EQUAL(taddr,
1211 			    &ifatoia6(ifa)->ia_addr.sin6_addr) &&
1212  			    ((SC2IFP(sc)->if_flags &
1213 			    (IFF_UP|IFF_RUNNING)) == (IFF_UP|IFF_RUNNING))) {
1214 				struct ifnet *ifp = SC2IFP(sc);
1215 				mtag = m_tag_get(PACKET_TAG_CARP,
1216 				    sizeof(struct ifnet *), M_NOWAIT);
1217 				if (mtag == NULL) {
1218 					/* better a bit than nothing */
1219 					CARP_UNLOCK(cif);
1220 					return (IFP2ENADDR(sc->sc_ifp));
1221 				}
1222 				bcopy(&ifp, (caddr_t)(mtag + 1),
1223 				    sizeof(struct ifnet *));
1224 				m_tag_prepend(m, mtag);
1225 
1226 				CARP_UNLOCK(cif);
1227 				return (IFP2ENADDR(sc->sc_ifp));
1228 			}
1229 		}
1230 	}
1231 	CARP_UNLOCK(cif);
1232 
1233 	return (NULL);
1234 }
1235 #endif
1236 
1237 struct ifnet *
1238 carp_forus(void *v, void *dhost)
1239 {
1240 	struct carp_if *cif = v;
1241 	struct carp_softc *vh;
1242 	u_int8_t *ena = dhost;
1243 
1244 	if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1245 		return (NULL);
1246 
1247 	CARP_LOCK(cif);
1248 	TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list)
1249 		if ((SC2IFP(vh)->if_flags & (IFF_UP|IFF_RUNNING)) ==
1250 		    (IFF_UP|IFF_RUNNING) && vh->sc_state == MASTER &&
1251 		    !bcmp(dhost, IFP2ENADDR(vh->sc_ifp), ETHER_ADDR_LEN)) {
1252 		    	CARP_UNLOCK(cif);
1253 			return (SC2IFP(vh));
1254 		}
1255 
1256     	CARP_UNLOCK(cif);
1257 	return (NULL);
1258 }
1259 
1260 static void
1261 carp_master_down(void *v)
1262 {
1263 	struct carp_softc *sc = v;
1264 
1265 	CARP_SCLOCK(sc);
1266 	carp_master_down_locked(sc);
1267 	CARP_SCUNLOCK(sc);
1268 }
1269 
1270 static void
1271 carp_master_down_locked(struct carp_softc *sc)
1272 {
1273 	if (sc->sc_carpdev)
1274 		CARP_SCLOCK_ASSERT(sc);
1275 
1276 	switch (sc->sc_state) {
1277 	case INIT:
1278 		printf("%s: master_down event in INIT state\n",
1279 		    SC2IFP(sc)->if_xname);
1280 		break;
1281 	case MASTER:
1282 		break;
1283 	case BACKUP:
1284 		carp_set_state(sc, MASTER);
1285 		carp_send_ad_locked(sc);
1286 		carp_send_arp(sc);
1287 #ifdef INET6
1288 		carp_send_na(sc);
1289 #endif /* INET6 */
1290 		carp_setrun(sc, 0);
1291 		carp_setroute(sc, RTM_ADD);
1292 		break;
1293 	}
1294 }
1295 
1296 /*
1297  * When in backup state, af indicates whether to reset the master down timer
1298  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1299  */
1300 static void
1301 carp_setrun(struct carp_softc *sc, sa_family_t af)
1302 {
1303 	struct timeval tv;
1304 
1305 	if (sc->sc_carpdev)
1306 		CARP_SCLOCK_ASSERT(sc);
1307 
1308 	if (SC2IFP(sc)->if_flags & IFF_UP &&
1309 	    sc->sc_vhid > 0 && (sc->sc_naddrs || sc->sc_naddrs6))
1310 		SC2IFP(sc)->if_flags |= IFF_RUNNING;
1311 	else {
1312 		SC2IFP(sc)->if_flags &= ~IFF_RUNNING;
1313 		carp_setroute(sc, RTM_DELETE);
1314 		return;
1315 	}
1316 
1317 	switch (sc->sc_state) {
1318 	case INIT:
1319 		if (carp_opts[CARPCTL_PREEMPT] && !carp_suppress_preempt) {
1320 			carp_send_ad_locked(sc);
1321 			carp_send_arp(sc);
1322 #ifdef INET6
1323 			carp_send_na(sc);
1324 #endif /* INET6 */
1325 			CARP_DEBUG("%s: INIT -> MASTER (preempting)\n",
1326 			    SC2IFP(sc)->if_xname);
1327 			carp_set_state(sc, MASTER);
1328 			carp_setroute(sc, RTM_ADD);
1329 		} else {
1330 			CARP_DEBUG("%s: INIT -> BACKUP\n", SC2IFP(sc)->if_xname);
1331 			carp_set_state(sc, BACKUP);
1332 			carp_setroute(sc, RTM_DELETE);
1333 			carp_setrun(sc, 0);
1334 		}
1335 		break;
1336 	case BACKUP:
1337 		callout_stop(&sc->sc_ad_tmo);
1338 		tv.tv_sec = 3 * sc->sc_advbase;
1339 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1340 		switch (af) {
1341 #ifdef INET
1342 		case AF_INET:
1343 			callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1344 			    carp_master_down, sc);
1345 			break;
1346 #endif /* INET */
1347 #ifdef INET6
1348 		case AF_INET6:
1349 			callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1350 			    carp_master_down, sc);
1351 			break;
1352 #endif /* INET6 */
1353 		default:
1354 			if (sc->sc_naddrs)
1355 				callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1356 				    carp_master_down, sc);
1357 			if (sc->sc_naddrs6)
1358 				callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1359 				    carp_master_down, sc);
1360 			break;
1361 		}
1362 		break;
1363 	case MASTER:
1364 		tv.tv_sec = sc->sc_advbase;
1365 		tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1366 		callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1367 		    carp_send_ad, sc);
1368 		break;
1369 	}
1370 }
1371 
1372 static int
1373 carp_set_addr(struct carp_softc *sc, struct sockaddr_in *sin)
1374 {
1375 	struct ifnet *ifp;
1376 	struct carp_if *cif;
1377 	struct in_ifaddr *ia, *ia_if;
1378 	struct ip_moptions *imo = &sc->sc_imo;
1379 	struct in_addr addr;
1380 	u_long iaddr = htonl(sin->sin_addr.s_addr);
1381 	int own, error;
1382 
1383 	if (sin->sin_addr.s_addr == 0) {
1384 		if (!(SC2IFP(sc)->if_flags & IFF_UP))
1385 			carp_set_state(sc, INIT);
1386 		if (sc->sc_naddrs)
1387 			SC2IFP(sc)->if_flags |= IFF_UP;
1388 		carp_setrun(sc, 0);
1389 		return (0);
1390 	}
1391 
1392 	/* we have to do it by hands to check we won't match on us */
1393 	ia_if = NULL; own = 0;
1394 	TAILQ_FOREACH(ia, &in_ifaddrhead, ia_link) {
1395 		/* and, yeah, we need a multicast-capable iface too */
1396 		if (ia->ia_ifp != SC2IFP(sc) &&
1397 		    (ia->ia_ifp->if_flags & IFF_MULTICAST) &&
1398 		    (iaddr & ia->ia_subnetmask) == ia->ia_subnet) {
1399 			if (!ia_if)
1400 				ia_if = ia;
1401 			if (sin->sin_addr.s_addr ==
1402 			    ia->ia_addr.sin_addr.s_addr)
1403 				own++;
1404 		}
1405 	}
1406 
1407 	if (!ia_if)
1408 		return (EADDRNOTAVAIL);
1409 
1410 	ia = ia_if;
1411 	ifp = ia->ia_ifp;
1412 
1413 	if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0 ||
1414 	    (imo->imo_multicast_ifp && imo->imo_multicast_ifp != ifp))
1415 		return (EADDRNOTAVAIL);
1416 
1417 	if (imo->imo_num_memberships == 0) {
1418 		addr.s_addr = htonl(INADDR_CARP_GROUP);
1419 		if ((imo->imo_membership[0] = in_addmulti(&addr, ifp)) == NULL)
1420 			return (ENOBUFS);
1421 		imo->imo_num_memberships++;
1422 		imo->imo_multicast_ifp = ifp;
1423 		imo->imo_multicast_ttl = CARP_DFLTTL;
1424 		imo->imo_multicast_loop = 0;
1425 	}
1426 
1427 	if (!ifp->if_carp) {
1428 
1429 		MALLOC(cif, struct carp_if *, sizeof(*cif), M_CARP,
1430 		    M_WAITOK|M_ZERO);
1431 		if (!cif) {
1432 			error = ENOBUFS;
1433 			goto cleanup;
1434 		}
1435 		if ((error = ifpromisc(ifp, 1))) {
1436 			FREE(cif, M_CARP);
1437 			goto cleanup;
1438 		}
1439 
1440 		CARP_LOCK_INIT(cif);
1441 		CARP_LOCK(cif);
1442 		cif->vhif_ifp = ifp;
1443 		TAILQ_INIT(&cif->vhif_vrs);
1444 		ifp->if_carp = cif;
1445 
1446 	} else {
1447 		struct carp_softc *vr;
1448 
1449 		cif = (struct carp_if *)ifp->if_carp;
1450 		CARP_LOCK(cif);
1451 		TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list)
1452 			if (vr != sc && vr->sc_vhid == sc->sc_vhid) {
1453 				CARP_UNLOCK(cif);
1454 				error = EINVAL;
1455 				goto cleanup;
1456 			}
1457 	}
1458 	sc->sc_ia = ia;
1459 	sc->sc_carpdev = ifp;
1460 
1461 	{ /* XXX prevent endless loop if already in queue */
1462 	struct carp_softc *vr, *after = NULL;
1463 	int myself = 0;
1464 	cif = (struct carp_if *)ifp->if_carp;
1465 
1466 	/* XXX: cif should not change, right? So we still hold the lock */
1467 	CARP_LOCK_ASSERT(cif);
1468 
1469 	TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1470 		if (vr == sc)
1471 			myself = 1;
1472 		if (vr->sc_vhid < sc->sc_vhid)
1473 			after = vr;
1474 	}
1475 
1476 	if (!myself) {
1477 		/* We're trying to keep things in order */
1478 		if (after == NULL) {
1479 			TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list);
1480 		} else {
1481 			TAILQ_INSERT_AFTER(&cif->vhif_vrs, after, sc, sc_list);
1482 		}
1483 		cif->vhif_nvrs++;
1484 	}
1485 	}
1486 
1487 	sc->sc_naddrs++;
1488 	SC2IFP(sc)->if_flags |= IFF_UP;
1489 	if (own)
1490 		sc->sc_advskew = 0;
1491 	carp_sc_state_locked(sc);
1492 	carp_setrun(sc, 0);
1493 
1494 	CARP_UNLOCK(cif);
1495 
1496 	return (0);
1497 
1498 cleanup:
1499 	in_delmulti(imo->imo_membership[--imo->imo_num_memberships]);
1500 	return (error);
1501 }
1502 
1503 static int
1504 carp_del_addr(struct carp_softc *sc, struct sockaddr_in *sin)
1505 {
1506 	int error = 0;
1507 
1508 	if (!--sc->sc_naddrs) {
1509 		struct carp_if *cif = (struct carp_if *)sc->sc_carpdev->if_carp;
1510 		struct ip_moptions *imo = &sc->sc_imo;
1511 
1512 		CARP_LOCK(cif);
1513 		callout_stop(&sc->sc_ad_tmo);
1514 		SC2IFP(sc)->if_flags &= ~(IFF_UP|IFF_RUNNING);
1515 		sc->sc_vhid = -1;
1516 		in_delmulti(imo->imo_membership[--imo->imo_num_memberships]);
1517 		imo->imo_multicast_ifp = NULL;
1518 		TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list);
1519 		if (!--cif->vhif_nvrs) {
1520 			sc->sc_carpdev->if_carp = NULL;
1521 			CARP_LOCK_DESTROY(cif);
1522 			FREE(cif, M_IFADDR);
1523 		} else {
1524 			CARP_UNLOCK(cif);
1525 		}
1526 	}
1527 
1528 	return (error);
1529 }
1530 
1531 #ifdef INET6
1532 static int
1533 carp_set_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6)
1534 {
1535 	struct ifnet *ifp;
1536 	struct carp_if *cif;
1537 	struct in6_ifaddr *ia, *ia_if;
1538 	struct ip6_moptions *im6o = &sc->sc_im6o;
1539 	struct in6_multi_mship *imm;
1540 	struct sockaddr_in6 addr;
1541 	int own, error;
1542 
1543 	if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1544 		if (!(SC2IFP(sc)->if_flags & IFF_UP))
1545 			carp_set_state(sc, INIT);
1546 		if (sc->sc_naddrs6)
1547 			SC2IFP(sc)->if_flags |= IFF_UP;
1548 		carp_setrun(sc, 0);
1549 		return (0);
1550 	}
1551 
1552 	/* we have to do it by hands to check we won't match on us */
1553 	ia_if = NULL; own = 0;
1554 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1555 		int i;
1556 
1557 		for (i = 0; i < 4; i++) {
1558 			if ((sin6->sin6_addr.s6_addr32[i] &
1559 			    ia->ia_prefixmask.sin6_addr.s6_addr32[i]) !=
1560 			    (ia->ia_addr.sin6_addr.s6_addr32[i] &
1561 			    ia->ia_prefixmask.sin6_addr.s6_addr32[i]))
1562 				break;
1563 		}
1564 		/* and, yeah, we need a multicast-capable iface too */
1565 		if (ia->ia_ifp != SC2IFP(sc) &&
1566 		    (ia->ia_ifp->if_flags & IFF_MULTICAST) &&
1567 		    (i == 4)) {
1568 			if (!ia_if)
1569 				ia_if = ia;
1570 			if (IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
1571 			    &ia->ia_addr.sin6_addr))
1572 				own++;
1573 		}
1574 	}
1575 
1576 	if (!ia_if)
1577 		return (EADDRNOTAVAIL);
1578 	ia = ia_if;
1579 	ifp = ia->ia_ifp;
1580 
1581 	if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0 ||
1582 	    (im6o->im6o_multicast_ifp && im6o->im6o_multicast_ifp != ifp))
1583 		return (EADDRNOTAVAIL);
1584 
1585 	if (!sc->sc_naddrs6) {
1586 		im6o->im6o_multicast_ifp = ifp;
1587 
1588 		/* join CARP multicast address */
1589 		bzero(&addr, sizeof(addr));
1590 		addr.sin6_family = AF_INET6;
1591 		addr.sin6_len = sizeof(addr);
1592 		addr.sin6_addr.s6_addr16[0] = htons(0xff02);
1593 		addr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1594 		addr.sin6_addr.s6_addr8[15] = 0x12;
1595 		if ((imm = in6_joingroup(ifp, &addr.sin6_addr, &error)) == NULL)
1596 			goto cleanup;
1597 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
1598 
1599 		/* join solicited multicast address */
1600 		bzero(&addr.sin6_addr, sizeof(addr.sin6_addr));
1601 		addr.sin6_addr.s6_addr16[0] = htons(0xff02);
1602 		addr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1603 		addr.sin6_addr.s6_addr32[1] = 0;
1604 		addr.sin6_addr.s6_addr32[2] = htonl(1);
1605 		addr.sin6_addr.s6_addr32[3] = sin6->sin6_addr.s6_addr32[3];
1606 		addr.sin6_addr.s6_addr8[12] = 0xff;
1607 		if ((imm = in6_joingroup(ifp, &addr.sin6_addr, &error)) == NULL)
1608 			goto cleanup;
1609 		LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
1610 	}
1611 
1612 	if (!ifp->if_carp) {
1613 		MALLOC(cif, struct carp_if *, sizeof(*cif), M_CARP,
1614 		    M_WAITOK|M_ZERO);
1615 		if (!cif) {
1616 			error = ENOBUFS;
1617 			goto cleanup;
1618 		}
1619 		if ((error = ifpromisc(ifp, 1))) {
1620 			FREE(cif, M_CARP);
1621 			goto cleanup;
1622 		}
1623 
1624 		CARP_LOCK_INIT(cif);
1625 		CARP_LOCK(cif);
1626 		cif->vhif_ifp = ifp;
1627 		TAILQ_INIT(&cif->vhif_vrs);
1628 		ifp->if_carp = cif;
1629 
1630 	} else {
1631 		struct carp_softc *vr;
1632 
1633 		cif = (struct carp_if *)ifp->if_carp;
1634 		CARP_LOCK(cif);
1635 		TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list)
1636 			if (vr != sc && vr->sc_vhid == sc->sc_vhid) {
1637 				CARP_UNLOCK(cif);
1638 				error = EINVAL;
1639 				goto cleanup;
1640 			}
1641 	}
1642 	sc->sc_ia6 = ia;
1643 	sc->sc_carpdev = ifp;
1644 
1645 	{ /* XXX prevent endless loop if already in queue */
1646 	struct carp_softc *vr, *after = NULL;
1647 	int myself = 0;
1648 	cif = (struct carp_if *)ifp->if_carp;
1649 	CARP_LOCK_ASSERT(cif);
1650 
1651 	TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1652 		if (vr == sc)
1653 			myself = 1;
1654 		if (vr->sc_vhid < sc->sc_vhid)
1655 			after = vr;
1656 	}
1657 
1658 	if (!myself) {
1659 		/* We're trying to keep things in order */
1660 		if (after == NULL) {
1661 			TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list);
1662 		} else {
1663 			TAILQ_INSERT_AFTER(&cif->vhif_vrs, after, sc, sc_list);
1664 		}
1665 		cif->vhif_nvrs++;
1666 	}
1667 	}
1668 
1669 	sc->sc_naddrs6++;
1670 	SC2IFP(sc)->if_flags |= IFF_UP;
1671 	if (own)
1672 		sc->sc_advskew = 0;
1673 	carp_sc_state_locked(sc);
1674 	carp_setrun(sc, 0);
1675 
1676 	CARP_UNLOCK(cif);
1677 
1678 	return (0);
1679 
1680 cleanup:
1681 	/* clean up multicast memberships */
1682 	if (!sc->sc_naddrs6) {
1683 		while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1684 			imm = LIST_FIRST(&im6o->im6o_memberships);
1685 			LIST_REMOVE(imm, i6mm_chain);
1686 			in6_leavegroup(imm);
1687 		}
1688 	}
1689 	return (error);
1690 }
1691 
1692 static int
1693 carp_del_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6)
1694 {
1695 	int error = 0;
1696 
1697 	if (!--sc->sc_naddrs6) {
1698 		struct carp_if *cif = (struct carp_if *)sc->sc_carpdev->if_carp;
1699 		struct ip6_moptions *im6o = &sc->sc_im6o;
1700 
1701 		CARP_LOCK(cif);
1702 		callout_stop(&sc->sc_ad_tmo);
1703 		SC2IFP(sc)->if_flags &= ~(IFF_UP|IFF_RUNNING);
1704 		sc->sc_vhid = -1;
1705 		while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1706 			struct in6_multi_mship *imm =
1707 			    LIST_FIRST(&im6o->im6o_memberships);
1708 
1709 			LIST_REMOVE(imm, i6mm_chain);
1710 			in6_leavegroup(imm);
1711 		}
1712 		im6o->im6o_multicast_ifp = NULL;
1713 		TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list);
1714 		if (!--cif->vhif_nvrs) {
1715 			CARP_LOCK_DESTROY(cif);
1716 			sc->sc_carpdev->if_carp = NULL;
1717 			FREE(cif, M_IFADDR);
1718 		} else
1719 			CARP_UNLOCK(cif);
1720 	}
1721 
1722 	return (error);
1723 }
1724 #endif /* INET6 */
1725 
1726 static int
1727 carp_ioctl(struct ifnet *ifp, u_long cmd, caddr_t addr)
1728 {
1729 	struct carp_softc *sc = ifp->if_softc, *vr;
1730 	struct carpreq carpr;
1731 	struct ifaddr *ifa;
1732 	struct ifreq *ifr;
1733 	struct ifaliasreq *ifra;
1734 	int locked = 0, error = 0;
1735 
1736 	ifa = (struct ifaddr *)addr;
1737 	ifra = (struct ifaliasreq *)addr;
1738 	ifr = (struct ifreq *)addr;
1739 
1740 	switch (cmd) {
1741 	case SIOCSIFADDR:
1742 		switch (ifa->ifa_addr->sa_family) {
1743 #ifdef INET
1744 		case AF_INET:
1745 			SC2IFP(sc)->if_flags |= IFF_UP;
1746 			bcopy(ifa->ifa_addr, ifa->ifa_dstaddr,
1747 			    sizeof(struct sockaddr));
1748 			error = carp_set_addr(sc, satosin(ifa->ifa_addr));
1749 			break;
1750 #endif /* INET */
1751 #ifdef INET6
1752 		case AF_INET6:
1753 			SC2IFP(sc)->if_flags |= IFF_UP;
1754 			error = carp_set_addr6(sc, satosin6(ifa->ifa_addr));
1755 			break;
1756 #endif /* INET6 */
1757 		default:
1758 			error = EAFNOSUPPORT;
1759 			break;
1760 		}
1761 		break;
1762 
1763 	case SIOCAIFADDR:
1764 		switch (ifa->ifa_addr->sa_family) {
1765 #ifdef INET
1766 		case AF_INET:
1767 			SC2IFP(sc)->if_flags |= IFF_UP;
1768 			bcopy(ifa->ifa_addr, ifa->ifa_dstaddr,
1769 			    sizeof(struct sockaddr));
1770 			error = carp_set_addr(sc, satosin(&ifra->ifra_addr));
1771 			break;
1772 #endif /* INET */
1773 #ifdef INET6
1774 		case AF_INET6:
1775 			SC2IFP(sc)->if_flags |= IFF_UP;
1776 			error = carp_set_addr6(sc, satosin6(&ifra->ifra_addr));
1777 			break;
1778 #endif /* INET6 */
1779 		default:
1780 			error = EAFNOSUPPORT;
1781 			break;
1782 		}
1783 		break;
1784 
1785 	case SIOCDIFADDR:
1786 		switch (ifa->ifa_addr->sa_family) {
1787 #ifdef INET
1788 		case AF_INET:
1789 			error = carp_del_addr(sc, satosin(&ifra->ifra_addr));
1790 			break;
1791 #endif /* INET */
1792 #ifdef INET6
1793 		case AF_INET6:
1794 			error = carp_del_addr6(sc, satosin6(&ifra->ifra_addr));
1795 			break;
1796 #endif /* INET6 */
1797 		default:
1798 			error = EAFNOSUPPORT;
1799 			break;
1800 		}
1801 		break;
1802 
1803 	case SIOCSIFFLAGS:
1804 		if (sc->sc_carpdev) {
1805 			locked = 1;
1806 			CARP_SCLOCK(sc);
1807 		}
1808 		if (sc->sc_state != INIT && !(ifr->ifr_flags & IFF_UP)) {
1809  			callout_stop(&sc->sc_ad_tmo);
1810  			callout_stop(&sc->sc_md_tmo);
1811  			callout_stop(&sc->sc_md6_tmo);
1812 			if (sc->sc_state == MASTER)
1813 				carp_send_ad_locked(sc);
1814 			carp_set_state(sc, INIT);
1815 			carp_setrun(sc, 0);
1816 		} else if (sc->sc_state == INIT && (ifr->ifr_flags & IFF_UP)) {
1817 			SC2IFP(sc)->if_flags |= IFF_UP;
1818 			carp_setrun(sc, 0);
1819 		}
1820 		break;
1821 
1822 	case SIOCSVH:
1823 		if ((error = suser(curthread)) != 0)
1824 			break;
1825 		if ((error = copyin(ifr->ifr_data, &carpr, sizeof carpr)))
1826 			break;
1827 		error = 1;
1828 		if (sc->sc_carpdev) {
1829 			locked = 1;
1830 			CARP_SCLOCK(sc);
1831 		}
1832 		if (sc->sc_state != INIT && carpr.carpr_state != sc->sc_state) {
1833 			switch (carpr.carpr_state) {
1834 			case BACKUP:
1835 				callout_stop(&sc->sc_ad_tmo);
1836 				carp_set_state(sc, BACKUP);
1837 				carp_setrun(sc, 0);
1838 				carp_setroute(sc, RTM_DELETE);
1839 				break;
1840 			case MASTER:
1841 				carp_master_down_locked(sc);
1842 				break;
1843 			default:
1844 				break;
1845 			}
1846 		}
1847 		if (carpr.carpr_vhid > 0) {
1848 			if (carpr.carpr_vhid > 255) {
1849 				error = EINVAL;
1850 				break;
1851 			}
1852 			if (sc->sc_carpdev) {
1853 				struct carp_if *cif;
1854 				cif = (struct carp_if *)sc->sc_carpdev->if_carp;
1855 				TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list)
1856 					if (vr != sc &&
1857 					    vr->sc_vhid == carpr.carpr_vhid)
1858 						return EEXIST;
1859 			}
1860 			sc->sc_vhid = carpr.carpr_vhid;
1861 			IFP2ENADDR(sc->sc_ifp)[0] = 0;
1862 			IFP2ENADDR(sc->sc_ifp)[1] = 0;
1863 			IFP2ENADDR(sc->sc_ifp)[2] = 0x5e;
1864 			IFP2ENADDR(sc->sc_ifp)[3] = 0;
1865 			IFP2ENADDR(sc->sc_ifp)[4] = 1;
1866 			IFP2ENADDR(sc->sc_ifp)[5] = sc->sc_vhid;
1867 			error--;
1868 		}
1869 		if (carpr.carpr_advbase > 0 || carpr.carpr_advskew > 0) {
1870 			if (carpr.carpr_advskew >= 255) {
1871 				error = EINVAL;
1872 				break;
1873 			}
1874 			if (carpr.carpr_advbase > 255) {
1875 				error = EINVAL;
1876 				break;
1877 			}
1878 			sc->sc_advbase = carpr.carpr_advbase;
1879 			sc->sc_advskew = carpr.carpr_advskew;
1880 			error--;
1881 		}
1882 		bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1883 		if (error > 0)
1884 			error = EINVAL;
1885 		else {
1886 			error = 0;
1887 			carp_setrun(sc, 0);
1888 		}
1889 		break;
1890 
1891 	case SIOCGVH:
1892 		/* XXX: lockless read */
1893 		bzero(&carpr, sizeof(carpr));
1894 		carpr.carpr_state = sc->sc_state;
1895 		carpr.carpr_vhid = sc->sc_vhid;
1896 		carpr.carpr_advbase = sc->sc_advbase;
1897 		carpr.carpr_advskew = sc->sc_advskew;
1898 		if (suser(curthread) == 0)
1899 			bcopy(sc->sc_key, carpr.carpr_key,
1900 			    sizeof(carpr.carpr_key));
1901 		error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
1902 		break;
1903 
1904 	default:
1905 		error = EINVAL;
1906 	}
1907 
1908 	if (locked)
1909 		CARP_SCUNLOCK(sc);
1910 
1911 	carp_hmac_prepare(sc);
1912 
1913 	return (error);
1914 }
1915 
1916 /*
1917  * XXX: this is looutput. We should eventually use it from there.
1918  */
1919 static int
1920 carp_looutput(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst,
1921     struct rtentry *rt)
1922 {
1923 	M_ASSERTPKTHDR(m); /* check if we have the packet header */
1924 
1925 	if (rt && rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
1926 		m_freem(m);
1927 		return (rt->rt_flags & RTF_BLACKHOLE ? 0 :
1928 			rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1929 	}
1930 
1931 	ifp->if_opackets++;
1932 	ifp->if_obytes += m->m_pkthdr.len;
1933 #if 1	/* XXX */
1934 	switch (dst->sa_family) {
1935 	case AF_INET:
1936 	case AF_INET6:
1937 	case AF_IPX:
1938 	case AF_APPLETALK:
1939 		break;
1940 	default:
1941 		printf("carp_looutput: af=%d unexpected\n", dst->sa_family);
1942 		m_freem(m);
1943 		return (EAFNOSUPPORT);
1944 	}
1945 #endif
1946 	return(if_simloop(ifp, m, dst->sa_family, 0));
1947 }
1948 
1949 /*
1950  * Start output on carp interface. This function should never be called.
1951  */
1952 static void
1953 carp_start(struct ifnet *ifp)
1954 {
1955 #ifdef DEBUG
1956 	printf("%s: start called\n", ifp->if_xname);
1957 #endif
1958 }
1959 
1960 int
1961 carp_output(struct ifnet *ifp, struct mbuf *m, struct sockaddr *sa,
1962     struct rtentry *rt)
1963 {
1964 	struct m_tag *mtag;
1965 	struct carp_softc *sc;
1966 	struct ifnet *carp_ifp;
1967 
1968 	if (!sa)
1969 		return (0);
1970 
1971 	switch (sa->sa_family) {
1972 #ifdef INET
1973 	case AF_INET:
1974 		break;
1975 #endif /* INET */
1976 #ifdef INET6
1977 	case AF_INET6:
1978 		break;
1979 #endif /* INET6 */
1980 	default:
1981 		return (0);
1982 	}
1983 
1984 	mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
1985 	if (mtag == NULL)
1986 		return (0);
1987 
1988 	bcopy(mtag + 1, &carp_ifp, sizeof(struct ifnet *));
1989 	sc = carp_ifp->if_softc;
1990 
1991 	/* Set the source MAC address to Virtual Router MAC Address */
1992 	switch (ifp->if_type) {
1993 	case IFT_ETHER:
1994 	case IFT_L2VLAN: {
1995 			struct ether_header *eh;
1996 
1997 			eh = mtod(m, struct ether_header *);
1998 			eh->ether_shost[0] = 0;
1999 			eh->ether_shost[1] = 0;
2000 			eh->ether_shost[2] = 0x5e;
2001 			eh->ether_shost[3] = 0;
2002 			eh->ether_shost[4] = 1;
2003 			eh->ether_shost[5] = sc->sc_vhid;
2004 		}
2005 		break;
2006 	case IFT_FDDI: {
2007 			struct fddi_header *fh;
2008 
2009 			fh = mtod(m, struct fddi_header *);
2010 			fh->fddi_shost[0] = 0;
2011 			fh->fddi_shost[1] = 0;
2012 			fh->fddi_shost[2] = 0x5e;
2013 			fh->fddi_shost[3] = 0;
2014 			fh->fddi_shost[4] = 1;
2015 			fh->fddi_shost[5] = sc->sc_vhid;
2016 		}
2017 		break;
2018 	case IFT_ISO88025: {
2019  			struct iso88025_header *th;
2020  			th = mtod(m, struct iso88025_header *);
2021 			th->iso88025_shost[0] = 3;
2022 			th->iso88025_shost[1] = 0;
2023 			th->iso88025_shost[2] = 0x40 >> (sc->sc_vhid - 1);
2024 			th->iso88025_shost[3] = 0x40000 >> (sc->sc_vhid - 1);
2025 			th->iso88025_shost[4] = 0;
2026 			th->iso88025_shost[5] = 0;
2027 		}
2028 		break;
2029 	default:
2030 		printf("%s: carp is not supported for this interface type\n",
2031 		    ifp->if_xname);
2032 		return (EOPNOTSUPP);
2033 	}
2034 
2035 	return (0);
2036 }
2037 
2038 static void
2039 carp_set_state(struct carp_softc *sc, int state)
2040 {
2041 
2042 	if (sc->sc_carpdev)
2043 		CARP_SCLOCK_ASSERT(sc);
2044 
2045 	if (sc->sc_state == state)
2046 		return;
2047 
2048 	sc->sc_state = state;
2049 	switch (state) {
2050 	case BACKUP:
2051 		SC2IFP(sc)->if_link_state = LINK_STATE_DOWN;
2052 		break;
2053 	case MASTER:
2054 		SC2IFP(sc)->if_link_state = LINK_STATE_UP;
2055 		break;
2056 	default:
2057 		SC2IFP(sc)->if_link_state = LINK_STATE_UNKNOWN;
2058 		break;
2059 	}
2060 	rt_ifmsg(SC2IFP(sc));
2061 }
2062 
2063 void
2064 carp_carpdev_state(void *v)
2065 {
2066 	struct carp_if *cif = v;
2067 
2068 	CARP_LOCK(cif);
2069 	carp_carpdev_state_locked(cif);
2070 	CARP_UNLOCK(cif);
2071 }
2072 
2073 static void
2074 carp_carpdev_state_locked(struct carp_if *cif)
2075 {
2076 	struct carp_softc *sc;
2077 
2078 	TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list)
2079 		carp_sc_state_locked(sc);
2080 }
2081 
2082 static void
2083 carp_sc_state_locked(struct carp_softc *sc)
2084 {
2085 	CARP_SCLOCK_ASSERT(sc);
2086 
2087 	if (sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
2088 	    !(sc->sc_carpdev->if_flags & IFF_UP)) {
2089 		sc->sc_flags_backup = SC2IFP(sc)->if_flags;
2090 		SC2IFP(sc)->if_flags &= ~(IFF_UP|IFF_RUNNING);
2091 		callout_stop(&sc->sc_ad_tmo);
2092 		callout_stop(&sc->sc_md_tmo);
2093 		callout_stop(&sc->sc_md6_tmo);
2094 		carp_set_state(sc, INIT);
2095 		carp_setrun(sc, 0);
2096 		if (!sc->sc_suppress) {
2097 			carp_suppress_preempt++;
2098 			if (carp_suppress_preempt == 1) {
2099 				CARP_SCUNLOCK(sc);
2100 				carp_send_ad_all();
2101 				CARP_SCLOCK(sc);
2102 			}
2103 		}
2104 		sc->sc_suppress = 1;
2105 	} else {
2106 		SC2IFP(sc)->if_flags |= sc->sc_flags_backup;
2107 		carp_set_state(sc, INIT);
2108 		carp_setrun(sc, 0);
2109 		if (sc->sc_suppress)
2110 			carp_suppress_preempt--;
2111 		sc->sc_suppress = 0;
2112 	}
2113 
2114 	return;
2115 }
2116 
2117 static int
2118 carp_modevent(module_t mod, int type, void *data)
2119 {
2120 	int error = 0;
2121 
2122 	switch (type) {
2123 	case MOD_LOAD:
2124 		mtx_init(&carp_mtx, "carp_mtx", NULL, MTX_DEF);
2125 		LIST_INIT(&carpif_list);
2126 		if_clone_attach(&carp_cloner);
2127 		break;
2128 
2129 	case MOD_UNLOAD:
2130 		if_clone_detach(&carp_cloner);
2131 		while (!LIST_EMPTY(&carpif_list))
2132 			carp_clone_destroy(SC2IFP(LIST_FIRST(&carpif_list)));
2133 		mtx_destroy(&carp_mtx);
2134 		break;
2135 
2136 	default:
2137 		error = EINVAL;
2138 		break;
2139 	}
2140 
2141 	return error;
2142 }
2143 
2144 static moduledata_t carp_mod = {
2145 	"carp",
2146 	carp_modevent,
2147 	0
2148 };
2149 
2150 DECLARE_MODULE(carp, carp_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
2151