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