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