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