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