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