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