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