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