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