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