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