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