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