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