carp: Lockless MPSAFE step 1 of many
[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  */
29
30 #include "opt_carp.h"
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/in_cksum.h>
38 #include <sys/limits.h>
39 #include <sys/malloc.h>
40 #include <sys/mbuf.h>
41 #include <sys/msgport2.h>
42 #include <sys/time.h>
43 #include <sys/proc.h>
44 #include <sys/priv.h>
45 #include <sys/sockio.h>
46 #include <sys/socket.h>
47 #include <sys/sysctl.h>
48 #include <sys/syslog.h>
49 #include <sys/thread.h>
50
51 #include <machine/stdarg.h>
52 #include <crypto/sha1.h>
53
54 #include <net/bpf.h>
55 #include <net/ethernet.h>
56 #include <net/if.h>
57 #include <net/if_dl.h>
58 #include <net/if_types.h>
59 #include <net/route.h>
60 #include <net/if_clone.h>
61 #include <net/if_var.h>
62 #include <net/ifq_var.h>
63 #include <net/netmsg2.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 <netinet/ip_carp.h>
83
84 #define CARP_IFNAME             "carp"
85 #define CARP_IS_RUNNING(ifp)    \
86         (((ifp)->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
87
88 struct carp_vhaddr {
89         uint32_t                vha_flags;      /* CARP_VHAF_ */
90         struct in_ifaddr        *vha_ia;        /* carp address */
91         struct in_ifaddr        *vha_iaback;    /* backing address */
92         TAILQ_ENTRY(carp_vhaddr) vha_link;
93 };
94 TAILQ_HEAD(carp_vhaddr_list, carp_vhaddr);
95
96 struct carp_softc {
97         struct arpcom            arpcom;
98         struct ifnet            *sc_carpdev;    /* parent interface */
99         struct carp_vhaddr_list  sc_vha_list;   /* virtual addr list */
100
101         const struct in_ifaddr  *sc_ia;         /* primary iface address v4 */
102         struct ip_moptions       sc_imo;
103
104 #ifdef INET6
105         struct in6_ifaddr       *sc_ia6;        /* primary iface address v6 */
106         struct ip6_moptions      sc_im6o;
107 #endif /* INET6 */
108         TAILQ_ENTRY(carp_softc)  sc_list;
109
110         enum { INIT = 0, BACKUP, MASTER }
111                                  sc_state;
112         int                      sc_dead;
113
114         int                      sc_suppress;
115
116         int                      sc_sendad_errors;
117 #define CARP_SENDAD_MAX_ERRORS  3
118         int                      sc_sendad_success;
119 #define CARP_SENDAD_MIN_SUCCESS 3
120
121         int                      sc_vhid;
122         int                      sc_advskew;
123         int                      sc_naddrs;     /* actually used IPv4 vha */
124         int                      sc_naddrs6;
125         int                      sc_advbase;    /* seconds */
126         int                      sc_init_counter;
127         uint64_t                 sc_counter;
128
129         /* authentication */
130 #define CARP_HMAC_PAD   64
131         unsigned char            sc_key[CARP_KEY_LEN];
132         unsigned char            sc_pad[CARP_HMAC_PAD];
133         SHA1_CTX                 sc_sha1;
134
135         struct callout           sc_ad_tmo;     /* advertisement timeout */
136         struct callout           sc_md_tmo;     /* master down timeout */
137         struct callout           sc_md6_tmo;    /* master down timeout */
138
139         LIST_ENTRY(carp_softc)   sc_next;       /* Interface clue */
140 };
141
142 #define sc_if   arpcom.ac_if
143
144 struct carp_if {
145         TAILQ_HEAD(, carp_softc) vhif_vrs;
146 };
147
148 struct netmsg_carp {
149         struct netmsg_base      base;
150         struct ifnet            *nc_carpdev;
151 };
152
153 SYSCTL_DECL(_net_inet_carp);
154
155 static int carp_opts[CARPCTL_MAXID] = { 0, 1, 0, 1, 0, 0 }; /* XXX for now */
156 SYSCTL_INT(_net_inet_carp, CARPCTL_ALLOW, allow, CTLFLAG_RW,
157     &carp_opts[CARPCTL_ALLOW], 0, "Accept incoming CARP packets");
158 SYSCTL_INT(_net_inet_carp, CARPCTL_PREEMPT, preempt, CTLFLAG_RW,
159     &carp_opts[CARPCTL_PREEMPT], 0, "high-priority backup preemption mode");
160 SYSCTL_INT(_net_inet_carp, CARPCTL_LOG, log, CTLFLAG_RW,
161     &carp_opts[CARPCTL_LOG], 0, "log bad carp packets");
162 SYSCTL_INT(_net_inet_carp, CARPCTL_ARPBALANCE, arpbalance, CTLFLAG_RW,
163     &carp_opts[CARPCTL_ARPBALANCE], 0, "balance arp responses");
164
165 static int carp_suppress_preempt = 0;
166 SYSCTL_INT(_net_inet_carp, OID_AUTO, suppress_preempt, CTLFLAG_RD,
167     &carp_suppress_preempt, 0, "Preemption is suppressed");
168
169 static struct carpstats carpstats;
170 SYSCTL_STRUCT(_net_inet_carp, CARPCTL_STATS, stats, CTLFLAG_RW,
171     &carpstats, carpstats,
172     "CARP statistics (struct carpstats, netinet/ip_carp.h)");
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 struct lwkt_token carp_tok = LWKT_TOKEN_INITIALIZER(carp_token);
185
186 static void     carp_hmac_prepare(struct carp_softc *);
187 static void     carp_hmac_generate(struct carp_softc *, uint32_t *,
188                     unsigned char *);
189 static int      carp_hmac_verify(struct carp_softc *, uint32_t *,
190                     unsigned char *);
191 static void     carp_setroute(struct carp_softc *, int);
192 static void     carp_proto_input_c(struct carp_softc *, struct mbuf *,
193                     struct carp_header *, sa_family_t);
194 static int      carp_clone_create(struct if_clone *, int, caddr_t);
195 static int      carp_clone_destroy(struct ifnet *);
196 static void     carp_detach(struct carp_softc *, int, boolean_t);
197 static void     carp_prepare_ad(struct carp_softc *, struct carp_header *);
198 static void     carp_send_ad_all(void);
199 static void     carp_send_ad_timeout(void *);
200 static void     carp_send_ad(struct carp_softc *);
201 static void     carp_send_arp(struct carp_softc *);
202 static void     carp_master_down_timeout(void *);
203 static void     carp_master_down(struct carp_softc *);
204 static void     carp_setrun(struct carp_softc *, sa_family_t);
205 static void     carp_set_state(struct carp_softc *, int);
206 static struct ifnet *carp_forus(struct carp_if *, const uint8_t *);
207
208 static void     carp_init(void *);
209 static int      carp_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
210 static int      carp_output(struct ifnet *, struct mbuf *, struct sockaddr *,
211                     struct rtentry *);
212 static void     carp_start(struct ifnet *);
213 static void     carp_serialize(struct ifnet *, enum ifnet_serialize);
214 static void     carp_deserialize(struct ifnet *, enum ifnet_serialize);
215 static int      carp_tryserialize(struct ifnet *, enum ifnet_serialize);
216 #ifdef INVARIANTS
217 static void     carp_serialize_assert(struct ifnet *, enum ifnet_serialize,
218                     boolean_t);
219 #endif
220
221 static void     carp_multicast_cleanup(struct carp_softc *);
222 static void     carp_add_addr(struct carp_softc *, struct ifaddr *);
223 static void     carp_del_addr(struct carp_softc *, struct ifaddr *);
224 static void     carp_config_addr(struct carp_softc *, struct ifaddr *);
225 static void     carp_link_addrs(struct carp_softc *, struct ifnet *,
226                     struct ifaddr *);
227 static void     carp_unlink_addrs(struct carp_softc *, struct ifnet *,
228                     struct ifaddr *);
229 static void     carp_update_addrs(struct carp_softc *, struct ifaddr *);
230
231 static int      carp_get_vhaddr(struct carp_softc *, struct ifdrv *);
232 static int      carp_config_vhaddr(struct carp_softc *, struct carp_vhaddr *,
233                     struct in_ifaddr *);
234 static int      carp_activate_vhaddr(struct carp_softc *, struct carp_vhaddr *,
235                     struct ifnet *, struct in_ifaddr *, int);
236 static void     carp_deactivate_vhaddr(struct carp_softc *,
237                     struct carp_vhaddr *, boolean_t);
238 static int      carp_addroute_vhaddr(struct carp_softc *, struct carp_vhaddr *);
239 static void     carp_delroute_vhaddr(struct carp_softc *, struct carp_vhaddr *,
240                     boolean_t);
241
242 static void     carp_sc_state(struct carp_softc *);
243 #ifdef INET6
244 static void     carp_send_na(struct carp_softc *);
245 #ifdef notyet
246 static int      carp_set_addr6(struct carp_softc *, struct sockaddr_in6 *);
247 static int      carp_del_addr6(struct carp_softc *, struct sockaddr_in6 *);
248 #endif
249 static void     carp_multicast6_cleanup(struct carp_softc *);
250 #endif
251 static void     carp_stop(struct carp_softc *, int);
252 static void     carp_suspend(struct carp_softc *, int);
253
254 static void     carp_ifaddr(void *, struct ifnet *, enum ifaddr_event,
255                             struct ifaddr *);
256 static void     carp_ifdetach(void *, struct ifnet *);
257
258 static void     carp_ifdetach_dispatch(netmsg_t);
259
260 static MALLOC_DEFINE(M_CARP, "CARP", "CARP interfaces");
261
262 static LIST_HEAD(, carp_softc) carpif_list;
263
264 static struct if_clone carp_cloner =
265 IF_CLONE_INITIALIZER(CARP_IFNAME, carp_clone_create, carp_clone_destroy,
266                      0, IF_MAXUNIT);
267
268 static uint8_t  carp_etheraddr[ETHER_ADDR_LEN] = { 0, 0, 0x5e, 0, 1, 0 };
269
270 static eventhandler_tag carp_ifdetach_event;
271 static eventhandler_tag carp_ifaddr_event;
272
273 static __inline void
274 carp_insert_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha_new)
275 {
276         struct carp_vhaddr *vha;
277         u_long new_addr, addr;
278
279         KKASSERT((vha_new->vha_flags & CARP_VHAF_ONLIST) == 0);
280
281         /*
282          * Virtual address list is sorted; smaller one first
283          */
284         new_addr = ntohl(vha_new->vha_ia->ia_addr.sin_addr.s_addr);
285
286         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
287                 addr = ntohl(vha->vha_ia->ia_addr.sin_addr.s_addr);
288
289                 if (addr > new_addr)
290                         break;
291         }
292         if (vha == NULL)
293                 TAILQ_INSERT_TAIL(&sc->sc_vha_list, vha_new, vha_link);
294         else
295                 TAILQ_INSERT_BEFORE(vha, vha_new, vha_link);
296         vha_new->vha_flags |= CARP_VHAF_ONLIST;
297 }
298
299 static __inline void
300 carp_remove_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha)
301 {
302         KKASSERT(vha->vha_flags & CARP_VHAF_ONLIST);
303         vha->vha_flags &= ~CARP_VHAF_ONLIST;
304         TAILQ_REMOVE(&sc->sc_vha_list, vha, vha_link);
305 }
306
307 static void
308 carp_hmac_prepare(struct carp_softc *sc)
309 {
310         uint8_t version = CARP_VERSION, type = CARP_ADVERTISEMENT;
311         uint8_t vhid = sc->sc_vhid & 0xff;
312         int i;
313 #ifdef INET6
314         struct ifaddr_container *ifac;
315         struct in6_addr in6;
316 #endif
317 #ifdef INET
318         struct carp_vhaddr *vha;
319 #endif
320
321         /* XXX: possible race here */
322
323         /* compute ipad from key */
324         bzero(sc->sc_pad, sizeof(sc->sc_pad));
325         bcopy(sc->sc_key, sc->sc_pad, sizeof(sc->sc_key));
326         for (i = 0; i < sizeof(sc->sc_pad); i++)
327                 sc->sc_pad[i] ^= 0x36;
328
329         /* precompute first part of inner hash */
330         SHA1Init(&sc->sc_sha1);
331         SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad));
332         SHA1Update(&sc->sc_sha1, (void *)&version, sizeof(version));
333         SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type));
334         SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid));
335 #ifdef INET
336         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
337                 SHA1Update(&sc->sc_sha1,
338                     (const uint8_t *)&vha->vha_ia->ia_addr.sin_addr,
339                     sizeof(struct in_addr));
340         }
341 #endif /* INET */
342 #ifdef INET6
343         TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) {
344                 struct ifaddr *ifa = ifac->ifa;
345
346                 if (ifa->ifa_addr->sa_family == AF_INET6) {
347                         in6 = ifatoia6(ifa)->ia_addr.sin6_addr;
348                         in6_clearscope(&in6);
349                         SHA1Update(&sc->sc_sha1, (void *)&in6, sizeof(in6));
350                 }
351         }
352 #endif /* INET6 */
353
354         /* convert ipad to opad */
355         for (i = 0; i < sizeof(sc->sc_pad); i++)
356                 sc->sc_pad[i] ^= 0x36 ^ 0x5c;
357 }
358
359 static void
360 carp_hmac_generate(struct carp_softc *sc, uint32_t counter[2],
361     unsigned char md[20])
362 {
363         SHA1_CTX sha1ctx;
364
365         /* fetch first half of inner hash */
366         bcopy(&sc->sc_sha1, &sha1ctx, sizeof(sha1ctx));
367
368         SHA1Update(&sha1ctx, (void *)counter, sizeof(sc->sc_counter));
369         SHA1Final(md, &sha1ctx);
370
371         /* outer hash */
372         SHA1Init(&sha1ctx);
373         SHA1Update(&sha1ctx, sc->sc_pad, sizeof(sc->sc_pad));
374         SHA1Update(&sha1ctx, md, 20);
375         SHA1Final(md, &sha1ctx);
376 }
377
378 static int
379 carp_hmac_verify(struct carp_softc *sc, uint32_t counter[2],
380     unsigned char md[20])
381 {
382         unsigned char md2[20];
383
384         carp_hmac_generate(sc, counter, md2);
385         return (bcmp(md, md2, sizeof(md2)));
386 }
387
388 static void
389 carp_setroute(struct carp_softc *sc, int cmd)
390 {
391 #ifdef INET6
392         struct ifaddr_container *ifac;
393 #endif
394         struct carp_vhaddr *vha;
395
396         KKASSERT(cmd == RTM_DELETE || cmd == RTM_ADD);
397
398         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
399                 if (vha->vha_iaback == NULL)
400                         continue;
401                 if (cmd == RTM_DELETE)
402                         carp_delroute_vhaddr(sc, vha, FALSE);
403                 else
404                         carp_addroute_vhaddr(sc, vha);
405         }
406
407 #ifdef INET6
408         TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) {
409                 struct ifaddr *ifa = ifac->ifa;
410
411                 if (ifa->ifa_addr->sa_family == AF_INET6) {
412                         if (cmd == RTM_ADD)
413                                 in6_ifaddloop(ifa);
414                         else
415                                 in6_ifremloop(ifa);
416                 }
417         }
418 #endif /* INET6 */
419 }
420
421 static int
422 carp_clone_create(struct if_clone *ifc, int unit, caddr_t param __unused)
423 {
424         struct carp_softc *sc;
425         struct ifnet *ifp;
426
427         sc = kmalloc(sizeof(*sc), M_CARP, M_WAITOK | M_ZERO);
428         ifp = &sc->sc_if;
429
430         sc->sc_suppress = 0;
431         sc->sc_advbase = CARP_DFLTINTV;
432         sc->sc_vhid = -1;       /* required setting */
433         sc->sc_advskew = 0;
434         sc->sc_init_counter = 1;
435         sc->sc_naddrs = 0;
436         sc->sc_naddrs6 = 0;
437
438         TAILQ_INIT(&sc->sc_vha_list);
439
440 #ifdef INET6
441         sc->sc_im6o.im6o_multicast_hlim = CARP_DFLTTL;
442 #endif
443
444         callout_init_mp(&sc->sc_ad_tmo);
445         callout_init_mp(&sc->sc_md_tmo);
446         callout_init_mp(&sc->sc_md6_tmo);
447
448         if_initname(ifp, CARP_IFNAME, unit);
449         ifp->if_softc = sc;
450         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
451         ifp->if_init = carp_init;
452         ifp->if_ioctl = carp_ioctl;
453         ifp->if_start = carp_start;
454         ifp->if_serialize = carp_serialize;
455         ifp->if_deserialize = carp_deserialize;
456         ifp->if_tryserialize = carp_tryserialize;
457 #ifdef INVARIANTS
458         ifp->if_serialize_assert = carp_serialize_assert;
459 #endif
460         ifq_set_maxlen(&ifp->if_snd, ifqmaxlen);
461         ifq_set_ready(&ifp->if_snd);
462
463         ether_ifattach(ifp, carp_etheraddr, NULL);
464
465         ifp->if_type = IFT_CARP;
466         ifp->if_output = carp_output;
467
468         carp_gettok();
469         LIST_INSERT_HEAD(&carpif_list, sc, sc_next);
470         carp_reltok();
471
472         return (0);
473 }
474
475 static int
476 carp_clone_destroy(struct ifnet *ifp)
477 {
478         struct carp_softc *sc = ifp->if_softc;
479
480         carp_gettok();
481
482         sc->sc_dead = 1;
483         carp_detach(sc, 1, FALSE);
484         LIST_REMOVE(sc, sc_next);
485
486         carp_reltok();
487
488         bpfdetach(ifp);
489         if_detach(ifp);
490
491         KASSERT(sc->sc_naddrs == 0, ("certain inet address is still active\n"));
492         kfree(sc, M_CARP);
493
494         return 0;
495 }
496
497 static void
498 carp_detach(struct carp_softc *sc, int detach, boolean_t del_iaback)
499 {
500         struct carp_if *cif;
501
502         carp_suspend(sc, detach);
503
504         carp_multicast_cleanup(sc);
505 #ifdef INET6
506         carp_multicast6_cleanup(sc);
507 #endif
508
509         if (!sc->sc_dead && detach) {
510                 struct carp_vhaddr *vha;
511
512                 TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link)
513                         carp_deactivate_vhaddr(sc, vha, del_iaback);
514                 KKASSERT(sc->sc_naddrs == 0);
515         }
516
517         if (sc->sc_carpdev != NULL) {
518                 cif = sc->sc_carpdev->if_carp;
519                 TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list);
520                 if (TAILQ_EMPTY(&cif->vhif_vrs)) {
521                         ifpromisc(sc->sc_carpdev, 0);
522                         sc->sc_carpdev->if_carp = NULL;
523                         kfree(cif, M_CARP);
524                 }
525                 sc->sc_carpdev = NULL;
526                 sc->sc_ia = NULL;
527         }
528 }
529
530 static void
531 carp_ifdetach_dispatch(netmsg_t msg)
532 {
533         struct netmsg_carp *cmsg = (struct netmsg_carp *)msg;
534         struct ifnet *ifp = cmsg->nc_carpdev;
535         struct carp_if *cif = ifp->if_carp;
536         struct carp_softc *sc;
537
538         carp_gettok();
539
540         while (ifp->if_carp &&
541                (sc = TAILQ_FIRST(&cif->vhif_vrs)) != NULL)
542                 carp_detach(sc, 1, TRUE);
543
544         carp_reltok();
545
546         lwkt_replymsg(&cmsg->base.lmsg, 0);
547 }
548
549 /* Detach an interface from the carp. */
550 static void
551 carp_ifdetach(void *arg __unused, struct ifnet *ifp)
552 {
553         struct netmsg_carp cmsg;
554
555         ASSERT_IFNET_NOT_SERIALIZED_ALL(ifp);
556
557         bzero(&cmsg, sizeof(cmsg));
558         netmsg_init(&cmsg.base, NULL, &curthread->td_msgport, 0,
559             carp_ifdetach_dispatch);
560         cmsg.nc_carpdev = ifp;
561
562         lwkt_domsg(cpu_portfn(0), &cmsg.base.lmsg, 0);
563 }
564
565 /*
566  * process input packet.
567  * we have rearranged checks order compared to the rfc,
568  * but it seems more efficient this way or not possible otherwise.
569  */
570 int
571 carp_proto_input(struct mbuf **mp, int *offp, int proto)
572 {
573         struct mbuf *m = *mp;
574         struct ip *ip = mtod(m, struct ip *);
575         struct ifnet *ifp = m->m_pkthdr.rcvif;
576         struct carp_header *ch;
577         struct carp_softc *sc;
578         int len, iphlen;
579
580         carp_gettok();
581
582         iphlen = *offp;
583         *mp = NULL;
584
585         carpstats.carps_ipackets++;
586
587         if (!carp_opts[CARPCTL_ALLOW]) {
588                 m_freem(m);
589                 goto back;
590         }
591
592         /* Check if received on a valid carp interface */
593         if (ifp->if_type != IFT_CARP) {
594                 carpstats.carps_badif++;
595                 CARP_LOG("carp_proto_input: packet received on non-carp "
596                     "interface: %s\n", ifp->if_xname);
597                 m_freem(m);
598                 goto back;
599         }
600
601         if (!CARP_IS_RUNNING(ifp)) {
602                 carpstats.carps_badif++;
603                 CARP_LOG("carp_proto_input: packet received on stopped carp "
604                     "interface: %s\n", ifp->if_xname);
605                 m_freem(m);
606                 goto back;
607         }
608
609         sc = ifp->if_softc;
610         if (sc->sc_carpdev == NULL) {
611                 carpstats.carps_badif++;
612                 CARP_LOG("carp_proto_input: packet received on defunc carp "
613                     "interface: %s\n", ifp->if_xname);
614                 m_freem(m);
615                 goto back;
616         }
617
618         if (!IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
619                 carpstats.carps_badif++;
620                 CARP_LOG("carp_proto_input: non-mcast packet on "
621                     "interface: %s\n", ifp->if_xname);
622                 m_freem(m);
623                 goto back;
624         }
625
626         /* Verify that the IP TTL is CARP_DFLTTL. */
627         if (ip->ip_ttl != CARP_DFLTTL) {
628                 carpstats.carps_badttl++;
629                 CARP_LOG("carp_proto_input: received ttl %d != %d on %s\n",
630                     ip->ip_ttl, CARP_DFLTTL, ifp->if_xname);
631                 m_freem(m);
632                 goto back;
633         }
634
635         /* Minimal CARP packet size */
636         len = iphlen + sizeof(*ch);
637
638         /*
639          * Verify that the received packet length is
640          * not less than the CARP header
641          */
642         if (m->m_pkthdr.len < len) {
643                 carpstats.carps_badlen++;
644                 CARP_LOG("packet too short %d on %s\n", m->m_pkthdr.len,
645                     ifp->if_xname);
646                 m_freem(m);
647                 goto back;
648         }
649
650         /* Make sure that CARP header is contiguous */
651         if (len > m->m_len) {
652                 m = m_pullup(m, len);
653                 if (m == NULL) {
654                         carpstats.carps_hdrops++;
655                         CARP_LOG("carp_proto_input: m_pullup failed\n");
656                         goto back;
657                 }
658                 ip = mtod(m, struct ip *);
659         }
660         ch = (struct carp_header *)((uint8_t *)ip + iphlen);
661
662         /* Verify the CARP checksum */
663         if (in_cksum_skip(m, len, iphlen)) {
664                 carpstats.carps_badsum++;
665                 CARP_LOG("carp_proto_input: checksum failed on %s\n",
666                     ifp->if_xname);
667                 m_freem(m);
668                 goto back;
669         }
670         carp_proto_input_c(sc, m, ch, AF_INET);
671 back:
672         carp_reltok();
673         return(IPPROTO_DONE);
674 }
675
676 #ifdef INET6
677 int
678 carp6_proto_input(struct mbuf **mp, int *offp, int proto)
679 {
680         struct mbuf *m = *mp;
681         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
682         struct ifnet *ifp = m->m_pkthdr.rcvif;
683         struct carp_header *ch;
684         struct carp_softc *sc;
685         u_int len;
686
687         carp_gettok();
688
689         carpstats.carps_ipackets6++;
690
691         if (!carp_opts[CARPCTL_ALLOW]) {
692                 m_freem(m);
693                 goto back;
694         }
695
696         /* check if received on a valid carp interface */
697         if (ifp->if_type != IFT_CARP) {
698                 carpstats.carps_badif++;
699                 CARP_LOG("carp6_proto_input: packet received on non-carp "
700                     "interface: %s\n", ifp->if_xname);
701                 m_freem(m);
702                 goto back;
703         }
704
705         if (!CARP_IS_RUNNING(ifp)) {
706                 carpstats.carps_badif++;
707                 CARP_LOG("carp_proto_input: packet received on stopped carp "
708                     "interface: %s\n", ifp->if_xname);
709                 m_freem(m);
710                 goto back;
711         }
712
713         sc = ifp->if_softc;
714         if (sc->sc_carpdev == NULL) {
715                 carpstats.carps_badif++;
716                 CARP_LOG("carp6_proto_input: packet received on defunc-carp "
717                     "interface: %s\n", ifp->if_xname);
718                 m_freem(m);
719                 goto back;
720         }
721
722         /* verify that the IP TTL is 255 */
723         if (ip6->ip6_hlim != CARP_DFLTTL) {
724                 carpstats.carps_badttl++;
725                 CARP_LOG("carp6_proto_input: received ttl %d != 255 on %s\n",
726                     ip6->ip6_hlim, ifp->if_xname);
727                 m_freem(m);
728                 goto back;
729         }
730
731         /* verify that we have a complete carp packet */
732         len = m->m_len;
733         IP6_EXTHDR_GET(ch, struct carp_header *, m, *offp, sizeof(*ch));
734         if (ch == NULL) {
735                 carpstats.carps_badlen++;
736                 CARP_LOG("carp6_proto_input: packet size %u too small\n", len);
737                 goto back;
738         }
739
740         /* verify the CARP checksum */
741         if (in_cksum_range(m, 0, *offp, sizeof(*ch))) {
742                 carpstats.carps_badsum++;
743                 CARP_LOG("carp6_proto_input: checksum failed, on %s\n",
744                     ifp->if_xname);
745                 m_freem(m);
746                 goto back;
747         }
748
749         carp_proto_input_c(sc, m, ch, AF_INET6);
750 back:
751         carp_reltok();
752         return (IPPROTO_DONE);
753 }
754 #endif /* INET6 */
755
756 static void
757 carp_proto_input_c(struct carp_softc *sc, struct mbuf *m,
758     struct carp_header *ch, sa_family_t af)
759 {
760         struct ifnet *cifp;
761         uint64_t tmp_counter;
762         struct timeval sc_tv, ch_tv;
763
764         if (sc->sc_vhid != ch->carp_vhid) {
765                 /*
766                  * CARP uses multicast, however, multicast packets
767                  * are tapped to all CARP interfaces on the physical
768                  * interface receiving the CARP packets, so we don't
769                  * update any stats here.
770                  */
771                 m_freem(m);
772                 return;
773         }
774         cifp = &sc->sc_if;
775
776         /* verify the CARP version. */
777         if (ch->carp_version != CARP_VERSION) {
778                 carpstats.carps_badver++;
779                 CARP_LOG("%s; invalid version %d\n", cifp->if_xname,
780                          ch->carp_version);
781                 m_freem(m);
782                 return;
783         }
784
785         /* verify the hash */
786         if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) {
787                 carpstats.carps_badauth++;
788                 CARP_LOG("%s: incorrect hash\n", cifp->if_xname);
789                 m_freem(m);
790                 return;
791         }
792
793         tmp_counter = ntohl(ch->carp_counter[0]);
794         tmp_counter = tmp_counter<<32;
795         tmp_counter += ntohl(ch->carp_counter[1]);
796
797         /* XXX Replay protection goes here */
798
799         sc->sc_init_counter = 0;
800         sc->sc_counter = tmp_counter;
801
802         sc_tv.tv_sec = sc->sc_advbase;
803         if (carp_suppress_preempt && sc->sc_advskew <  240)
804                 sc_tv.tv_usec = 240 * 1000000 / 256;
805         else
806                 sc_tv.tv_usec = sc->sc_advskew * 1000000 / 256;
807         ch_tv.tv_sec = ch->carp_advbase;
808         ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256;
809
810         switch (sc->sc_state) {
811         case INIT:
812                 break;
813
814         case MASTER:
815                 /*
816                  * If we receive an advertisement from a master who's going to
817                  * be more frequent than us, go into BACKUP state.
818                  */
819                 if (timevalcmp(&sc_tv, &ch_tv, >) ||
820                     timevalcmp(&sc_tv, &ch_tv, ==)) {
821                         callout_stop(&sc->sc_ad_tmo);
822                         CARP_DEBUG("%s: MASTER -> BACKUP "
823                            "(more frequent advertisement received)\n",
824                            cifp->if_xname);
825                         carp_set_state(sc, BACKUP);
826                         carp_setrun(sc, 0);
827                         carp_setroute(sc, RTM_DELETE);
828                 }
829                 break;
830
831         case BACKUP:
832                 /*
833                  * If we're pre-empting masters who advertise slower than us,
834                  * and this one claims to be slower, treat him as down.
835                  */
836                 if (carp_opts[CARPCTL_PREEMPT] &&
837                     timevalcmp(&sc_tv, &ch_tv, <)) {
838                         CARP_DEBUG("%s: BACKUP -> MASTER "
839                             "(preempting a slower master)\n", cifp->if_xname);
840                         carp_master_down(sc);
841                         break;
842                 }
843
844                 /*
845                  *  If the master is going to advertise at such a low frequency
846                  *  that he's guaranteed to time out, we'd might as well just
847                  *  treat him as timed out now.
848                  */
849                 sc_tv.tv_sec = sc->sc_advbase * 3;
850                 if (timevalcmp(&sc_tv, &ch_tv, <)) {
851                         CARP_DEBUG("%s: BACKUP -> MASTER (master timed out)\n",
852                                    cifp->if_xname);
853                         carp_master_down(sc);
854                         break;
855                 }
856
857                 /*
858                  * Otherwise, we reset the counter and wait for the next
859                  * advertisement.
860                  */
861                 carp_setrun(sc, af);
862                 break;
863         }
864         m_freem(m);
865 }
866
867 struct mbuf *
868 carp_input(void *v, struct mbuf *m)
869 {
870         struct carp_if *cif = v;
871         struct ether_header *eh;
872         struct carp_softc *sc;
873         struct ifnet *ifp;
874
875         ASSERT_LWKT_TOKEN_HELD(&carp_tok);
876
877         eh = mtod(m, struct ether_header *);
878
879         ifp = carp_forus(cif, eh->ether_dhost);
880         if (ifp != NULL) {
881                 ether_reinput_oncpu(ifp, m, REINPUT_RUNBPF);
882                 return NULL;
883         }
884
885         if ((m->m_flags & (M_BCAST | M_MCAST)) == 0)
886                 return m;
887
888         /*
889          * XXX Should really check the list of multicast addresses
890          * for each CARP interface _before_ copying.
891          */
892         TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) {
893                 struct mbuf *m0;
894
895                 if ((sc->sc_if.if_flags & IFF_UP) == 0)
896                         continue;
897
898                 m0 = m_dup(m, MB_DONTWAIT);
899                 if (m0 == NULL)
900                         continue;
901
902                 ether_reinput_oncpu(&sc->sc_if, m0, REINPUT_RUNBPF);
903         }
904         return m;
905 }
906
907 static void
908 carp_prepare_ad(struct carp_softc *sc, struct carp_header *ch)
909 {
910         if (sc->sc_init_counter) {
911                 /* this could also be seconds since unix epoch */
912                 sc->sc_counter = karc4random();
913                 sc->sc_counter = sc->sc_counter << 32;
914                 sc->sc_counter += karc4random();
915         } else {
916                 sc->sc_counter++;
917         }
918
919         ch->carp_counter[0] = htonl((sc->sc_counter >> 32) & 0xffffffff);
920         ch->carp_counter[1] = htonl(sc->sc_counter & 0xffffffff);
921
922         carp_hmac_generate(sc, ch->carp_counter, ch->carp_md);
923 }
924
925 static void
926 carp_send_ad_all(void)
927 {
928         struct carp_softc *sc;
929
930         LIST_FOREACH(sc, &carpif_list, sc_next) {
931                 if (sc->sc_carpdev == NULL)
932                         continue;
933
934                 if (CARP_IS_RUNNING(&sc->sc_if) && sc->sc_state == MASTER)
935                         carp_send_ad(sc);
936         }
937 }
938
939 static void
940 carp_send_ad_timeout(void *xsc)
941 {
942         carp_gettok();
943         carp_send_ad(xsc);
944         carp_reltok();
945 }
946
947 static void
948 carp_send_ad(struct carp_softc *sc)
949 {
950         struct ifnet *cifp = &sc->sc_if;
951         struct carp_header ch;
952         struct timeval tv;
953         struct carp_header *ch_ptr;
954         struct mbuf *m;
955         int len, advbase, advskew;
956
957         if (!CARP_IS_RUNNING(cifp)) {
958                 /* Bow out */
959                 advbase = 255;
960                 advskew = 255;
961         } else {
962                 advbase = sc->sc_advbase;
963                 if (!carp_suppress_preempt || sc->sc_advskew > 240)
964                         advskew = sc->sc_advskew;
965                 else
966                         advskew = 240;
967                 tv.tv_sec = advbase;
968                 tv.tv_usec = advskew * 1000000 / 256;
969         }
970
971         ch.carp_version = CARP_VERSION;
972         ch.carp_type = CARP_ADVERTISEMENT;
973         ch.carp_vhid = sc->sc_vhid;
974         ch.carp_advbase = advbase;
975         ch.carp_advskew = advskew;
976         ch.carp_authlen = 7;    /* XXX DEFINE */
977         ch.carp_pad1 = 0;       /* must be zero */
978         ch.carp_cksum = 0;
979
980 #ifdef INET
981         if (sc->sc_ia != NULL) {
982                 struct ip *ip;
983
984                 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
985                 if (m == NULL) {
986                         cifp->if_oerrors++;
987                         carpstats.carps_onomem++;
988                         /* XXX maybe less ? */
989                         if (advbase != 255 || advskew != 255)
990                                 callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv),
991                                     carp_send_ad_timeout, sc);
992                         return;
993                 }
994                 len = sizeof(*ip) + sizeof(ch);
995                 m->m_pkthdr.len = len;
996                 m->m_pkthdr.rcvif = NULL;
997                 m->m_len = len;
998                 MH_ALIGN(m, m->m_len);
999                 m->m_flags |= M_MCAST;
1000                 ip = mtod(m, struct ip *);
1001                 ip->ip_v = IPVERSION;
1002                 ip->ip_hl = sizeof(*ip) >> 2;
1003                 ip->ip_tos = IPTOS_LOWDELAY;
1004                 ip->ip_len = len;
1005                 ip->ip_id = ip_newid();
1006                 ip->ip_off = IP_DF;
1007                 ip->ip_ttl = CARP_DFLTTL;
1008                 ip->ip_p = IPPROTO_CARP;
1009                 ip->ip_sum = 0;
1010                 ip->ip_src = sc->sc_ia->ia_addr.sin_addr;
1011                 ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP);
1012
1013                 ch_ptr = (struct carp_header *)(&ip[1]);
1014                 bcopy(&ch, ch_ptr, sizeof(ch));
1015                 carp_prepare_ad(sc, ch_ptr);
1016                 ch_ptr->carp_cksum = in_cksum_skip(m, len, sizeof(*ip));
1017
1018                 getmicrotime(&cifp->if_lastchange);
1019                 cifp->if_opackets++;
1020                 cifp->if_obytes += len;
1021                 carpstats.carps_opackets++;
1022
1023                 if (ip_output(m, NULL, NULL, IP_RAWOUTPUT, &sc->sc_imo, NULL)) {
1024                         cifp->if_oerrors++;
1025                         if (sc->sc_sendad_errors < INT_MAX)
1026                                 sc->sc_sendad_errors++;
1027                         if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
1028                                 carp_suppress_preempt++;
1029                                 if (carp_suppress_preempt == 1) {
1030                                         carp_send_ad_all();
1031                                 }
1032                         }
1033                         sc->sc_sendad_success = 0;
1034                 } else {
1035                         if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
1036                                 if (++sc->sc_sendad_success >=
1037                                     CARP_SENDAD_MIN_SUCCESS) {
1038                                         carp_suppress_preempt--;
1039                                         sc->sc_sendad_errors = 0;
1040                                 }
1041                         } else {
1042                                 sc->sc_sendad_errors = 0;
1043                         }
1044                 }
1045         }
1046 #endif /* INET */
1047 #ifdef INET6
1048         if (sc->sc_ia6) {
1049                 struct ip6_hdr *ip6;
1050
1051                 MGETHDR(m, MB_DONTWAIT, MT_HEADER);
1052                 if (m == NULL) {
1053                         cifp->if_oerrors++;
1054                         carpstats.carps_onomem++;
1055                         /* XXX maybe less ? */
1056                         if (advbase != 255 || advskew != 255)
1057                                 callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv),
1058                                     carp_send_ad_timeout, sc);
1059                         return;
1060                 }
1061                 len = sizeof(*ip6) + sizeof(ch);
1062                 m->m_pkthdr.len = len;
1063                 m->m_pkthdr.rcvif = NULL;
1064                 m->m_len = len;
1065                 MH_ALIGN(m, m->m_len);
1066                 m->m_flags |= M_MCAST;
1067                 ip6 = mtod(m, struct ip6_hdr *);
1068                 bzero(ip6, sizeof(*ip6));
1069                 ip6->ip6_vfc |= IPV6_VERSION;
1070                 ip6->ip6_hlim = CARP_DFLTTL;
1071                 ip6->ip6_nxt = IPPROTO_CARP;
1072                 bcopy(&sc->sc_ia6->ia_addr.sin6_addr, &ip6->ip6_src,
1073                     sizeof(struct in6_addr));
1074                 /* set the multicast destination */
1075
1076                 ip6->ip6_dst.s6_addr16[0] = htons(0xff02);
1077                 ip6->ip6_dst.s6_addr8[15] = 0x12;
1078                 if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) {
1079                         cifp->if_oerrors++;
1080                         m_freem(m);
1081                         CARP_LOG("%s: in6_setscope failed\n", __func__);
1082                         return;
1083                 }
1084
1085                 ch_ptr = (struct carp_header *)(&ip6[1]);
1086                 bcopy(&ch, ch_ptr, sizeof(ch));
1087                 carp_prepare_ad(sc, ch_ptr);
1088                 ch_ptr->carp_cksum = in_cksum_skip(m, len, sizeof(*ip6));
1089
1090                 getmicrotime(&cifp->if_lastchange);
1091                 cifp->if_opackets++;
1092                 cifp->if_obytes += len;
1093                 carpstats.carps_opackets6++;
1094
1095                 if (ip6_output(m, NULL, NULL, 0, &sc->sc_im6o, NULL, NULL)) {
1096                         cifp->if_oerrors++;
1097                         if (sc->sc_sendad_errors < INT_MAX)
1098                                 sc->sc_sendad_errors++;
1099                         if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
1100                                 carp_suppress_preempt++;
1101                                 if (carp_suppress_preempt == 1) {
1102                                         carp_send_ad_all();
1103                                 }
1104                         }
1105                         sc->sc_sendad_success = 0;
1106                 } else {
1107                         if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS) {
1108                                 if (++sc->sc_sendad_success >=
1109                                     CARP_SENDAD_MIN_SUCCESS) {
1110                                         carp_suppress_preempt--;
1111                                         sc->sc_sendad_errors = 0;
1112                                 }
1113                         } else {
1114                                 sc->sc_sendad_errors = 0;
1115                         }
1116                 }
1117         }
1118 #endif /* INET6 */
1119
1120         if (advbase != 255 || advskew != 255)
1121                 callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv),
1122                     carp_send_ad_timeout, sc);
1123 }
1124
1125 /*
1126  * Broadcast a gratuitous ARP request containing
1127  * the virtual router MAC address for each IP address
1128  * associated with the virtual router.
1129  */
1130 static void
1131 carp_send_arp(struct carp_softc *sc)
1132 {
1133         const struct carp_vhaddr *vha;
1134
1135         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1136                 if (vha->vha_iaback == NULL)
1137                         continue;
1138                 arp_gratuitous(&sc->sc_if, &vha->vha_ia->ia_ifa);
1139         }
1140 }
1141
1142 #ifdef INET6
1143 static void
1144 carp_send_na(struct carp_softc *sc)
1145 {
1146         struct ifaddr_container *ifac;
1147         struct in6_addr *in6;
1148         static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1149
1150         TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid], ifa_link) {
1151                 struct ifaddr *ifa = ifac->ifa;
1152
1153                 if (ifa->ifa_addr->sa_family != AF_INET6)
1154                         continue;
1155
1156                 in6 = &ifatoia6(ifa)->ia_addr.sin6_addr;
1157                 nd6_na_output(sc->sc_carpdev, &mcast, in6,
1158                     ND_NA_FLAG_OVERRIDE, 1, NULL);
1159                 DELAY(1000);    /* XXX */
1160         }
1161 }
1162 #endif /* INET6 */
1163
1164 static __inline const struct carp_vhaddr *
1165 carp_find_addr(const struct carp_softc *sc, const struct in_addr *addr)
1166 {
1167         struct carp_vhaddr *vha;
1168
1169         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1170                 if (vha->vha_iaback == NULL)
1171                         continue;
1172
1173                 if (vha->vha_ia->ia_addr.sin_addr.s_addr == addr->s_addr)
1174                         return vha;
1175         }
1176         return NULL;
1177 }
1178
1179 #ifdef notyet
1180 static int
1181 carp_iamatch_balance(const struct carp_if *cif, const struct in_addr *itaddr,
1182                      const struct in_addr *isaddr, uint8_t **enaddr)
1183 {
1184         const struct carp_softc *vh;
1185         int index, count = 0;
1186
1187         /*
1188          * XXX proof of concept implementation.
1189          * We use the source ip to decide which virtual host should
1190          * handle the request. If we're master of that virtual host,
1191          * then we respond, otherwise, just drop the arp packet on
1192          * the floor.
1193          */
1194
1195         TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1196                 if (!CARP_IS_RUNNING(&vh->sc_if))
1197                         continue;
1198
1199                 if (carp_find_addr(vh, itaddr) != NULL)
1200                         count++;
1201         }
1202         if (count == 0)
1203                 return 0;
1204
1205         /* this should be a hash, like pf_hash() */
1206         index = ntohl(isaddr->s_addr) % count;
1207         count = 0;
1208
1209         TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1210                 if (!CARP_IS_RUNNING(&vh->sc_if))
1211                         continue;
1212
1213                 if (carp_find_addr(vh, itaddr) == NULL)
1214                         continue;
1215
1216                 if (count == index) {
1217                         if (vh->sc_state == MASTER) {
1218                                 *enaddr = IF_LLADDR(&vh->sc_if);
1219                                 return 1;
1220                         } else {
1221                                 return 0;
1222                         }
1223                 }
1224                 count++;
1225         }
1226         return 0;
1227 }
1228 #endif
1229
1230 int
1231 carp_iamatch(const struct in_ifaddr *ia)
1232 {
1233         const struct carp_softc *sc = ia->ia_ifp->if_softc;
1234
1235         ASSERT_LWKT_TOKEN_HELD(&carp_tok);
1236
1237 #ifdef notyet
1238         if (carp_opts[CARPCTL_ARPBALANCE])
1239                 return carp_iamatch_balance(cif, itaddr, isaddr, enaddr);
1240 #endif
1241
1242         if (!CARP_IS_RUNNING(&sc->sc_if) || sc->sc_state != MASTER)
1243                 return 0;
1244
1245         return 1;
1246 }
1247
1248 #ifdef INET6
1249 struct ifaddr *
1250 carp_iamatch6(void *v, struct in6_addr *taddr)
1251 {
1252         struct carp_if *cif = v;
1253         struct carp_softc *vh;
1254
1255         ASSERT_LWKT_TOKEN_HELD(&carp_tok);
1256
1257         TAILQ_FOREACH(vh, &cif->vhif_vrs, sc_list) {
1258                 struct ifaddr_container *ifac;
1259
1260                 TAILQ_FOREACH(ifac, &vh->sc_if.if_addrheads[mycpuid],
1261                               ifa_link) {
1262                         struct ifaddr *ifa = ifac->ifa;
1263
1264                         if (IN6_ARE_ADDR_EQUAL(taddr,
1265                             &ifatoia6(ifa)->ia_addr.sin6_addr) &&
1266                             CARP_IS_RUNNING(&vh->sc_if) &&
1267                             vh->sc_state == MASTER) {
1268                                 return (ifa);
1269                         }
1270                 }
1271         }
1272         return (NULL);
1273 }
1274
1275 void *
1276 carp_macmatch6(void *v, struct mbuf *m, const struct in6_addr *taddr)
1277 {
1278         struct m_tag *mtag;
1279         struct carp_if *cif = v;
1280         struct carp_softc *sc;
1281
1282         ASSERT_LWKT_TOKEN_HELD(&carp_tok);
1283
1284         TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) {
1285                 struct ifaddr_container *ifac;
1286
1287                 TAILQ_FOREACH(ifac, &sc->sc_if.if_addrheads[mycpuid],
1288                               ifa_link) {
1289                         struct ifaddr *ifa = ifac->ifa;
1290
1291                         if (IN6_ARE_ADDR_EQUAL(taddr,
1292                             &ifatoia6(ifa)->ia_addr.sin6_addr) &&
1293                             CARP_IS_RUNNING(&sc->sc_if)) {
1294                                 struct ifnet *ifp = &sc->sc_if;
1295
1296                                 mtag = m_tag_get(PACKET_TAG_CARP,
1297                                     sizeof(struct ifnet *), MB_DONTWAIT);
1298                                 if (mtag == NULL) {
1299                                         /* better a bit than nothing */
1300                                         return (IF_LLADDR(ifp));
1301                                 }
1302                                 bcopy(&ifp, (caddr_t)(mtag + 1),
1303                                     sizeof(struct ifnet *));
1304                                 m_tag_prepend(m, mtag);
1305
1306                                 return (IF_LLADDR(ifp));
1307                         }
1308                 }
1309         }
1310         return (NULL);
1311 }
1312 #endif
1313
1314 static struct ifnet *
1315 carp_forus(struct carp_if *cif, const uint8_t *dhost)
1316 {
1317         struct carp_softc *sc;
1318
1319         ASSERT_LWKT_TOKEN_HELD(&carp_tok);
1320
1321         if (memcmp(dhost, carp_etheraddr, ETHER_ADDR_LEN - 1) != 0)
1322                 return NULL;
1323
1324         TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list) {
1325                 struct ifnet *ifp = &sc->sc_if;
1326
1327                 if (CARP_IS_RUNNING(ifp) && sc->sc_state == MASTER &&
1328                     !bcmp(dhost, IF_LLADDR(ifp), ETHER_ADDR_LEN))
1329                         return ifp;
1330         }
1331         return NULL;
1332 }
1333
1334 static void
1335 carp_master_down_timeout(void *xsc)
1336 {
1337         struct carp_softc *sc = xsc;
1338
1339         CARP_DEBUG("%s: BACKUP -> MASTER (master timed out)\n",
1340                    sc->sc_if.if_xname);
1341         carp_gettok();
1342         carp_master_down(sc);
1343         carp_reltok();
1344 }
1345
1346 static void
1347 carp_master_down(struct carp_softc *sc)
1348 {
1349         switch (sc->sc_state) {
1350         case INIT:
1351                 kprintf("%s: master_down event in INIT state\n",
1352                         sc->sc_if.if_xname);
1353                 break;
1354
1355         case MASTER:
1356                 break;
1357
1358         case BACKUP:
1359                 carp_set_state(sc, MASTER);
1360                 carp_send_ad(sc);
1361                 carp_send_arp(sc);
1362 #ifdef INET6
1363                 carp_send_na(sc);
1364 #endif /* INET6 */
1365                 carp_setrun(sc, 0);
1366                 carp_setroute(sc, RTM_ADD);
1367                 break;
1368         }
1369 }
1370
1371 /*
1372  * When in backup state, af indicates whether to reset the master down timer
1373  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1374  */
1375 static void
1376 carp_setrun(struct carp_softc *sc, sa_family_t af)
1377 {
1378         struct ifnet *cifp = &sc->sc_if;
1379         struct timeval tv;
1380
1381         if (sc->sc_carpdev == NULL) {
1382                 carp_set_state(sc, INIT);
1383                 return;
1384         }
1385
1386         if ((cifp->if_flags & IFF_RUNNING) && sc->sc_vhid > 0 &&
1387             (sc->sc_naddrs || sc->sc_naddrs6)) {
1388                 /* Nothing */
1389         } else {
1390                 carp_setroute(sc, RTM_DELETE);
1391                 return;
1392         }
1393
1394         switch (sc->sc_state) {
1395         case INIT:
1396                 if (carp_opts[CARPCTL_PREEMPT] && !carp_suppress_preempt) {
1397                         carp_send_ad(sc);
1398                         carp_send_arp(sc);
1399 #ifdef INET6
1400                         carp_send_na(sc);
1401 #endif /* INET6 */
1402                         CARP_DEBUG("%s: INIT -> MASTER (preempting)\n",
1403                                    cifp->if_xname);
1404                         carp_set_state(sc, MASTER);
1405                         carp_setroute(sc, RTM_ADD);
1406                 } else {
1407                         CARP_DEBUG("%s: INIT -> BACKUP\n", cifp->if_xname);
1408                         carp_set_state(sc, BACKUP);
1409                         carp_setroute(sc, RTM_DELETE);
1410                         carp_setrun(sc, 0);
1411                 }
1412                 break;
1413
1414         case BACKUP:
1415                 callout_stop(&sc->sc_ad_tmo);
1416                 tv.tv_sec = 3 * sc->sc_advbase;
1417                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1418                 switch (af) {
1419 #ifdef INET
1420                 case AF_INET:
1421                         callout_reset(&sc->sc_md_tmo, tvtohz_high(&tv),
1422                             carp_master_down_timeout, sc);
1423                         break;
1424 #endif /* INET */
1425 #ifdef INET6
1426                 case AF_INET6:
1427                         callout_reset(&sc->sc_md6_tmo, tvtohz_high(&tv),
1428                             carp_master_down_timeout, sc);
1429                         break;
1430 #endif /* INET6 */
1431                 default:
1432                         if (sc->sc_naddrs)
1433                                 callout_reset(&sc->sc_md_tmo, tvtohz_high(&tv),
1434                                     carp_master_down_timeout, sc);
1435                         if (sc->sc_naddrs6)
1436                                 callout_reset(&sc->sc_md6_tmo, tvtohz_high(&tv),
1437                                     carp_master_down_timeout, sc);
1438                         break;
1439                 }
1440                 break;
1441
1442         case MASTER:
1443                 tv.tv_sec = sc->sc_advbase;
1444                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1445                 callout_reset(&sc->sc_ad_tmo, tvtohz_high(&tv),
1446                     carp_send_ad_timeout, sc);
1447                 break;
1448         }
1449 }
1450
1451 static void
1452 carp_multicast_cleanup(struct carp_softc *sc)
1453 {
1454         struct ip_moptions *imo = &sc->sc_imo;
1455
1456         if (imo->imo_num_memberships == 0)
1457                 return;
1458         KKASSERT(imo->imo_num_memberships == 1);
1459
1460         in_delmulti(imo->imo_membership[0]);
1461         imo->imo_membership[0] = NULL;
1462         imo->imo_num_memberships = 0;
1463         imo->imo_multicast_ifp = NULL;
1464 }
1465
1466 #ifdef INET6
1467 static void
1468 carp_multicast6_cleanup(struct carp_softc *sc)
1469 {
1470         struct ip6_moptions *im6o = &sc->sc_im6o;
1471
1472         while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1473                 struct in6_multi_mship *imm =
1474                     LIST_FIRST(&im6o->im6o_memberships);
1475
1476                 LIST_REMOVE(imm, i6mm_chain);
1477                 in6_leavegroup(imm);
1478         }
1479         im6o->im6o_multicast_ifp = NULL;
1480 }
1481 #endif
1482
1483 static int
1484 carp_get_vhaddr(struct carp_softc *sc, struct ifdrv *ifd)
1485 {
1486         const struct carp_vhaddr *vha;
1487         struct ifcarpvhaddr *carpa, *carpa0;
1488         int count, len, error;
1489
1490         count = 0;
1491         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link)
1492                 ++count;
1493
1494         if (ifd->ifd_len == 0) {
1495                 ifd->ifd_len = count * sizeof(*carpa);
1496                 return 0;
1497         } else if (count == 0 || ifd->ifd_len < sizeof(*carpa)) {
1498                 ifd->ifd_len = 0;
1499                 return 0;
1500         }
1501         len = min(ifd->ifd_len, sizeof(*carpa) * count);
1502         KKASSERT(len >= sizeof(*carpa));
1503
1504         carpa0 = carpa = kmalloc(len, M_TEMP, M_WAITOK | M_NULLOK | M_ZERO);
1505         if (carpa == NULL)
1506                 return ENOMEM;
1507
1508         count = 0;
1509         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1510                 if (len < sizeof(*carpa))
1511                         break;
1512
1513                 carpa->carpa_flags = vha->vha_flags;
1514                 carpa->carpa_addr.sin_family = AF_INET;
1515                 carpa->carpa_addr.sin_addr = vha->vha_ia->ia_addr.sin_addr;
1516
1517                 carpa->carpa_baddr.sin_family = AF_INET;
1518                 if (vha->vha_iaback == NULL) {
1519                         carpa->carpa_baddr.sin_addr.s_addr = INADDR_ANY;
1520                 } else {
1521                         carpa->carpa_baddr.sin_addr =
1522                         vha->vha_iaback->ia_addr.sin_addr;
1523                 }
1524
1525                 ++carpa;
1526                 ++count;
1527                 len -= sizeof(*carpa);
1528         }
1529         ifd->ifd_len = sizeof(*carpa) * count;
1530         KKASSERT(ifd->ifd_len > 0);
1531
1532         error = copyout(carpa0, ifd->ifd_data, ifd->ifd_len);
1533         kfree(carpa0, M_TEMP);
1534         return error;
1535 }
1536
1537 static int
1538 carp_config_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha,
1539     struct in_ifaddr *ia_del)
1540 {
1541         struct ifnet *ifp;
1542         struct in_ifaddr *ia_if;
1543         struct in_ifaddr_container *iac;
1544         const struct sockaddr_in *sin;
1545         u_long iaddr;
1546         int own;
1547
1548         KKASSERT(vha->vha_ia != NULL);
1549
1550         sin = &vha->vha_ia->ia_addr;
1551         iaddr = ntohl(sin->sin_addr.s_addr);
1552
1553         ia_if = NULL;
1554         own = 0;
1555         TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
1556                 struct in_ifaddr *ia = iac->ia;
1557
1558                 if (ia == ia_del)
1559                         continue;
1560
1561                 if (ia->ia_ifp->if_type == IFT_CARP)
1562                         continue;
1563
1564                 if ((ia->ia_ifp->if_flags & IFF_UP) == 0)
1565                         continue;
1566
1567                 /* and, yeah, we need a multicast-capable iface too */
1568                 if ((ia->ia_ifp->if_flags & IFF_MULTICAST) == 0)
1569                         continue;
1570
1571                 if ((iaddr & ia->ia_subnetmask) == ia->ia_subnet) {
1572                         if (sin->sin_addr.s_addr ==
1573                             ia->ia_addr.sin_addr.s_addr)
1574                                 own = 1;
1575                         if (ia_if == NULL)
1576                                 ia_if = ia;
1577                         else if (sc->sc_carpdev != NULL &&
1578                                  sc->sc_carpdev == ia->ia_ifp)
1579                                 ia_if = ia;
1580                 }
1581         }
1582
1583         carp_deactivate_vhaddr(sc, vha, FALSE);
1584         if (!ia_if)
1585                 return ENOENT;
1586
1587         ifp = ia_if->ia_ifp;
1588
1589         /* XXX Don't allow parent iface to be changed */
1590         if (sc->sc_carpdev != NULL && sc->sc_carpdev != ifp)
1591                 return EEXIST;
1592
1593         return carp_activate_vhaddr(sc, vha, ifp, ia_if, own);
1594 }
1595
1596 static void
1597 carp_add_addr(struct carp_softc *sc, struct ifaddr *carp_ifa)
1598 {
1599         struct carp_vhaddr *vha_new;
1600         struct in_ifaddr *carp_ia;
1601 #ifdef INVARIANTS
1602         struct carp_vhaddr *vha;
1603 #endif
1604
1605         KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET);
1606         carp_ia = ifatoia(carp_ifa);
1607
1608 #ifdef INVARIANTS
1609         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link)
1610                 KKASSERT(vha->vha_ia != NULL && vha->vha_ia != carp_ia);
1611 #endif
1612
1613         vha_new = kmalloc(sizeof(*vha_new), M_CARP, M_WAITOK | M_ZERO);
1614         vha_new->vha_ia = carp_ia;
1615         carp_insert_vhaddr(sc, vha_new);
1616
1617         if (carp_config_vhaddr(sc, vha_new, NULL) != 0) {
1618                 /*
1619                  * If the above configuration fails, it may only mean
1620                  * that the new address is problematic.  However, the
1621                  * carp(4) interface may already have several working
1622                  * addresses.  Since the expected behaviour of
1623                  * SIOC[AS]IFADDR is to put the NIC into working state,
1624                  * we try starting the state machine manually here with
1625                  * the hope that the carp(4)'s previously working
1626                  * addresses still could be brought up.
1627                  */
1628                 carp_hmac_prepare(sc);
1629                 carp_set_state(sc, INIT);
1630                 carp_setrun(sc, 0);
1631         }
1632 }
1633
1634 static void
1635 carp_del_addr(struct carp_softc *sc, struct ifaddr *carp_ifa)
1636 {
1637         struct carp_vhaddr *vha;
1638         struct in_ifaddr *carp_ia;
1639
1640         KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET);
1641         carp_ia = ifatoia(carp_ifa);
1642
1643         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1644                 KKASSERT(vha->vha_ia != NULL);
1645                 if (vha->vha_ia == carp_ia)
1646                         break;
1647         }
1648         KASSERT(vha != NULL, ("no corresponding vhaddr %p\n", carp_ifa));
1649
1650         /*
1651          * Remove the vhaddr from the list before deactivating
1652          * the vhaddr, so that the HMAC could be correctly
1653          * updated in carp_deactivate_vhaddr()
1654          */
1655         carp_remove_vhaddr(sc, vha);
1656
1657         carp_deactivate_vhaddr(sc, vha, FALSE);
1658         kfree(vha, M_CARP);
1659 }
1660
1661 static void
1662 carp_config_addr(struct carp_softc *sc, struct ifaddr *carp_ifa)
1663 {
1664         struct carp_vhaddr *vha;
1665         struct in_ifaddr *carp_ia;
1666
1667         KKASSERT(carp_ifa->ifa_addr->sa_family == AF_INET);
1668         carp_ia = ifatoia(carp_ifa);
1669
1670         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
1671                 KKASSERT(vha->vha_ia != NULL);
1672                 if (vha->vha_ia == carp_ia)
1673                         break;
1674         }
1675         KASSERT(vha != NULL, ("no corresponding vhaddr %p\n", carp_ifa));
1676
1677         /* Remove then reinsert, to keep the vhaddr list sorted */
1678         carp_remove_vhaddr(sc, vha);
1679         carp_insert_vhaddr(sc, vha);
1680
1681         if (carp_config_vhaddr(sc, vha, NULL) != 0) {
1682                 /* See the comment in carp_add_addr() */
1683                 carp_hmac_prepare(sc);
1684                 carp_set_state(sc, INIT);
1685                 carp_setrun(sc, 0);
1686         }
1687 }
1688
1689 #ifdef notyet
1690
1691 #ifdef INET6
1692 static int
1693 carp_set_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6)
1694 {
1695         struct ifnet *ifp;
1696         struct carp_if *cif;
1697         struct in6_ifaddr *ia, *ia_if;
1698         struct ip6_moptions *im6o = &sc->sc_im6o;
1699         struct in6_multi_mship *imm;
1700         struct in6_addr in6;
1701         int own, error;
1702
1703         if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1704                 carp_setrun(sc, 0);
1705                 return (0);
1706         }
1707
1708         /* we have to do it by hands to check we won't match on us */
1709         ia_if = NULL; own = 0;
1710         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1711                 int i;
1712
1713                 for (i = 0; i < 4; i++) {
1714                         if ((sin6->sin6_addr.s6_addr32[i] &
1715                             ia->ia_prefixmask.sin6_addr.s6_addr32[i]) !=
1716                             (ia->ia_addr.sin6_addr.s6_addr32[i] &
1717                             ia->ia_prefixmask.sin6_addr.s6_addr32[i]))
1718                                 break;
1719                 }
1720                 /* and, yeah, we need a multicast-capable iface too */
1721                 if (ia->ia_ifp != &sc->sc_if &&
1722                     (ia->ia_ifp->if_flags & IFF_MULTICAST) &&
1723                     (i == 4)) {
1724                         if (!ia_if)
1725                                 ia_if = ia;
1726                         if (IN6_ARE_ADDR_EQUAL(&sin6->sin6_addr,
1727                             &ia->ia_addr.sin6_addr))
1728                                 own++;
1729                 }
1730         }
1731
1732         if (!ia_if)
1733                 return (EADDRNOTAVAIL);
1734         ia = ia_if;
1735         ifp = ia->ia_ifp;
1736
1737         if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0 ||
1738             (im6o->im6o_multicast_ifp && im6o->im6o_multicast_ifp != ifp))
1739                 return (EADDRNOTAVAIL);
1740
1741         if (!sc->sc_naddrs6) {
1742                 im6o->im6o_multicast_ifp = ifp;
1743
1744                 /* join CARP multicast address */
1745                 bzero(&in6, sizeof(in6));
1746                 in6.s6_addr16[0] = htons(0xff02);
1747                 in6.s6_addr8[15] = 0x12;
1748                 if (in6_setscope(&in6, ifp, NULL) != 0)
1749                         goto cleanup;
1750                 if ((imm = in6_joingroup(ifp, &in6, &error)) == NULL)
1751                         goto cleanup;
1752                 LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
1753
1754                 /* join solicited multicast address */
1755                 bzero(&in6, sizeof(in6));
1756                 in6.s6_addr16[0] = htons(0xff02);
1757                 in6.s6_addr32[1] = 0;
1758                 in6.s6_addr32[2] = htonl(1);
1759                 in6.s6_addr32[3] = sin6->sin6_addr.s6_addr32[3];
1760                 in6.s6_addr8[12] = 0xff;
1761                 if (in6_setscope(&in6, ifp, NULL) != 0)
1762                         goto cleanup;
1763                 if ((imm = in6_joingroup(ifp, &in6, &error)) == NULL)
1764                         goto cleanup;
1765                 LIST_INSERT_HEAD(&im6o->im6o_memberships, imm, i6mm_chain);
1766         }
1767
1768         if (!ifp->if_carp) {
1769                 cif = kmalloc(sizeof(*cif), M_CARP, M_WAITOK | M_ZERO);
1770
1771                 if ((error = ifpromisc(ifp, 1))) {
1772                         kfree(cif, M_CARP);
1773                         goto cleanup;
1774                 }
1775
1776                 TAILQ_INIT(&cif->vhif_vrs);
1777                 ifp->if_carp = cif;
1778         } else {
1779                 struct carp_softc *vr;
1780
1781                 cif = ifp->if_carp;
1782                 TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1783                         if (vr != sc && vr->sc_vhid == sc->sc_vhid) {
1784                                 error = EINVAL;
1785                                 goto cleanup;
1786                         }
1787                 }
1788         }
1789         sc->sc_ia6 = ia;
1790         sc->sc_carpdev = ifp;
1791
1792         { /* XXX prevent endless loop if already in queue */
1793         struct carp_softc *vr, *after = NULL;
1794         int myself = 0;
1795         cif = ifp->if_carp;
1796
1797         TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1798                 if (vr == sc)
1799                         myself = 1;
1800                 if (vr->sc_vhid < sc->sc_vhid)
1801                         after = vr;
1802         }
1803
1804         if (!myself) {
1805                 /* We're trying to keep things in order */
1806                 if (after == NULL)
1807                         TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list);
1808                 else
1809                         TAILQ_INSERT_AFTER(&cif->vhif_vrs, after, sc, sc_list);
1810         }
1811         }
1812
1813         sc->sc_naddrs6++;
1814         if (own)
1815                 sc->sc_advskew = 0;
1816         carp_sc_state(sc);
1817         carp_setrun(sc, 0);
1818
1819         return (0);
1820
1821 cleanup:
1822         /* clean up multicast memberships */
1823         if (!sc->sc_naddrs6) {
1824                 while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1825                         imm = LIST_FIRST(&im6o->im6o_memberships);
1826                         LIST_REMOVE(imm, i6mm_chain);
1827                         in6_leavegroup(imm);
1828                 }
1829         }
1830         return (error);
1831 }
1832
1833 static int
1834 carp_del_addr6(struct carp_softc *sc, struct sockaddr_in6 *sin6)
1835 {
1836         int error = 0;
1837
1838         if (!--sc->sc_naddrs6) {
1839                 struct carp_if *cif = sc->sc_carpdev->if_carp;
1840                 struct ip6_moptions *im6o = &sc->sc_im6o;
1841
1842                 callout_stop(&sc->sc_ad_tmo);
1843                 sc->sc_vhid = -1;
1844                 while (!LIST_EMPTY(&im6o->im6o_memberships)) {
1845                         struct in6_multi_mship *imm =
1846                             LIST_FIRST(&im6o->im6o_memberships);
1847
1848                         LIST_REMOVE(imm, i6mm_chain);
1849                         in6_leavegroup(imm);
1850                 }
1851                 im6o->im6o_multicast_ifp = NULL;
1852                 TAILQ_REMOVE(&cif->vhif_vrs, sc, sc_list);
1853                 if (TAILQ_EMPTY(&cif->vhif_vrs)) {
1854                         sc->sc_carpdev->if_carp = NULL;
1855                         kfree(cif, M_IFADDR);
1856                 }
1857         }
1858         return (error);
1859 }
1860 #endif /* INET6 */
1861
1862 #endif
1863
1864 static int
1865 carp_ioctl(struct ifnet *ifp, u_long cmd, caddr_t addr, struct ucred *cr)
1866 {
1867         struct carp_softc *sc = ifp->if_softc, *vr;
1868         struct carpreq carpr;
1869         struct ifaddr *ifa;
1870         struct ifreq *ifr;
1871         struct ifaliasreq *ifra;
1872         struct ifdrv *ifd;
1873         char devname[IFNAMSIZ];
1874         int error = 0;
1875
1876         carp_gettok();
1877
1878         ifa = (struct ifaddr *)addr;
1879         ifra = (struct ifaliasreq *)addr;
1880         ifr = (struct ifreq *)addr;
1881         ifd = (struct ifdrv *)addr;
1882
1883         switch (cmd) {
1884         case SIOCSIFFLAGS:
1885                 if (ifp->if_flags & IFF_UP) {
1886                         if ((ifp->if_flags & IFF_RUNNING) == 0)
1887                                 carp_init(sc);
1888                 } else if (ifp->if_flags & IFF_RUNNING) {
1889                         carp_stop(sc, 0);
1890                 }
1891                 break;
1892
1893         case SIOCSVH:
1894                 error = priv_check_cred(cr, PRIV_ROOT, NULL_CRED_OKAY);
1895                 if (error)
1896                         break;
1897                 error = copyin(ifr->ifr_data, &carpr, sizeof(carpr));
1898                 if (error)
1899                         break;
1900
1901                 error = 1;
1902                 if ((ifp->if_flags & IFF_RUNNING) &&
1903                     sc->sc_state != INIT && carpr.carpr_state != sc->sc_state) {
1904                         switch (carpr.carpr_state) {
1905                         case BACKUP:
1906                                 callout_stop(&sc->sc_ad_tmo);
1907                                 carp_set_state(sc, BACKUP);
1908                                 carp_setrun(sc, 0);
1909                                 carp_setroute(sc, RTM_DELETE);
1910                                 break;
1911
1912                         case MASTER:
1913                                 carp_master_down(sc);
1914                                 break;
1915
1916                         default:
1917                                 break;
1918                         }
1919                 }
1920                 if (carpr.carpr_vhid > 0) {
1921                         if (carpr.carpr_vhid > 255) {
1922                                 error = EINVAL;
1923                                 break;
1924                         }
1925                         if (sc->sc_carpdev) {
1926                                 struct carp_if *cif = sc->sc_carpdev->if_carp;
1927
1928                                 TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
1929                                         if (vr != sc &&
1930                                             vr->sc_vhid == carpr.carpr_vhid) {
1931                                                 carp_reltok();
1932                                                 return EEXIST;
1933                                         }
1934                                 }
1935                         }
1936                         sc->sc_vhid = carpr.carpr_vhid;
1937
1938                         IF_LLADDR(ifp)[5] = sc->sc_vhid;
1939                         bcopy(IF_LLADDR(ifp), sc->arpcom.ac_enaddr,
1940                             ETHER_ADDR_LEN);
1941
1942                         error--;
1943                 }
1944                 if (carpr.carpr_advbase > 0 || carpr.carpr_advskew > 0) {
1945                         if (carpr.carpr_advskew >= 255) {
1946                                 error = EINVAL;
1947                                 break;
1948                         }
1949                         if (carpr.carpr_advbase > 255) {
1950                                 error = EINVAL;
1951                                 break;
1952                         }
1953                         sc->sc_advbase = carpr.carpr_advbase;
1954                         sc->sc_advskew = carpr.carpr_advskew;
1955                         error--;
1956                 }
1957                 bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1958                 if (error > 0) {
1959                         error = EINVAL;
1960                 } else {
1961                         error = 0;
1962                         carp_setrun(sc, 0);
1963                 }
1964                 break;
1965
1966         case SIOCGVH:
1967                 bzero(&carpr, sizeof(carpr));
1968                 carpr.carpr_state = sc->sc_state;
1969                 carpr.carpr_vhid = sc->sc_vhid;
1970                 carpr.carpr_advbase = sc->sc_advbase;
1971                 carpr.carpr_advskew = sc->sc_advskew;
1972                 error = priv_check_cred(cr, PRIV_ROOT, NULL_CRED_OKAY);
1973                 if (error == 0) {
1974                         bcopy(sc->sc_key, carpr.carpr_key,
1975                               sizeof(carpr.carpr_key));
1976                 }
1977
1978                 error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
1979                 break;
1980
1981         case SIOCGDRVSPEC:
1982                 switch (ifd->ifd_cmd) {
1983                 case CARPGDEVNAME:
1984                         if (ifd->ifd_len != sizeof(devname))
1985                                 error = EINVAL;
1986                         break;
1987
1988                 case CARPGVHADDR:
1989                         break;
1990
1991                 default:
1992                         error = EINVAL;
1993                         break;
1994                 }
1995                 if (error)
1996                         break;
1997
1998                 switch (ifd->ifd_cmd) {
1999                 case CARPGVHADDR:
2000                         error = carp_get_vhaddr(sc, ifd);
2001                         break;
2002
2003                 case CARPGDEVNAME:
2004                         bzero(devname, sizeof(devname));
2005                         if (sc->sc_carpdev != NULL) {
2006                                 strlcpy(devname, sc->sc_carpdev->if_xname,
2007                                         sizeof(devname));
2008                         }
2009                         error = copyout(devname, ifd->ifd_data,
2010                                         sizeof(devname));
2011                         break;
2012                 }
2013                 break;
2014
2015         default:
2016                 error = ether_ioctl(ifp, cmd, addr);
2017                 break;
2018         }
2019         carp_hmac_prepare(sc);
2020
2021         carp_reltok();
2022         return error;
2023 }
2024
2025 static void
2026 carp_init(void *xsc)
2027 {
2028         struct carp_softc *sc = xsc;
2029
2030         carp_gettok();
2031
2032         sc->sc_if.if_flags |= IFF_RUNNING;
2033         carp_set_state(sc, INIT);
2034         carp_setrun(sc, 0);
2035
2036         carp_reltok();
2037 }
2038
2039 static int
2040 carp_output(struct ifnet *ifp, struct mbuf *m, struct sockaddr *dst,
2041     struct rtentry *rt)
2042 {
2043         struct carp_softc *sc = ifp->if_softc;
2044         int error = 0;
2045
2046         carp_gettok();
2047         if (sc->sc_carpdev) {
2048                 /*
2049                  * NOTE:
2050                  * CARP's ifp is passed to backing device's
2051                  * if_output method.
2052                  */
2053                 sc->sc_carpdev->if_output(ifp, m, dst, rt);
2054         } else {
2055                 m_freem(m);
2056                 error = ENETUNREACH;
2057         }
2058         carp_reltok();
2059
2060         return error;
2061 }
2062
2063 /*
2064  * Start output on carp interface. This function should never be called.
2065  */
2066 static void
2067 carp_start(struct ifnet *ifp)
2068 {
2069         panic("%s: start called\n", ifp->if_xname);
2070 }
2071
2072 static void
2073 carp_serialize(struct ifnet *ifp __unused,
2074     enum ifnet_serialize slz __unused)
2075 {
2076 }
2077
2078 static void
2079 carp_deserialize(struct ifnet *ifp __unused,
2080     enum ifnet_serialize slz __unused)
2081 {
2082 }
2083
2084 static int
2085 carp_tryserialize(struct ifnet *ifp __unused,
2086     enum ifnet_serialize slz __unused)
2087 {
2088         return 1;
2089 }
2090
2091 #ifdef INVARIANTS
2092
2093 static void
2094 carp_serialize_assert(struct ifnet *ifp __unused,
2095     enum ifnet_serialize slz __unused, boolean_t serialized __unused)
2096 {
2097 }
2098
2099 #endif  /* INVARIANTS */
2100
2101 static void
2102 carp_set_state(struct carp_softc *sc, int state)
2103 {
2104         struct ifnet *cifp = &sc->sc_if;
2105
2106         if (sc->sc_state == state)
2107                 return;
2108         sc->sc_state = state;
2109
2110         switch (sc->sc_state) {
2111         case BACKUP:
2112                 cifp->if_link_state = LINK_STATE_DOWN;
2113                 break;
2114
2115         case MASTER:
2116                 cifp->if_link_state = LINK_STATE_UP;
2117                 break;
2118
2119         default:
2120                 cifp->if_link_state = LINK_STATE_UNKNOWN;
2121                 break;
2122         }
2123         rt_ifmsg(cifp);
2124 }
2125
2126 void
2127 carp_group_demote_adj(struct ifnet *ifp, int adj)
2128 {
2129         struct ifg_list *ifgl;
2130         int *dm;
2131
2132         carp_gettok();
2133
2134         TAILQ_FOREACH(ifgl, &ifp->if_groups, ifgl_next) {
2135                 if (!strcmp(ifgl->ifgl_group->ifg_group, IFG_ALL))
2136                         continue;
2137                 dm = &ifgl->ifgl_group->ifg_carp_demoted;
2138
2139                 if (*dm + adj >= 0)
2140                         *dm += adj;
2141                 else
2142                         *dm = 0;
2143
2144                 if (adj > 0 && *dm == 1)
2145                         carp_send_ad_all();
2146                 CARP_LOG("%s demoted group %s to %d", ifp->if_xname,
2147                     ifgl->ifgl_group->ifg_group, *dm);
2148         }
2149
2150         carp_reltok();
2151 }
2152
2153 void
2154 carp_carpdev_state(void *v)
2155 {
2156         struct carp_if *cif = v;
2157         struct carp_softc *sc;
2158
2159         carp_gettok();
2160
2161         TAILQ_FOREACH(sc, &cif->vhif_vrs, sc_list)
2162                 carp_sc_state(sc);
2163
2164         carp_reltok();
2165 }
2166
2167 static void
2168 carp_sc_state(struct carp_softc *sc)
2169 {
2170         if (!(sc->sc_carpdev->if_flags & IFF_UP)) {
2171                 callout_stop(&sc->sc_ad_tmo);
2172                 callout_stop(&sc->sc_md_tmo);
2173                 callout_stop(&sc->sc_md6_tmo);
2174                 carp_set_state(sc, INIT);
2175                 carp_setrun(sc, 0);
2176                 if (!sc->sc_suppress) {
2177                         carp_suppress_preempt++;
2178                         if (carp_suppress_preempt == 1)
2179                                 carp_send_ad_all();
2180                 }
2181                 sc->sc_suppress = 1;
2182         } else {
2183                 carp_set_state(sc, INIT);
2184                 carp_setrun(sc, 0);
2185                 if (sc->sc_suppress)
2186                         carp_suppress_preempt--;
2187                 sc->sc_suppress = 0;
2188         }
2189 }
2190
2191 static void
2192 carp_stop(struct carp_softc *sc, int detach)
2193 {
2194         sc->sc_if.if_flags &= ~IFF_RUNNING;
2195
2196         callout_stop(&sc->sc_ad_tmo);
2197         callout_stop(&sc->sc_md_tmo);
2198         callout_stop(&sc->sc_md6_tmo);
2199
2200         if (!detach && sc->sc_state == MASTER)
2201                 carp_send_ad(sc);
2202
2203         if (sc->sc_suppress)
2204                 carp_suppress_preempt--;
2205         sc->sc_suppress = 0;
2206
2207         if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS)
2208                 carp_suppress_preempt--;
2209         sc->sc_sendad_errors = 0;
2210         sc->sc_sendad_success = 0;
2211
2212         carp_set_state(sc, INIT);
2213         carp_setrun(sc, 0);
2214 }
2215
2216 static void
2217 carp_suspend(struct carp_softc *sc, int detach)
2218 {
2219         struct ifnet *cifp = &sc->sc_if;
2220
2221         carp_stop(sc, detach);
2222
2223         /* Retain the running state, if we are not dead yet */
2224         if (!sc->sc_dead && (cifp->if_flags & IFF_UP))
2225                 cifp->if_flags |= IFF_RUNNING;
2226 }
2227
2228 static int
2229 carp_activate_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha,
2230     struct ifnet *ifp, struct in_ifaddr *ia_if, int own)
2231 {
2232         struct ip_moptions *imo = &sc->sc_imo;
2233         struct carp_if *cif;
2234         struct carp_softc *vr, *after = NULL;
2235         int onlist, error;
2236 #ifdef INVARIANTS
2237         int assert_onlist;
2238 #endif
2239
2240         KKASSERT(vha->vha_ia != NULL);
2241
2242         KASSERT(ia_if != NULL, ("NULL backing address\n"));
2243         KASSERT(vha->vha_iaback == NULL, ("%p is already activated\n", vha));
2244         KASSERT((vha->vha_flags & CARP_VHAF_OWNER) == 0,
2245                 ("inactive vhaddr %p is the address owner\n", vha));
2246
2247         KASSERT(sc->sc_carpdev == NULL || sc->sc_carpdev == ifp,
2248                 ("%s is already on %s\n", sc->sc_if.if_xname,
2249                  sc->sc_carpdev->if_xname));
2250
2251         if (!ifp->if_carp) {
2252                 KASSERT(sc->sc_carpdev == NULL,
2253                         ("%s is already on %s\n", sc->sc_if.if_xname,
2254                          sc->sc_carpdev->if_xname));
2255
2256                 cif = kmalloc(sizeof(*cif), M_CARP, M_WAITOK | M_ZERO);
2257
2258                 error = ifpromisc(ifp, 1);
2259                 if (error) {
2260                         kfree(cif, M_CARP);
2261                         return error;
2262                 }
2263
2264                 TAILQ_INIT(&cif->vhif_vrs);
2265                 ifp->if_carp = cif;
2266         } else {
2267                 cif = ifp->if_carp;
2268                 TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
2269                         if (vr != sc && vr->sc_vhid == sc->sc_vhid)
2270                                 return EINVAL;
2271                 }
2272         }
2273
2274 #ifdef INVARIANTS
2275         if (sc->sc_carpdev != NULL)
2276                 assert_onlist = 1;
2277         else
2278                 assert_onlist = 0;
2279 #endif
2280         sc->sc_ia = ia_if;
2281         sc->sc_carpdev = ifp;
2282
2283         cif = ifp->if_carp;
2284         onlist = 0;
2285         TAILQ_FOREACH(vr, &cif->vhif_vrs, sc_list) {
2286                 if (vr == sc)
2287                         onlist = 1;
2288                 if (vr->sc_vhid < sc->sc_vhid)
2289                         after = vr;
2290         }
2291
2292 #ifdef INVARIANTS
2293         if (assert_onlist) {
2294                 KASSERT(onlist, ("%s is not on %s carp list\n",
2295                         sc->sc_if.if_xname, ifp->if_xname));
2296         } else {
2297                 KASSERT(!onlist, ("%s is already on %s carp list\n",
2298                         sc->sc_if.if_xname, ifp->if_xname));
2299         }
2300 #endif
2301
2302         if (!onlist) {
2303                 /* We're trying to keep things in order */
2304                 if (after == NULL)
2305                         TAILQ_INSERT_TAIL(&cif->vhif_vrs, sc, sc_list);
2306                 else
2307                         TAILQ_INSERT_AFTER(&cif->vhif_vrs, after, sc, sc_list);
2308         }
2309
2310         vha->vha_iaback = ia_if;
2311         sc->sc_naddrs++;
2312
2313         if (own) {
2314                 vha->vha_flags |= CARP_VHAF_OWNER;
2315
2316                 /* XXX save user configured advskew? */
2317                 sc->sc_advskew = 0;
2318         }
2319
2320         carp_addroute_vhaddr(sc, vha);
2321
2322         /*
2323          * Join the multicast group only after the backing interface
2324          * has been hooked with the CARP interface.
2325          */
2326         KASSERT(imo->imo_multicast_ifp == NULL ||
2327                 imo->imo_multicast_ifp == &sc->sc_if,
2328                 ("%s didn't leave mcast group on %s\n",
2329                  sc->sc_if.if_xname, imo->imo_multicast_ifp->if_xname));
2330
2331         if (imo->imo_num_memberships == 0) {
2332                 struct in_addr addr;
2333
2334                 addr.s_addr = htonl(INADDR_CARP_GROUP);
2335                 imo->imo_membership[0] = in_addmulti(&addr, &sc->sc_if);
2336                 if (imo->imo_membership[0] == NULL) {
2337                         carp_deactivate_vhaddr(sc, vha, FALSE);
2338                         return ENOBUFS;
2339                 }
2340
2341                 imo->imo_num_memberships++;
2342                 imo->imo_multicast_ifp = &sc->sc_if;
2343                 imo->imo_multicast_ttl = CARP_DFLTTL;
2344                 imo->imo_multicast_loop = 0;
2345         }
2346
2347         carp_hmac_prepare(sc);
2348         carp_set_state(sc, INIT);
2349         carp_setrun(sc, 0);
2350         return 0;
2351 }
2352
2353 static void
2354 carp_deactivate_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha,
2355     boolean_t del_iaback)
2356 {
2357         KKASSERT(vha->vha_ia != NULL);
2358
2359         carp_hmac_prepare(sc);
2360
2361         if (vha->vha_iaback == NULL) {
2362                 KASSERT((vha->vha_flags & CARP_VHAF_OWNER) == 0,
2363                         ("inactive vhaddr %p is the address owner\n", vha));
2364                 return;
2365         }
2366
2367         vha->vha_flags &= ~CARP_VHAF_OWNER;
2368         carp_delroute_vhaddr(sc, vha, del_iaback);
2369
2370         KKASSERT(sc->sc_naddrs > 0);
2371         vha->vha_iaback = NULL;
2372         sc->sc_naddrs--;
2373         if (!sc->sc_naddrs) {
2374                 if (sc->sc_naddrs6) {
2375                         carp_multicast_cleanup(sc);
2376                         sc->sc_ia = NULL;
2377                 } else {
2378                         carp_detach(sc, 0, del_iaback);
2379                 }
2380         }
2381 }
2382
2383 static void
2384 carp_link_addrs(struct carp_softc *sc, struct ifnet *ifp, struct ifaddr *ifa_if)
2385 {
2386         struct carp_vhaddr *vha;
2387         struct in_ifaddr *ia_if;
2388
2389         KKASSERT(ifa_if->ifa_addr->sa_family == AF_INET);
2390         ia_if = ifatoia(ifa_if);
2391
2392         /*
2393          * Test each inactive vhaddr against the newly added address.
2394          * If the newly added address could be the backing address,
2395          * then activate the matching vhaddr.
2396          */
2397         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
2398                 const struct in_ifaddr *ia;
2399                 u_long iaddr;
2400                 int own;
2401
2402                 if (vha->vha_iaback != NULL)
2403                         continue;
2404
2405                 ia = vha->vha_ia;
2406                 iaddr = ntohl(ia->ia_addr.sin_addr.s_addr);
2407
2408                 if ((iaddr & ia_if->ia_subnetmask) != ia_if->ia_subnet)
2409                         continue;
2410
2411                 own = 0;
2412                 if (ia->ia_addr.sin_addr.s_addr ==
2413                     ia_if->ia_addr.sin_addr.s_addr)
2414                         own = 1;
2415
2416                 carp_activate_vhaddr(sc, vha, ifp, ia_if, own);
2417         }
2418 }
2419
2420 static void
2421 carp_unlink_addrs(struct carp_softc *sc, struct ifnet *ifp,
2422                   struct ifaddr *ifa_if)
2423 {
2424         struct carp_vhaddr *vha;
2425         struct in_ifaddr *ia_if;
2426
2427         KKASSERT(ifa_if->ifa_addr->sa_family == AF_INET);
2428         ia_if = ifatoia(ifa_if);
2429
2430         /*
2431          * Ad src address is deleted; set it to NULL.
2432          * Following loop will try pick up a new ad src address
2433          * if one of the vhaddr could retain its backing address.
2434          */
2435         if (sc->sc_ia == ia_if)
2436                 sc->sc_ia = NULL;
2437
2438         /*
2439          * Test each active vhaddr against the deleted address.
2440          * If the deleted address is vhaddr address's backing
2441          * address, then deactivate the vhaddr.
2442          */
2443         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link) {
2444                 if (vha->vha_iaback == NULL)
2445                         continue;
2446
2447                 if (vha->vha_iaback == ia_if)
2448                         carp_deactivate_vhaddr(sc, vha, TRUE);
2449                 else if (sc->sc_ia == NULL)
2450                         sc->sc_ia = vha->vha_iaback;
2451         }
2452 }
2453
2454 static void
2455 carp_update_addrs(struct carp_softc *sc, struct ifaddr *ifa_del)
2456 {
2457         struct carp_vhaddr *vha;
2458
2459         KKASSERT(sc->sc_carpdev == NULL);
2460
2461         TAILQ_FOREACH(vha, &sc->sc_vha_list, vha_link)
2462                 carp_config_vhaddr(sc, vha, ifatoia(ifa_del));
2463 }
2464
2465 static void
2466 carp_ifaddr(void *arg __unused, struct ifnet *ifp,
2467             enum ifaddr_event event, struct ifaddr *ifa)
2468 {
2469         struct carp_softc *sc;
2470
2471         carp_gettok();
2472
2473         if (ifa->ifa_addr->sa_family != AF_INET)
2474                 goto back;
2475
2476         KASSERT(&curthread->td_msgport == cpu_portfn(0),
2477             ("not in netisr0"));
2478
2479         if (ifp->if_type == IFT_CARP) {
2480                 /*
2481                  * Address is changed on carp(4) interface
2482                  */
2483                 switch (event) {
2484                 case IFADDR_EVENT_ADD:
2485                         carp_add_addr(ifp->if_softc, ifa);
2486                         break;
2487
2488                 case IFADDR_EVENT_CHANGE:
2489                         carp_config_addr(ifp->if_softc, ifa);
2490                         break;
2491
2492                 case IFADDR_EVENT_DELETE:
2493                         carp_del_addr(ifp->if_softc, ifa);
2494                         break;
2495                 }
2496                 goto back;
2497         }
2498
2499         /*
2500          * Address is changed on non-carp(4) interface
2501          */
2502         if ((ifp->if_flags & IFF_MULTICAST) == 0)
2503                 goto back;
2504
2505         LIST_FOREACH(sc, &carpif_list, sc_next) {
2506                 if (sc->sc_carpdev != NULL && sc->sc_carpdev != ifp) {
2507                         /* Not the parent iface; skip */
2508                         continue;
2509                 }
2510
2511                 switch (event) {
2512                 case IFADDR_EVENT_ADD:
2513                         carp_link_addrs(sc, ifp, ifa);
2514                         break;
2515
2516                 case IFADDR_EVENT_DELETE:
2517                         if (sc->sc_carpdev != NULL) {
2518                                 carp_unlink_addrs(sc, ifp, ifa);
2519                                 if (sc->sc_carpdev == NULL) {
2520                                         /*
2521                                          * We no longer have the parent
2522                                          * interface, however, certain
2523                                          * virtual addresses, which are
2524                                          * not used because they can't
2525                                          * match the previous parent
2526                                          * interface's addresses, may now
2527                                          * match different interface's
2528                                          * addresses.
2529                                          */
2530                                         carp_update_addrs(sc, ifa);
2531                                 }
2532                         } else {
2533                                 /*
2534                                  * The carp(4) interface didn't have a
2535                                  * parent iface, so it is not possible
2536                                  * that it will contain any address to
2537                                  * be unlinked.
2538                                  */
2539                         }
2540                         break;
2541
2542                 case IFADDR_EVENT_CHANGE:
2543                         if (sc->sc_carpdev == NULL) {
2544                                 /*
2545                                  * The carp(4) interface didn't have a
2546                                  * parent iface, so it is not possible
2547                                  * that it will contain any address to
2548                                  * be updated.
2549                                  */
2550                                 carp_link_addrs(sc, ifp, ifa);
2551                         } else {
2552                                 /*
2553                                  * First try breaking tie with the old
2554                                  * address.  Then see whether we could
2555                                  * link certain vhaddr to the new address.
2556                                  * If that fails, i.e. carpdev is NULL,
2557                                  * we try a global update.
2558                                  *
2559                                  * NOTE: The above order is critical.
2560                                  */
2561                                 carp_unlink_addrs(sc, ifp, ifa);
2562                                 carp_link_addrs(sc, ifp, ifa);
2563                                 if (sc->sc_carpdev == NULL) {
2564                                         /*
2565                                          * See the comment in the above
2566                                          * IFADDR_EVENT_DELETE block.
2567                                          */
2568                                         carp_update_addrs(sc, NULL);
2569                                 }
2570                         }
2571                         break;
2572                 }
2573         }
2574
2575 back:
2576         carp_reltok();
2577 }
2578
2579 void
2580 carp_proto_ctlinput(netmsg_t msg)
2581 {
2582         int cmd = msg->ctlinput.nm_cmd;
2583         struct sockaddr *sa = msg->ctlinput.nm_arg;
2584         struct in_ifaddr_container *iac;
2585
2586         carp_gettok();
2587
2588         TAILQ_FOREACH(iac, &in_ifaddrheads[mycpuid], ia_link) {
2589                 struct in_ifaddr *ia = iac->ia;
2590                 struct ifnet *ifp = ia->ia_ifp;
2591
2592                 if (ifp->if_type == IFT_CARP)
2593                         continue;
2594
2595                 if (ia->ia_ifa.ifa_addr == sa) {
2596                         if (cmd == PRC_IFDOWN) {
2597                                 carp_ifaddr(NULL, ifp, IFADDR_EVENT_DELETE,
2598                                     &ia->ia_ifa);
2599                         } else if (cmd == PRC_IFUP) {
2600                                 carp_ifaddr(NULL, ifp, IFADDR_EVENT_ADD,
2601                                     &ia->ia_ifa);
2602                         }
2603                         break;
2604                 }
2605         }
2606
2607         carp_reltok();
2608         lwkt_replymsg(&msg->lmsg, 0);
2609 }
2610
2611 void
2612 carp_gettok(void)
2613 {
2614         lwkt_gettoken(&carp_tok);
2615 }
2616
2617 void
2618 carp_reltok(void)
2619 {
2620         lwkt_reltoken(&carp_tok);
2621 }
2622
2623 struct ifnet *
2624 carp_parent(struct ifnet *cifp)
2625 {
2626         struct carp_softc *sc;
2627
2628         ASSERT_LWKT_TOKEN_HELD(&carp_tok);
2629
2630         KKASSERT(cifp->if_type == IFT_CARP);
2631         sc = cifp->if_softc;
2632
2633         return sc->sc_carpdev;
2634 }
2635
2636 #define rtinitflags(x) \
2637         (((x)->ia_ifp->if_flags & (IFF_LOOPBACK | IFF_POINTOPOINT)) \
2638                  ? RTF_HOST : 0)
2639
2640 static int
2641 carp_addroute_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha)
2642 {
2643         struct in_ifaddr *ia, *iaback;
2644         int error;
2645
2646         if (sc->sc_state != MASTER)
2647                 return 0;
2648
2649         ia = vha->vha_ia;
2650         KKASSERT(ia != NULL);
2651
2652         iaback = vha->vha_iaback;
2653         KKASSERT(iaback != NULL);
2654
2655         rtinit(&iaback->ia_ifa, RTM_DELETE, rtinitflags(iaback));
2656         in_ifadown(&iaback->ia_ifa, 1);
2657         iaback->ia_flags &= ~IFA_ROUTE;
2658
2659         error = rtinit(&ia->ia_ifa, RTM_ADD, rtinitflags(ia) | RTF_UP);
2660         if (!error)
2661                 ia->ia_flags |= IFA_ROUTE;
2662         return error;
2663 }
2664
2665 static void
2666 carp_delroute_vhaddr(struct carp_softc *sc, struct carp_vhaddr *vha,
2667     boolean_t del_iaback)
2668 {
2669         struct in_ifaddr *ia, *iaback;
2670
2671         ia = vha->vha_ia;
2672         KKASSERT(ia != NULL);
2673
2674         iaback = vha->vha_iaback;
2675         KKASSERT(iaback != NULL);
2676
2677         rtinit(&ia->ia_ifa, RTM_DELETE, rtinitflags(ia));
2678         in_ifadown(&ia->ia_ifa, 1);
2679         ia->ia_flags &= ~IFA_ROUTE;
2680
2681         if (!del_iaback && (iaback->ia_ifp->if_flags & IFF_UP)) {
2682                 int error;
2683
2684                 error = rtinit(&iaback->ia_ifa, RTM_ADD,
2685                     rtinitflags(iaback) | RTF_UP);
2686                 if (!error)
2687                         iaback->ia_flags |= IFA_ROUTE;
2688         }
2689 }
2690
2691 static int
2692 carp_modevent(module_t mod, int type, void *data)
2693 {
2694         switch (type) {
2695         case MOD_LOAD:
2696                 LIST_INIT(&carpif_list);
2697                 carp_ifdetach_event =
2698                 EVENTHANDLER_REGISTER(ifnet_detach_event, carp_ifdetach, NULL,
2699                                       EVENTHANDLER_PRI_ANY);
2700                 carp_ifaddr_event =
2701                 EVENTHANDLER_REGISTER(ifaddr_event, carp_ifaddr, NULL,
2702                                       EVENTHANDLER_PRI_FIRST);
2703                 if_clone_attach(&carp_cloner);
2704                 break;
2705
2706         case MOD_UNLOAD:
2707                 EVENTHANDLER_DEREGISTER(ifnet_detach_event,
2708                                         carp_ifdetach_event);
2709                 EVENTHANDLER_DEREGISTER(ifaddr_event,
2710                                         carp_ifaddr_event);
2711                 if_clone_detach(&carp_cloner);
2712                 break;
2713
2714         default:
2715                 return (EINVAL);
2716         }
2717         return (0);
2718 }
2719
2720 static moduledata_t carp_mod = {
2721         "carp",
2722         carp_modevent,
2723         0
2724 };
2725 DECLARE_MODULE(carp, carp_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);