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