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