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