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