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