]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_carp.c
Update mandoc to 1.13.2
[FreeBSD/FreeBSD.git] / sys / netinet / ip_carp.c
1 /*-
2  * Copyright (c) 2002 Michael Shalayeff.
3  * Copyright (c) 2003 Ryan McBride.
4  * Copyright (c) 2011 Gleb Smirnoff <glebius@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
20  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
24  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
25  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
26  * THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include "opt_bpf.h"
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/bus.h>
39 #include <sys/jail.h>
40 #include <sys/kernel.h>
41 #include <sys/limits.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/module.h>
45 #include <sys/priv.h>
46 #include <sys/proc.h>
47 #include <sys/protosw.h>
48 #include <sys/socket.h>
49 #include <sys/sockio.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/taskqueue.h>
53 #include <sys/counter.h>
54
55 #include <net/ethernet.h>
56 #include <net/fddi.h>
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #include <net/if_dl.h>
60 #include <net/if_llatbl.h>
61 #include <net/if_types.h>
62 #include <net/iso88025.h>
63 #include <net/route.h>
64 #include <net/vnet.h>
65
66 #if defined(INET) || defined(INET6)
67 #include <netinet/in.h>
68 #include <netinet/in_var.h>
69 #include <netinet/ip_carp.h>
70 #include <netinet/ip.h>
71 #include <machine/in_cksum.h>
72 #endif
73 #ifdef INET
74 #include <netinet/ip_var.h>
75 #include <netinet/if_ether.h>
76 #endif
77
78 #ifdef INET6
79 #include <netinet/icmp6.h>
80 #include <netinet/ip6.h>
81 #include <netinet6/in6_var.h>
82 #include <netinet6/ip6_var.h>
83 #include <netinet6/scope6_var.h>
84 #include <netinet6/nd6.h>
85 #endif
86
87 #include <crypto/sha1.h>
88
89 static MALLOC_DEFINE(M_CARP, "CARP", "CARP addresses");
90
91 struct carp_softc {
92         struct ifnet            *sc_carpdev;    /* Pointer to parent ifnet. */
93         struct ifaddr           **sc_ifas;      /* Our ifaddrs. */
94         struct sockaddr_dl      sc_addr;        /* Our link level address. */
95         struct callout          sc_ad_tmo;      /* Advertising timeout. */
96 #ifdef INET
97         struct callout          sc_md_tmo;      /* Master down timeout. */
98 #endif
99 #ifdef INET6
100         struct callout          sc_md6_tmo;     /* XXX: Master down timeout. */
101 #endif
102         struct mtx              sc_mtx;
103
104         int                     sc_vhid;
105         int                     sc_advskew;
106         int                     sc_advbase;
107
108         int                     sc_naddrs;
109         int                     sc_naddrs6;
110         int                     sc_ifasiz;
111         enum { INIT = 0, BACKUP, MASTER }       sc_state;
112         int                     sc_suppress;
113         int                     sc_sendad_errors;
114 #define CARP_SENDAD_MAX_ERRORS  3
115         int                     sc_sendad_success;
116 #define CARP_SENDAD_MIN_SUCCESS 3
117
118         int                     sc_init_counter;
119         uint64_t                sc_counter;
120
121         /* authentication */
122 #define CARP_HMAC_PAD   64
123         unsigned char sc_key[CARP_KEY_LEN];
124         unsigned char sc_pad[CARP_HMAC_PAD];
125         SHA1_CTX sc_sha1;
126
127         TAILQ_ENTRY(carp_softc) sc_list;        /* On the carp_if list. */
128         LIST_ENTRY(carp_softc)  sc_next;        /* On the global list. */
129 };
130
131 struct carp_if {
132 #ifdef INET
133         int     cif_naddrs;
134 #endif
135 #ifdef INET6
136         int     cif_naddrs6;
137 #endif
138         TAILQ_HEAD(, carp_softc) cif_vrs;
139 #ifdef INET
140         struct ip_moptions       cif_imo;
141 #endif
142 #ifdef INET6
143         struct ip6_moptions      cif_im6o;
144 #endif
145         struct ifnet    *cif_ifp;
146         struct mtx      cif_mtx;
147         uint32_t        cif_flags;
148 #define CIF_PROMISC     0x00000001
149 };
150
151 #define CARP_INET       0
152 #define CARP_INET6      1
153 static int proto_reg[] = {-1, -1};
154
155 /*
156  * Brief design of carp(4).
157  *
158  * Any carp-capable ifnet may have a list of carp softcs hanging off
159  * its ifp->if_carp pointer. Each softc represents one unique virtual
160  * host id, or vhid. The softc has a back pointer to the ifnet. All
161  * softcs are joined in a global list, which has quite limited use.
162  *
163  * Any interface address that takes part in CARP negotiation has a
164  * pointer to the softc of its vhid, ifa->ifa_carp. That could be either
165  * AF_INET or AF_INET6 address.
166  *
167  * Although, one can get the softc's backpointer to ifnet and traverse
168  * through its ifp->if_addrhead queue to find all interface addresses
169  * involved in CARP, we keep a growable array of ifaddr pointers. This
170  * allows us to avoid grabbing the IF_ADDR_LOCK() in many traversals that
171  * do calls into the network stack, thus avoiding LORs.
172  *
173  * Locking:
174  *
175  * Each softc has a lock sc_mtx. It is used to synchronise carp_input_c(),
176  * callout-driven events and ioctl()s.
177  *
178  * To traverse the list of softcs on an ifnet we use CIF_LOCK(), to
179  * traverse the global list we use the mutex carp_mtx.
180  *
181  * Known issues with locking:
182  *
183  * - There is no protection for races between two ioctl() requests,
184  *   neither SIOCSVH, nor SIOCAIFADDR & SIOCAIFADDR_IN6. I think that all
185  *   interface ioctl()s should be serialized right in net/if.c.
186  * - Sending ad, we put the pointer to the softc in an mtag, and no reference
187  *   counting is done on the softc.
188  * - On module unload we may race (?) with packet processing thread
189  *   dereferencing our function pointers.
190  */
191
192 /* Accept incoming CARP packets. */
193 static VNET_DEFINE(int, carp_allow) = 1;
194 #define V_carp_allow    VNET(carp_allow)
195
196 /* Preempt slower nodes. */
197 static VNET_DEFINE(int, carp_preempt) = 0;
198 #define V_carp_preempt  VNET(carp_preempt)
199
200 /* Log level. */
201 static VNET_DEFINE(int, carp_log) = 1;
202 #define V_carp_log      VNET(carp_log)
203
204 /* Global advskew demotion. */
205 static VNET_DEFINE(int, carp_demotion) = 0;
206 #define V_carp_demotion VNET(carp_demotion)
207
208 /* Send error demotion factor. */
209 static VNET_DEFINE(int, carp_senderr_adj) = CARP_MAXSKEW;
210 #define V_carp_senderr_adj      VNET(carp_senderr_adj)
211
212 /* Iface down demotion factor. */
213 static VNET_DEFINE(int, carp_ifdown_adj) = CARP_MAXSKEW;
214 #define V_carp_ifdown_adj       VNET(carp_ifdown_adj)
215
216 static int carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS);
217
218 SYSCTL_NODE(_net_inet, IPPROTO_CARP,    carp,   CTLFLAG_RW, 0,  "CARP");
219 SYSCTL_INT(_net_inet_carp, OID_AUTO, allow, CTLFLAG_VNET | CTLFLAG_RW,
220     &VNET_NAME(carp_allow), 0, "Accept incoming CARP packets");
221 SYSCTL_INT(_net_inet_carp, OID_AUTO, preempt, CTLFLAG_VNET | CTLFLAG_RW,
222     &VNET_NAME(carp_preempt), 0, "High-priority backup preemption mode");
223 SYSCTL_INT(_net_inet_carp, OID_AUTO, log, CTLFLAG_VNET | CTLFLAG_RW,
224     &VNET_NAME(carp_log), 0, "CARP log level");
225 SYSCTL_PROC(_net_inet_carp, OID_AUTO, demotion,
226     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
227     0, 0, carp_demote_adj_sysctl, "I",
228     "Adjust demotion factor (skew of advskew)");
229 SYSCTL_INT(_net_inet_carp, OID_AUTO, senderr_demotion_factor,
230     CTLFLAG_VNET | CTLFLAG_RW,
231     &VNET_NAME(carp_senderr_adj), 0, "Send error demotion factor adjustment");
232 SYSCTL_INT(_net_inet_carp, OID_AUTO, ifdown_demotion_factor,
233     CTLFLAG_VNET | CTLFLAG_RW,
234     &VNET_NAME(carp_ifdown_adj), 0,
235     "Interface down demotion factor adjustment");
236
237 VNET_PCPUSTAT_DEFINE(struct carpstats, carpstats);
238 VNET_PCPUSTAT_SYSINIT(carpstats);
239 VNET_PCPUSTAT_SYSUNINIT(carpstats);
240
241 #define CARPSTATS_ADD(name, val)        \
242     counter_u64_add(VNET(carpstats)[offsetof(struct carpstats, name) / \
243         sizeof(uint64_t)], (val))
244 #define CARPSTATS_INC(name)             CARPSTATS_ADD(name, 1)
245
246 SYSCTL_VNET_PCPUSTAT(_net_inet_carp, OID_AUTO, stats, struct carpstats,
247     carpstats, "CARP statistics (struct carpstats, netinet/ip_carp.h)");
248
249 #define CARP_LOCK_INIT(sc)      mtx_init(&(sc)->sc_mtx, "carp_softc",   \
250         NULL, MTX_DEF)
251 #define CARP_LOCK_DESTROY(sc)   mtx_destroy(&(sc)->sc_mtx)
252 #define CARP_LOCK_ASSERT(sc)    mtx_assert(&(sc)->sc_mtx, MA_OWNED)
253 #define CARP_LOCK(sc)           mtx_lock(&(sc)->sc_mtx)
254 #define CARP_UNLOCK(sc)         mtx_unlock(&(sc)->sc_mtx)
255 #define CIF_LOCK_INIT(cif)      mtx_init(&(cif)->cif_mtx, "carp_if",   \
256         NULL, MTX_DEF)
257 #define CIF_LOCK_DESTROY(cif)   mtx_destroy(&(cif)->cif_mtx)
258 #define CIF_LOCK_ASSERT(cif)    mtx_assert(&(cif)->cif_mtx, MA_OWNED)
259 #define CIF_LOCK(cif)           mtx_lock(&(cif)->cif_mtx)
260 #define CIF_UNLOCK(cif)         mtx_unlock(&(cif)->cif_mtx)
261 #define CIF_FREE(cif)   do {                            \
262                 CIF_LOCK_ASSERT(cif);                   \
263                 if (TAILQ_EMPTY(&(cif)->cif_vrs))       \
264                         carp_free_if(cif);              \
265                 else                                    \
266                         CIF_UNLOCK(cif);                \
267 } while (0)
268
269 #define CARP_LOG(...)   do {                            \
270         if (V_carp_log > 0)                             \
271                 log(LOG_INFO, "carp: " __VA_ARGS__);    \
272 } while (0)
273
274 #define CARP_DEBUG(...) do {                            \
275         if (V_carp_log > 1)                             \
276                 log(LOG_DEBUG, __VA_ARGS__);            \
277 } while (0)
278
279 #define IFNET_FOREACH_IFA(ifp, ifa)                                     \
280         IF_ADDR_LOCK_ASSERT(ifp);                                       \
281         TAILQ_FOREACH((ifa), &(ifp)->if_addrhead, ifa_link)             \
282                 if ((ifa)->ifa_carp != NULL)
283
284 #define CARP_FOREACH_IFA(sc, ifa)                                       \
285         CARP_LOCK_ASSERT(sc);                                           \
286         for (int _i = 0;                                                \
287                 _i < (sc)->sc_naddrs + (sc)->sc_naddrs6 &&              \
288                 ((ifa) = sc->sc_ifas[_i]) != NULL;                      \
289                 ++_i)
290
291 #define IFNET_FOREACH_CARP(ifp, sc)                                     \
292         CIF_LOCK_ASSERT(ifp->if_carp);                                  \
293         TAILQ_FOREACH((sc), &(ifp)->if_carp->cif_vrs, sc_list)
294
295 #define DEMOTE_ADVSKEW(sc)                                      \
296     (((sc)->sc_advskew + V_carp_demotion > CARP_MAXSKEW) ?      \
297     CARP_MAXSKEW : ((sc)->sc_advskew + V_carp_demotion))
298
299 static void     carp_input_c(struct mbuf *, struct carp_header *, sa_family_t);
300 static struct carp_softc
301                 *carp_alloc(struct ifnet *);
302 static void     carp_detach_locked(struct ifaddr *);
303 static void     carp_destroy(struct carp_softc *);
304 static struct carp_if
305                 *carp_alloc_if(struct ifnet *);
306 static void     carp_free_if(struct carp_if *);
307 static void     carp_set_state(struct carp_softc *, int);
308 static void     carp_sc_state(struct carp_softc *);
309 static void     carp_setrun(struct carp_softc *, sa_family_t);
310 static void     carp_master_down(void *);
311 static void     carp_master_down_locked(struct carp_softc *);
312 static void     carp_send_ad(void *);
313 static void     carp_send_ad_locked(struct carp_softc *);
314 static void     carp_addroute(struct carp_softc *);
315 static void     carp_ifa_addroute(struct ifaddr *);
316 static void     carp_delroute(struct carp_softc *);
317 static void     carp_ifa_delroute(struct ifaddr *);
318 static void     carp_send_ad_all(void *, int);
319 static void     carp_demote_adj(int, char *);
320
321 static LIST_HEAD(, carp_softc) carp_list;
322 static struct mtx carp_mtx;
323 static struct task carp_sendall_task =
324     TASK_INITIALIZER(0, carp_send_ad_all, NULL);
325
326 static void
327 carp_hmac_prepare(struct carp_softc *sc)
328 {
329         uint8_t version = CARP_VERSION, type = CARP_ADVERTISEMENT;
330         uint8_t vhid = sc->sc_vhid & 0xff;
331         struct ifaddr *ifa;
332         int i, found;
333 #ifdef INET
334         struct in_addr last, cur, in;
335 #endif
336 #ifdef INET6
337         struct in6_addr last6, cur6, in6;
338 #endif
339
340         CARP_LOCK_ASSERT(sc);
341
342         /* Compute ipad from key. */
343         bzero(sc->sc_pad, sizeof(sc->sc_pad));
344         bcopy(sc->sc_key, sc->sc_pad, sizeof(sc->sc_key));
345         for (i = 0; i < sizeof(sc->sc_pad); i++)
346                 sc->sc_pad[i] ^= 0x36;
347
348         /* Precompute first part of inner hash. */
349         SHA1Init(&sc->sc_sha1);
350         SHA1Update(&sc->sc_sha1, sc->sc_pad, sizeof(sc->sc_pad));
351         SHA1Update(&sc->sc_sha1, (void *)&version, sizeof(version));
352         SHA1Update(&sc->sc_sha1, (void *)&type, sizeof(type));
353         SHA1Update(&sc->sc_sha1, (void *)&vhid, sizeof(vhid));
354 #ifdef INET
355         cur.s_addr = 0;
356         do {
357                 found = 0;
358                 last = cur;
359                 cur.s_addr = 0xffffffff;
360                 CARP_FOREACH_IFA(sc, ifa) {
361                         in.s_addr = ifatoia(ifa)->ia_addr.sin_addr.s_addr;
362                         if (ifa->ifa_addr->sa_family == AF_INET &&
363                             ntohl(in.s_addr) > ntohl(last.s_addr) &&
364                             ntohl(in.s_addr) < ntohl(cur.s_addr)) {
365                                 cur.s_addr = in.s_addr;
366                                 found++;
367                         }
368                 }
369                 if (found)
370                         SHA1Update(&sc->sc_sha1, (void *)&cur, sizeof(cur));
371         } while (found);
372 #endif /* INET */
373 #ifdef INET6
374         memset(&cur6, 0, sizeof(cur6));
375         do {
376                 found = 0;
377                 last6 = cur6;
378                 memset(&cur6, 0xff, sizeof(cur6));
379                 CARP_FOREACH_IFA(sc, ifa) {
380                         in6 = ifatoia6(ifa)->ia_addr.sin6_addr;
381                         if (IN6_IS_SCOPE_EMBED(&in6))
382                                 in6.s6_addr16[1] = 0;
383                         if (ifa->ifa_addr->sa_family == AF_INET6 &&
384                             memcmp(&in6, &last6, sizeof(in6)) > 0 &&
385                             memcmp(&in6, &cur6, sizeof(in6)) < 0) {
386                                 cur6 = in6;
387                                 found++;
388                         }
389                 }
390                 if (found)
391                         SHA1Update(&sc->sc_sha1, (void *)&cur6, sizeof(cur6));
392         } while (found);
393 #endif /* INET6 */
394
395         /* convert ipad to opad */
396         for (i = 0; i < sizeof(sc->sc_pad); i++)
397                 sc->sc_pad[i] ^= 0x36 ^ 0x5c;
398 }
399
400 static void
401 carp_hmac_generate(struct carp_softc *sc, uint32_t counter[2],
402     unsigned char md[20])
403 {
404         SHA1_CTX sha1ctx;
405
406         CARP_LOCK_ASSERT(sc);
407
408         /* fetch first half of inner hash */
409         bcopy(&sc->sc_sha1, &sha1ctx, sizeof(sha1ctx));
410
411         SHA1Update(&sha1ctx, (void *)counter, sizeof(sc->sc_counter));
412         SHA1Final(md, &sha1ctx);
413
414         /* outer hash */
415         SHA1Init(&sha1ctx);
416         SHA1Update(&sha1ctx, sc->sc_pad, sizeof(sc->sc_pad));
417         SHA1Update(&sha1ctx, md, 20);
418         SHA1Final(md, &sha1ctx);
419 }
420
421 static int
422 carp_hmac_verify(struct carp_softc *sc, uint32_t counter[2],
423     unsigned char md[20])
424 {
425         unsigned char md2[20];
426
427         CARP_LOCK_ASSERT(sc);
428
429         carp_hmac_generate(sc, counter, md2);
430
431         return (bcmp(md, md2, sizeof(md2)));
432 }
433
434 /*
435  * process input packet.
436  * we have rearranged checks order compared to the rfc,
437  * but it seems more efficient this way or not possible otherwise.
438  */
439 #ifdef INET
440 int
441 carp_input(struct mbuf **mp, int *offp, int proto)
442 {
443         struct mbuf *m = *mp;
444         struct ip *ip = mtod(m, struct ip *);
445         struct carp_header *ch;
446         int iplen, len;
447
448         iplen = *offp;
449         *mp = NULL;
450
451         CARPSTATS_INC(carps_ipackets);
452
453         if (!V_carp_allow) {
454                 m_freem(m);
455                 return (IPPROTO_DONE);
456         }
457
458         /* verify that the IP TTL is 255.  */
459         if (ip->ip_ttl != CARP_DFLTTL) {
460                 CARPSTATS_INC(carps_badttl);
461                 CARP_DEBUG("%s: received ttl %d != 255 on %s\n", __func__,
462                     ip->ip_ttl,
463                     m->m_pkthdr.rcvif->if_xname);
464                 m_freem(m);
465                 return (IPPROTO_DONE);
466         }
467
468         iplen = ip->ip_hl << 2;
469
470         if (m->m_pkthdr.len < iplen + sizeof(*ch)) {
471                 CARPSTATS_INC(carps_badlen);
472                 CARP_DEBUG("%s: received len %zd < sizeof(struct carp_header) "
473                     "on %s\n", __func__, m->m_len - sizeof(struct ip),
474                     m->m_pkthdr.rcvif->if_xname);
475                 m_freem(m);
476                 return (IPPROTO_DONE);
477         }
478
479         if (iplen + sizeof(*ch) < m->m_len) {
480                 if ((m = m_pullup(m, iplen + sizeof(*ch))) == NULL) {
481                         CARPSTATS_INC(carps_hdrops);
482                         CARP_DEBUG("%s: pullup failed\n", __func__);
483                         return (IPPROTO_DONE);
484                 }
485                 ip = mtod(m, struct ip *);
486         }
487         ch = (struct carp_header *)((char *)ip + iplen);
488
489         /*
490          * verify that the received packet length is
491          * equal to the CARP header
492          */
493         len = iplen + sizeof(*ch);
494         if (len > m->m_pkthdr.len) {
495                 CARPSTATS_INC(carps_badlen);
496                 CARP_DEBUG("%s: packet too short %d on %s\n", __func__,
497                     m->m_pkthdr.len,
498                     m->m_pkthdr.rcvif->if_xname);
499                 m_freem(m);
500                 return (IPPROTO_DONE);
501         }
502
503         if ((m = m_pullup(m, len)) == NULL) {
504                 CARPSTATS_INC(carps_hdrops);
505                 return (IPPROTO_DONE);
506         }
507         ip = mtod(m, struct ip *);
508         ch = (struct carp_header *)((char *)ip + iplen);
509
510         /* verify the CARP checksum */
511         m->m_data += iplen;
512         if (in_cksum(m, len - iplen)) {
513                 CARPSTATS_INC(carps_badsum);
514                 CARP_DEBUG("%s: checksum failed on %s\n", __func__,
515                     m->m_pkthdr.rcvif->if_xname);
516                 m_freem(m);
517                 return (IPPROTO_DONE);
518         }
519         m->m_data -= iplen;
520
521         carp_input_c(m, ch, AF_INET);
522         return (IPPROTO_DONE);
523 }
524 #endif
525
526 #ifdef INET6
527 int
528 carp6_input(struct mbuf **mp, int *offp, int proto)
529 {
530         struct mbuf *m = *mp;
531         struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
532         struct carp_header *ch;
533         u_int len;
534
535         CARPSTATS_INC(carps_ipackets6);
536
537         if (!V_carp_allow) {
538                 m_freem(m);
539                 return (IPPROTO_DONE);
540         }
541
542         /* check if received on a valid carp interface */
543         if (m->m_pkthdr.rcvif->if_carp == NULL) {
544                 CARPSTATS_INC(carps_badif);
545                 CARP_DEBUG("%s: packet received on non-carp interface: %s\n",
546                     __func__, m->m_pkthdr.rcvif->if_xname);
547                 m_freem(m);
548                 return (IPPROTO_DONE);
549         }
550
551         /* verify that the IP TTL is 255 */
552         if (ip6->ip6_hlim != CARP_DFLTTL) {
553                 CARPSTATS_INC(carps_badttl);
554                 CARP_DEBUG("%s: received ttl %d != 255 on %s\n", __func__,
555                     ip6->ip6_hlim, m->m_pkthdr.rcvif->if_xname);
556                 m_freem(m);
557                 return (IPPROTO_DONE);
558         }
559
560         /* verify that we have a complete carp packet */
561         len = m->m_len;
562         IP6_EXTHDR_GET(ch, struct carp_header *, m, *offp, sizeof(*ch));
563         if (ch == NULL) {
564                 CARPSTATS_INC(carps_badlen);
565                 CARP_DEBUG("%s: packet size %u too small\n", __func__, len);
566                 return (IPPROTO_DONE);
567         }
568
569
570         /* verify the CARP checksum */
571         m->m_data += *offp;
572         if (in_cksum(m, sizeof(*ch))) {
573                 CARPSTATS_INC(carps_badsum);
574                 CARP_DEBUG("%s: checksum failed, on %s\n", __func__,
575                     m->m_pkthdr.rcvif->if_xname);
576                 m_freem(m);
577                 return (IPPROTO_DONE);
578         }
579         m->m_data -= *offp;
580
581         carp_input_c(m, ch, AF_INET6);
582         return (IPPROTO_DONE);
583 }
584 #endif /* INET6 */
585
586 static void
587 carp_input_c(struct mbuf *m, struct carp_header *ch, sa_family_t af)
588 {
589         struct ifnet *ifp = m->m_pkthdr.rcvif;
590         struct ifaddr *ifa;
591         struct carp_softc *sc;
592         uint64_t tmp_counter;
593         struct timeval sc_tv, ch_tv;
594
595         /* verify that the VHID is valid on the receiving interface */
596         IF_ADDR_RLOCK(ifp);
597         IFNET_FOREACH_IFA(ifp, ifa)
598                 if (ifa->ifa_addr->sa_family == af &&
599                     ifa->ifa_carp->sc_vhid == ch->carp_vhid) {
600                         ifa_ref(ifa);
601                         break;
602                 }
603         IF_ADDR_RUNLOCK(ifp);
604
605         if (ifa == NULL) {
606                 CARPSTATS_INC(carps_badvhid);
607                 m_freem(m);
608                 return;
609         }
610
611         /* verify the CARP version. */
612         if (ch->carp_version != CARP_VERSION) {
613                 CARPSTATS_INC(carps_badver);
614                 CARP_DEBUG("%s: invalid version %d\n", ifp->if_xname,
615                     ch->carp_version);
616                 ifa_free(ifa);
617                 m_freem(m);
618                 return;
619         }
620
621         sc = ifa->ifa_carp;
622         CARP_LOCK(sc);
623         ifa_free(ifa);
624
625         if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) {
626                 CARPSTATS_INC(carps_badauth);
627                 CARP_DEBUG("%s: incorrect hash for VHID %u@%s\n", __func__,
628                     sc->sc_vhid, ifp->if_xname);
629                 goto out;
630         }
631
632         tmp_counter = ntohl(ch->carp_counter[0]);
633         tmp_counter = tmp_counter<<32;
634         tmp_counter += ntohl(ch->carp_counter[1]);
635
636         /* XXX Replay protection goes here */
637
638         sc->sc_init_counter = 0;
639         sc->sc_counter = tmp_counter;
640
641         sc_tv.tv_sec = sc->sc_advbase;
642         sc_tv.tv_usec = DEMOTE_ADVSKEW(sc) * 1000000 / 256;
643         ch_tv.tv_sec = ch->carp_advbase;
644         ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256;
645
646         switch (sc->sc_state) {
647         case INIT:
648                 break;
649         case MASTER:
650                 /*
651                  * If we receive an advertisement from a master who's going to
652                  * be more frequent than us, go into BACKUP state.
653                  */
654                 if (timevalcmp(&sc_tv, &ch_tv, >) ||
655                     timevalcmp(&sc_tv, &ch_tv, ==)) {
656                         callout_stop(&sc->sc_ad_tmo);
657                         CARP_LOG("VHID %u@%s: MASTER -> BACKUP "
658                             "(more frequent advertisement received)\n",
659                             sc->sc_vhid,
660                             sc->sc_carpdev->if_xname);
661                         carp_set_state(sc, BACKUP);
662                         carp_setrun(sc, 0);
663                         carp_delroute(sc);
664                 }
665                 break;
666         case BACKUP:
667                 /*
668                  * If we're pre-empting masters who advertise slower than us,
669                  * and this one claims to be slower, treat him as down.
670                  */
671                 if (V_carp_preempt && timevalcmp(&sc_tv, &ch_tv, <)) {
672                         CARP_LOG("VHID %u@%s: BACKUP -> MASTER "
673                             "(preempting a slower master)\n",
674                             sc->sc_vhid,
675                             sc->sc_carpdev->if_xname);
676                         carp_master_down_locked(sc);
677                         break;
678                 }
679
680                 /*
681                  *  If the master is going to advertise at such a low frequency
682                  *  that he's guaranteed to time out, we'd might as well just
683                  *  treat him as timed out now.
684                  */
685                 sc_tv.tv_sec = sc->sc_advbase * 3;
686                 if (timevalcmp(&sc_tv, &ch_tv, <)) {
687                         CARP_LOG("VHID %u@%s: BACKUP -> MASTER "
688                             "(master timed out)\n",
689                             sc->sc_vhid,
690                             sc->sc_carpdev->if_xname);
691                         carp_master_down_locked(sc);
692                         break;
693                 }
694
695                 /*
696                  * Otherwise, we reset the counter and wait for the next
697                  * advertisement.
698                  */
699                 carp_setrun(sc, af);
700                 break;
701         }
702
703 out:
704         CARP_UNLOCK(sc);
705         m_freem(m);
706 }
707
708 static int
709 carp_prepare_ad(struct mbuf *m, struct carp_softc *sc, struct carp_header *ch)
710 {
711         struct m_tag *mtag;
712
713         if (sc->sc_init_counter) {
714                 /* this could also be seconds since unix epoch */
715                 sc->sc_counter = arc4random();
716                 sc->sc_counter = sc->sc_counter << 32;
717                 sc->sc_counter += arc4random();
718         } else
719                 sc->sc_counter++;
720
721         ch->carp_counter[0] = htonl((sc->sc_counter>>32)&0xffffffff);
722         ch->carp_counter[1] = htonl(sc->sc_counter&0xffffffff);
723
724         carp_hmac_generate(sc, ch->carp_counter, ch->carp_md);
725
726         /* Tag packet for carp_output */
727         if ((mtag = m_tag_get(PACKET_TAG_CARP, sizeof(struct carp_softc *),
728             M_NOWAIT)) == NULL) {
729                 m_freem(m);
730                 CARPSTATS_INC(carps_onomem);
731                 return (ENOMEM);
732         }
733         bcopy(&sc, mtag + 1, sizeof(sc));
734         m_tag_prepend(m, mtag);
735
736         return (0);
737 }
738
739 /*
740  * To avoid LORs and possible recursions this function shouldn't
741  * be called directly, but scheduled via taskqueue.
742  */
743 static void
744 carp_send_ad_all(void *ctx __unused, int pending __unused)
745 {
746         struct carp_softc *sc;
747
748         mtx_lock(&carp_mtx);
749         LIST_FOREACH(sc, &carp_list, sc_next)
750                 if (sc->sc_state == MASTER) {
751                         CARP_LOCK(sc);
752                         CURVNET_SET(sc->sc_carpdev->if_vnet);
753                         carp_send_ad_locked(sc);
754                         CURVNET_RESTORE();
755                         CARP_UNLOCK(sc);
756                 }
757         mtx_unlock(&carp_mtx);
758 }
759
760 /* Send a periodic advertisement, executed in callout context. */
761 static void
762 carp_send_ad(void *v)
763 {
764         struct carp_softc *sc = v;
765
766         CARP_LOCK_ASSERT(sc);
767         CURVNET_SET(sc->sc_carpdev->if_vnet);
768         carp_send_ad_locked(sc);
769         CURVNET_RESTORE();
770         CARP_UNLOCK(sc);
771 }
772
773 static void
774 carp_send_ad_error(struct carp_softc *sc, int error)
775 {
776
777         if (error) {
778                 if (sc->sc_sendad_errors < INT_MAX)
779                         sc->sc_sendad_errors++;
780                 if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
781                         static const char fmt[] = "send error %d on %s";
782                         char msg[sizeof(fmt) + IFNAMSIZ];
783
784                         sprintf(msg, fmt, error, sc->sc_carpdev->if_xname);
785                         carp_demote_adj(V_carp_senderr_adj, msg);
786                 }
787                 sc->sc_sendad_success = 0;
788         } else {
789                 if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS &&
790                     ++sc->sc_sendad_success >= CARP_SENDAD_MIN_SUCCESS) {
791                         static const char fmt[] = "send ok on %s";
792                         char msg[sizeof(fmt) + IFNAMSIZ];
793
794                         sprintf(msg, fmt, sc->sc_carpdev->if_xname);
795                         carp_demote_adj(-V_carp_senderr_adj, msg);
796                         sc->sc_sendad_errors = 0;
797                 } else
798                         sc->sc_sendad_errors = 0;
799         }
800 }
801
802 static void
803 carp_send_ad_locked(struct carp_softc *sc)
804 {
805         struct carp_header ch;
806         struct timeval tv;
807         struct sockaddr sa;
808         struct ifaddr *ifa;
809         struct carp_header *ch_ptr;
810         struct mbuf *m;
811         int len, advskew;
812
813         CARP_LOCK_ASSERT(sc);
814
815         advskew = DEMOTE_ADVSKEW(sc);
816         tv.tv_sec = sc->sc_advbase;
817         tv.tv_usec = advskew * 1000000 / 256;
818
819         ch.carp_version = CARP_VERSION;
820         ch.carp_type = CARP_ADVERTISEMENT;
821         ch.carp_vhid = sc->sc_vhid;
822         ch.carp_advbase = sc->sc_advbase;
823         ch.carp_advskew = advskew;
824         ch.carp_authlen = 7;    /* XXX DEFINE */
825         ch.carp_pad1 = 0;       /* must be zero */
826         ch.carp_cksum = 0;
827
828         /* XXXGL: OpenBSD picks first ifaddr with needed family. */
829
830 #ifdef INET
831         if (sc->sc_naddrs) {
832                 struct ip *ip;
833
834                 m = m_gethdr(M_NOWAIT, MT_DATA);
835                 if (m == NULL) {
836                         CARPSTATS_INC(carps_onomem);
837                         goto resched;
838                 }
839                 len = sizeof(*ip) + sizeof(ch);
840                 m->m_pkthdr.len = len;
841                 m->m_pkthdr.rcvif = NULL;
842                 m->m_len = len;
843                 MH_ALIGN(m, m->m_len);
844                 m->m_flags |= M_MCAST;
845                 ip = mtod(m, struct ip *);
846                 ip->ip_v = IPVERSION;
847                 ip->ip_hl = sizeof(*ip) >> 2;
848                 ip->ip_tos = IPTOS_LOWDELAY;
849                 ip->ip_len = htons(len);
850                 ip->ip_id = ip_newid();
851                 ip->ip_off = htons(IP_DF);
852                 ip->ip_ttl = CARP_DFLTTL;
853                 ip->ip_p = IPPROTO_CARP;
854                 ip->ip_sum = 0;
855
856                 bzero(&sa, sizeof(sa));
857                 sa.sa_family = AF_INET;
858                 ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
859                 if (ifa != NULL) {
860                         ip->ip_src.s_addr =
861                             ifatoia(ifa)->ia_addr.sin_addr.s_addr;
862                         ifa_free(ifa);
863                 } else
864                         ip->ip_src.s_addr = 0;
865                 ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP);
866
867                 ch_ptr = (struct carp_header *)(&ip[1]);
868                 bcopy(&ch, ch_ptr, sizeof(ch));
869                 if (carp_prepare_ad(m, sc, ch_ptr))
870                         goto resched;
871
872                 m->m_data += sizeof(*ip);
873                 ch_ptr->carp_cksum = in_cksum(m, len - sizeof(*ip));
874                 m->m_data -= sizeof(*ip);
875
876                 CARPSTATS_INC(carps_opackets);
877
878                 carp_send_ad_error(sc, ip_output(m, NULL, NULL, IP_RAWOUTPUT,
879                     &sc->sc_carpdev->if_carp->cif_imo, NULL));
880         }
881 #endif /* INET */
882 #ifdef INET6
883         if (sc->sc_naddrs6) {
884                 struct ip6_hdr *ip6;
885
886                 m = m_gethdr(M_NOWAIT, MT_DATA);
887                 if (m == NULL) {
888                         CARPSTATS_INC(carps_onomem);
889                         goto resched;
890                 }
891                 len = sizeof(*ip6) + sizeof(ch);
892                 m->m_pkthdr.len = len;
893                 m->m_pkthdr.rcvif = NULL;
894                 m->m_len = len;
895                 MH_ALIGN(m, m->m_len);
896                 m->m_flags |= M_MCAST;
897                 ip6 = mtod(m, struct ip6_hdr *);
898                 bzero(ip6, sizeof(*ip6));
899                 ip6->ip6_vfc |= IPV6_VERSION;
900                 ip6->ip6_hlim = CARP_DFLTTL;
901                 ip6->ip6_nxt = IPPROTO_CARP;
902                 bzero(&sa, sizeof(sa));
903
904                 /* set the source address */
905                 sa.sa_family = AF_INET6;
906                 ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
907                 if (ifa != NULL) {
908                         bcopy(IFA_IN6(ifa), &ip6->ip6_src,
909                             sizeof(struct in6_addr));
910                         ifa_free(ifa);
911                 } else
912                         /* This should never happen with IPv6. */
913                         bzero(&ip6->ip6_src, sizeof(struct in6_addr));
914
915                 /* Set the multicast destination. */
916                 ip6->ip6_dst.s6_addr16[0] = htons(0xff02);
917                 ip6->ip6_dst.s6_addr8[15] = 0x12;
918                 if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) {
919                         m_freem(m);
920                         CARP_DEBUG("%s: in6_setscope failed\n", __func__);
921                         goto resched;
922                 }
923
924                 ch_ptr = (struct carp_header *)(&ip6[1]);
925                 bcopy(&ch, ch_ptr, sizeof(ch));
926                 if (carp_prepare_ad(m, sc, ch_ptr))
927                         goto resched;
928
929                 m->m_data += sizeof(*ip6);
930                 ch_ptr->carp_cksum = in_cksum(m, len - sizeof(*ip6));
931                 m->m_data -= sizeof(*ip6);
932
933                 CARPSTATS_INC(carps_opackets6);
934
935                 carp_send_ad_error(sc, ip6_output(m, NULL, NULL, 0,
936                     &sc->sc_carpdev->if_carp->cif_im6o, NULL, NULL));
937         }
938 #endif /* INET6 */
939
940 resched:
941         callout_reset(&sc->sc_ad_tmo, tvtohz(&tv), carp_send_ad, sc);
942 }
943
944 static void
945 carp_addroute(struct carp_softc *sc)
946 {
947         struct ifaddr *ifa;
948
949         CARP_FOREACH_IFA(sc, ifa)
950                 carp_ifa_addroute(ifa);
951 }
952
953 static void
954 carp_ifa_addroute(struct ifaddr *ifa)
955 {
956
957         switch (ifa->ifa_addr->sa_family) {
958 #ifdef INET
959         case AF_INET:
960                 in_addprefix(ifatoia(ifa), RTF_UP);
961                 ifa_add_loopback_route(ifa,
962                     (struct sockaddr *)&ifatoia(ifa)->ia_addr);
963                 break;
964 #endif
965 #ifdef INET6
966         case AF_INET6:
967                 ifa_add_loopback_route(ifa,
968                     (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
969                 nd6_add_ifa_lle(ifatoia6(ifa));
970                 break;
971 #endif
972         }
973 }
974
975 static void
976 carp_delroute(struct carp_softc *sc)
977 {
978         struct ifaddr *ifa;
979
980         CARP_FOREACH_IFA(sc, ifa)
981                 carp_ifa_delroute(ifa);
982 }
983
984 static void
985 carp_ifa_delroute(struct ifaddr *ifa)
986 {
987
988         switch (ifa->ifa_addr->sa_family) {
989 #ifdef INET
990         case AF_INET:
991                 ifa_del_loopback_route(ifa,
992                     (struct sockaddr *)&ifatoia(ifa)->ia_addr);
993                 in_scrubprefix(ifatoia(ifa), LLE_STATIC);
994                 break;
995 #endif
996 #ifdef INET6
997         case AF_INET6:
998                 ifa_del_loopback_route(ifa,
999                     (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
1000                 nd6_rem_ifa_lle(ifatoia6(ifa));
1001                 break;
1002 #endif
1003         }
1004 }
1005
1006 int
1007 carp_master(struct ifaddr *ifa)
1008 {
1009         struct carp_softc *sc = ifa->ifa_carp;
1010
1011         return (sc->sc_state == MASTER);
1012 }
1013
1014 #ifdef INET
1015 /*
1016  * Broadcast a gratuitous ARP request containing
1017  * the virtual router MAC address for each IP address
1018  * associated with the virtual router.
1019  */
1020 static void
1021 carp_send_arp(struct carp_softc *sc)
1022 {
1023         struct ifaddr *ifa;
1024
1025         CARP_FOREACH_IFA(sc, ifa)
1026                 if (ifa->ifa_addr->sa_family == AF_INET)
1027                         arp_ifinit2(sc->sc_carpdev, ifa, LLADDR(&sc->sc_addr));
1028 }
1029
1030 int
1031 carp_iamatch(struct ifaddr *ifa, uint8_t **enaddr)
1032 {
1033         struct carp_softc *sc = ifa->ifa_carp;
1034
1035         if (sc->sc_state == MASTER) {
1036                 *enaddr = LLADDR(&sc->sc_addr);
1037                 return (1);
1038         }
1039
1040         return (0);
1041 }
1042 #endif
1043
1044 #ifdef INET6
1045 static void
1046 carp_send_na(struct carp_softc *sc)
1047 {
1048         static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1049         struct ifaddr *ifa;
1050         struct in6_addr *in6;
1051
1052         CARP_FOREACH_IFA(sc, ifa) {
1053                 if (ifa->ifa_addr->sa_family != AF_INET6)
1054                         continue;
1055
1056                 in6 = IFA_IN6(ifa);
1057                 nd6_na_output(sc->sc_carpdev, &mcast, in6,
1058                     ND_NA_FLAG_OVERRIDE, 1, NULL);
1059                 DELAY(1000);    /* XXX */
1060         }
1061 }
1062
1063 /*
1064  * Returns ifa in case it's a carp address and it is MASTER, or if the address
1065  * matches and is not a carp address.  Returns NULL otherwise.
1066  */
1067 struct ifaddr *
1068 carp_iamatch6(struct ifnet *ifp, struct in6_addr *taddr)
1069 {
1070         struct ifaddr *ifa;
1071
1072         ifa = NULL;
1073         IF_ADDR_RLOCK(ifp);
1074         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1075                 if (ifa->ifa_addr->sa_family != AF_INET6)
1076                         continue;
1077                 if (!IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa)))
1078                         continue;
1079                 if (ifa->ifa_carp && ifa->ifa_carp->sc_state != MASTER)
1080                         ifa = NULL;
1081                 else
1082                         ifa_ref(ifa);
1083                 break;
1084         }
1085         IF_ADDR_RUNLOCK(ifp);
1086
1087         return (ifa);
1088 }
1089
1090 caddr_t
1091 carp_macmatch6(struct ifnet *ifp, struct mbuf *m, const struct in6_addr *taddr)
1092 {
1093         struct ifaddr *ifa;
1094
1095         IF_ADDR_RLOCK(ifp);
1096         IFNET_FOREACH_IFA(ifp, ifa)
1097                 if (ifa->ifa_addr->sa_family == AF_INET6 &&
1098                     IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa))) {
1099                         struct carp_softc *sc = ifa->ifa_carp;
1100                         struct m_tag *mtag;
1101
1102                         IF_ADDR_RUNLOCK(ifp);
1103
1104                         mtag = m_tag_get(PACKET_TAG_CARP,
1105                             sizeof(struct carp_softc *), M_NOWAIT);
1106                         if (mtag == NULL)
1107                                 /* Better a bit than nothing. */
1108                                 return (LLADDR(&sc->sc_addr));
1109
1110                         bcopy(&sc, mtag + 1, sizeof(sc));
1111                         m_tag_prepend(m, mtag);
1112
1113                         return (LLADDR(&sc->sc_addr));
1114                 }
1115         IF_ADDR_RUNLOCK(ifp);
1116
1117         return (NULL);
1118 }
1119 #endif /* INET6 */
1120
1121 int
1122 carp_forus(struct ifnet *ifp, u_char *dhost)
1123 {
1124         struct carp_softc *sc;
1125         uint8_t *ena = dhost;
1126
1127         if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1128                 return (0);
1129
1130         CIF_LOCK(ifp->if_carp);
1131         IFNET_FOREACH_CARP(ifp, sc) {
1132                 CARP_LOCK(sc);
1133                 if (sc->sc_state == MASTER && !bcmp(dhost, LLADDR(&sc->sc_addr),
1134                     ETHER_ADDR_LEN)) {
1135                         CARP_UNLOCK(sc);
1136                         CIF_UNLOCK(ifp->if_carp);
1137                         return (1);
1138                 }
1139                 CARP_UNLOCK(sc);
1140         }
1141         CIF_UNLOCK(ifp->if_carp);
1142
1143         return (0);
1144 }
1145
1146 /* Master down timeout event, executed in callout context. */
1147 static void
1148 carp_master_down(void *v)
1149 {
1150         struct carp_softc *sc = v;
1151
1152         CARP_LOCK_ASSERT(sc);
1153
1154         CURVNET_SET(sc->sc_carpdev->if_vnet);
1155         if (sc->sc_state == BACKUP) {
1156                 CARP_LOG("VHID %u@%s: BACKUP -> MASTER (master down)\n",
1157                     sc->sc_vhid,
1158                     sc->sc_carpdev->if_xname);
1159                 carp_master_down_locked(sc);
1160         }
1161         CURVNET_RESTORE();
1162
1163         CARP_UNLOCK(sc);
1164 }
1165
1166 static void
1167 carp_master_down_locked(struct carp_softc *sc)
1168 {
1169
1170         CARP_LOCK_ASSERT(sc);
1171
1172         switch (sc->sc_state) {
1173         case BACKUP:
1174                 carp_set_state(sc, MASTER);
1175                 carp_send_ad_locked(sc);
1176 #ifdef INET
1177                 carp_send_arp(sc);
1178 #endif
1179 #ifdef INET6
1180                 carp_send_na(sc);
1181 #endif
1182                 carp_setrun(sc, 0);
1183                 carp_addroute(sc);
1184                 break;
1185         case INIT:
1186         case MASTER:
1187 #ifdef INVARIANTS
1188                 panic("carp: VHID %u@%s: master_down event in %s state\n",
1189                     sc->sc_vhid,
1190                     sc->sc_carpdev->if_xname,
1191                     sc->sc_state ? "MASTER" : "INIT");
1192 #endif
1193                 break;
1194         }
1195 }
1196
1197 /*
1198  * When in backup state, af indicates whether to reset the master down timer
1199  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1200  */
1201 static void
1202 carp_setrun(struct carp_softc *sc, sa_family_t af)
1203 {
1204         struct timeval tv;
1205
1206         CARP_LOCK_ASSERT(sc);
1207
1208         if ((sc->sc_carpdev->if_flags & IFF_UP) == 0 ||
1209             sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1210             (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0))
1211                 return;
1212
1213         switch (sc->sc_state) {
1214         case INIT:
1215                 CARP_LOG("VHID %u@%s: INIT -> BACKUP\n",
1216                     sc->sc_vhid,
1217                     sc->sc_carpdev->if_xname);
1218                 carp_set_state(sc, BACKUP);
1219                 carp_setrun(sc, 0);
1220                 break;
1221         case BACKUP:
1222                 callout_stop(&sc->sc_ad_tmo);
1223                 tv.tv_sec = 3 * sc->sc_advbase;
1224                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1225                 switch (af) {
1226 #ifdef INET
1227                 case AF_INET:
1228                         callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1229                             carp_master_down, sc);
1230                         break;
1231 #endif
1232 #ifdef INET6
1233                 case AF_INET6:
1234                         callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1235                             carp_master_down, sc);
1236                         break;
1237 #endif
1238                 default:
1239 #ifdef INET
1240                         if (sc->sc_naddrs)
1241                                 callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1242                                     carp_master_down, sc);
1243 #endif
1244 #ifdef INET6
1245                         if (sc->sc_naddrs6)
1246                                 callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1247                                     carp_master_down, sc);
1248 #endif
1249                         break;
1250                 }
1251                 break;
1252         case MASTER:
1253                 tv.tv_sec = sc->sc_advbase;
1254                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1255                 callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1256                     carp_send_ad, sc);
1257                 break;
1258         }
1259 }
1260
1261 /*
1262  * Setup multicast structures.
1263  */
1264 static int
1265 carp_multicast_setup(struct carp_if *cif, sa_family_t sa)
1266 {
1267         struct ifnet *ifp = cif->cif_ifp;
1268         int error = 0;
1269
1270         CIF_LOCK_ASSERT(cif);
1271
1272         switch (sa) {
1273 #ifdef INET
1274         case AF_INET:
1275             {
1276                 struct ip_moptions *imo = &cif->cif_imo;
1277                 struct in_addr addr;
1278
1279                 if (imo->imo_membership)
1280                         return (0);
1281
1282                 imo->imo_membership = (struct in_multi **)malloc(
1283                     (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_CARP,
1284                     M_NOWAIT);
1285                 if (imo->imo_membership == NULL)
1286                         return (ENOMEM);
1287                 imo->imo_mfilters = NULL;
1288                 imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1289                 imo->imo_multicast_vif = -1;
1290
1291                 addr.s_addr = htonl(INADDR_CARP_GROUP);
1292                 if ((error = in_joingroup(ifp, &addr, NULL,
1293                     &imo->imo_membership[0])) != 0) {
1294                         free(imo->imo_membership, M_CARP);
1295                         break;
1296                 }
1297                 imo->imo_num_memberships++;
1298                 imo->imo_multicast_ifp = ifp;
1299                 imo->imo_multicast_ttl = CARP_DFLTTL;
1300                 imo->imo_multicast_loop = 0;
1301                 break;
1302            }
1303 #endif
1304 #ifdef INET6
1305         case AF_INET6:
1306             {
1307                 struct ip6_moptions *im6o = &cif->cif_im6o;
1308                 struct in6_addr in6;
1309                 struct in6_multi *in6m;
1310
1311                 if (im6o->im6o_membership)
1312                         return (0);
1313
1314                 im6o->im6o_membership = (struct in6_multi **)malloc(
1315                     (sizeof(struct in6_multi *) * IPV6_MIN_MEMBERSHIPS), M_CARP,
1316                     M_ZERO | M_NOWAIT);
1317                 if (im6o->im6o_membership == NULL)
1318                         return (ENOMEM);
1319                 im6o->im6o_mfilters = NULL;
1320                 im6o->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
1321                 im6o->im6o_multicast_hlim = CARP_DFLTTL;
1322                 im6o->im6o_multicast_ifp = ifp;
1323
1324                 /* Join IPv6 CARP multicast group. */
1325                 bzero(&in6, sizeof(in6));
1326                 in6.s6_addr16[0] = htons(0xff02);
1327                 in6.s6_addr8[15] = 0x12;
1328                 if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1329                         free(im6o->im6o_membership, M_CARP);
1330                         break;
1331                 }
1332                 in6m = NULL;
1333                 if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1334                         free(im6o->im6o_membership, M_CARP);
1335                         break;
1336                 }
1337                 im6o->im6o_membership[0] = in6m;
1338                 im6o->im6o_num_memberships++;
1339
1340                 /* Join solicited multicast address. */
1341                 bzero(&in6, sizeof(in6));
1342                 in6.s6_addr16[0] = htons(0xff02);
1343                 in6.s6_addr32[1] = 0;
1344                 in6.s6_addr32[2] = htonl(1);
1345                 in6.s6_addr32[3] = 0;
1346                 in6.s6_addr8[12] = 0xff;
1347                 if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1348                         in6_mc_leave(im6o->im6o_membership[0], NULL);
1349                         free(im6o->im6o_membership, M_CARP);
1350                         break;
1351                 }
1352                 in6m = NULL;
1353                 if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1354                         in6_mc_leave(im6o->im6o_membership[0], NULL);
1355                         free(im6o->im6o_membership, M_CARP);
1356                         break;
1357                 }
1358                 im6o->im6o_membership[1] = in6m;
1359                 im6o->im6o_num_memberships++;
1360                 break;
1361             }
1362 #endif
1363         }
1364
1365         return (error);
1366 }
1367
1368 /*
1369  * Free multicast structures.
1370  */
1371 static void
1372 carp_multicast_cleanup(struct carp_if *cif, sa_family_t sa)
1373 {
1374
1375         CIF_LOCK_ASSERT(cif);
1376         switch (sa) {
1377 #ifdef INET
1378         case AF_INET:
1379                 if (cif->cif_naddrs == 0) {
1380                         struct ip_moptions *imo = &cif->cif_imo;
1381
1382                         in_leavegroup(imo->imo_membership[0], NULL);
1383                         KASSERT(imo->imo_mfilters == NULL,
1384                             ("%s: imo_mfilters != NULL", __func__));
1385                         free(imo->imo_membership, M_CARP);
1386                         imo->imo_membership = NULL;
1387
1388                 }
1389                 break;
1390 #endif
1391 #ifdef INET6
1392         case AF_INET6:
1393                 if (cif->cif_naddrs6 == 0) {
1394                         struct ip6_moptions *im6o = &cif->cif_im6o;
1395
1396                         in6_mc_leave(im6o->im6o_membership[0], NULL);
1397                         in6_mc_leave(im6o->im6o_membership[1], NULL);
1398                         KASSERT(im6o->im6o_mfilters == NULL,
1399                             ("%s: im6o_mfilters != NULL", __func__));
1400                         free(im6o->im6o_membership, M_CARP);
1401                         im6o->im6o_membership = NULL;
1402                 }
1403                 break;
1404 #endif
1405         }
1406 }
1407
1408 int
1409 carp_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *sa)
1410 {
1411         struct m_tag *mtag;
1412         struct carp_softc *sc;
1413
1414         if (!sa)
1415                 return (0);
1416
1417         switch (sa->sa_family) {
1418 #ifdef INET
1419         case AF_INET:
1420                 break;
1421 #endif
1422 #ifdef INET6
1423         case AF_INET6:
1424                 break;
1425 #endif
1426         default:
1427                 return (0);
1428         }
1429
1430         mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
1431         if (mtag == NULL)
1432                 return (0);
1433
1434         bcopy(mtag + 1, &sc, sizeof(sc));
1435
1436         /* Set the source MAC address to the Virtual Router MAC Address. */
1437         switch (ifp->if_type) {
1438         case IFT_ETHER:
1439         case IFT_BRIDGE:
1440         case IFT_L2VLAN: {
1441                         struct ether_header *eh;
1442
1443                         eh = mtod(m, struct ether_header *);
1444                         eh->ether_shost[0] = 0;
1445                         eh->ether_shost[1] = 0;
1446                         eh->ether_shost[2] = 0x5e;
1447                         eh->ether_shost[3] = 0;
1448                         eh->ether_shost[4] = 1;
1449                         eh->ether_shost[5] = sc->sc_vhid;
1450                 }
1451                 break;
1452         case IFT_FDDI: {
1453                         struct fddi_header *fh;
1454
1455                         fh = mtod(m, struct fddi_header *);
1456                         fh->fddi_shost[0] = 0;
1457                         fh->fddi_shost[1] = 0;
1458                         fh->fddi_shost[2] = 0x5e;
1459                         fh->fddi_shost[3] = 0;
1460                         fh->fddi_shost[4] = 1;
1461                         fh->fddi_shost[5] = sc->sc_vhid;
1462                 }
1463                 break;
1464         case IFT_ISO88025: {
1465                         struct iso88025_header *th;
1466                         th = mtod(m, struct iso88025_header *);
1467                         th->iso88025_shost[0] = 3;
1468                         th->iso88025_shost[1] = 0;
1469                         th->iso88025_shost[2] = 0x40 >> (sc->sc_vhid - 1);
1470                         th->iso88025_shost[3] = 0x40000 >> (sc->sc_vhid - 1);
1471                         th->iso88025_shost[4] = 0;
1472                         th->iso88025_shost[5] = 0;
1473                 }
1474                 break;
1475         default:
1476                 printf("%s: carp is not supported for the %d interface type\n",
1477                     ifp->if_xname, ifp->if_type);
1478                 return (EOPNOTSUPP);
1479         }
1480
1481         return (0);
1482 }
1483
1484 static struct carp_softc*
1485 carp_alloc(struct ifnet *ifp)
1486 {
1487         struct carp_softc *sc;
1488         struct carp_if *cif;
1489
1490         if ((cif = ifp->if_carp) == NULL)
1491                 cif = carp_alloc_if(ifp);
1492
1493         sc = malloc(sizeof(*sc), M_CARP, M_WAITOK|M_ZERO);
1494
1495         sc->sc_advbase = CARP_DFLTINTV;
1496         sc->sc_vhid = -1;       /* required setting */
1497         sc->sc_init_counter = 1;
1498         sc->sc_state = INIT;
1499
1500         sc->sc_ifasiz = sizeof(struct ifaddr *);
1501         sc->sc_ifas = malloc(sc->sc_ifasiz, M_CARP, M_WAITOK|M_ZERO);
1502         sc->sc_carpdev = ifp;
1503
1504         CARP_LOCK_INIT(sc);
1505 #ifdef INET
1506         callout_init_mtx(&sc->sc_md_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1507 #endif
1508 #ifdef INET6
1509         callout_init_mtx(&sc->sc_md6_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1510 #endif
1511         callout_init_mtx(&sc->sc_ad_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1512
1513         CIF_LOCK(cif);
1514         TAILQ_INSERT_TAIL(&cif->cif_vrs, sc, sc_list);
1515         CIF_UNLOCK(cif);
1516
1517         mtx_lock(&carp_mtx);
1518         LIST_INSERT_HEAD(&carp_list, sc, sc_next);
1519         mtx_unlock(&carp_mtx);
1520
1521         return (sc);
1522 }
1523
1524 static int
1525 carp_grow_ifas(struct carp_softc *sc)
1526 {
1527         struct ifaddr **new;
1528
1529         CARP_LOCK_ASSERT(sc);
1530
1531         new = malloc(sc->sc_ifasiz * 2, M_CARP, M_NOWAIT|M_ZERO);
1532         if (new == NULL)
1533                 return (ENOMEM);
1534         bcopy(sc->sc_ifas, new, sc->sc_ifasiz);
1535         free(sc->sc_ifas, M_CARP);
1536         sc->sc_ifas = new;
1537         sc->sc_ifasiz *= 2;
1538
1539         return (0);
1540 }
1541
1542 static void
1543 carp_destroy(struct carp_softc *sc)
1544 {
1545         struct ifnet *ifp = sc->sc_carpdev;
1546         struct carp_if *cif = ifp->if_carp;
1547
1548         CIF_LOCK_ASSERT(cif);
1549
1550         TAILQ_REMOVE(&cif->cif_vrs, sc, sc_list);
1551
1552         mtx_lock(&carp_mtx);
1553         LIST_REMOVE(sc, sc_next);
1554         mtx_unlock(&carp_mtx);
1555
1556         CARP_LOCK(sc);
1557         if (sc->sc_suppress)
1558                 carp_demote_adj(-V_carp_ifdown_adj, "vhid removed");
1559         callout_drain(&sc->sc_ad_tmo);
1560 #ifdef INET
1561         callout_drain(&sc->sc_md_tmo);
1562 #endif
1563 #ifdef INET6
1564         callout_drain(&sc->sc_md6_tmo);
1565 #endif
1566         CARP_LOCK_DESTROY(sc);
1567
1568         free(sc->sc_ifas, M_CARP);
1569         free(sc, M_CARP);
1570 }
1571
1572 static struct carp_if*
1573 carp_alloc_if(struct ifnet *ifp)
1574 {
1575         struct carp_if *cif;
1576         int error;
1577
1578         cif = malloc(sizeof(*cif), M_CARP, M_WAITOK|M_ZERO);
1579
1580         if ((error = ifpromisc(ifp, 1)) != 0)
1581                 printf("%s: ifpromisc(%s) failed: %d\n",
1582                     __func__, ifp->if_xname, error);
1583         else
1584                 cif->cif_flags |= CIF_PROMISC;
1585
1586         CIF_LOCK_INIT(cif);
1587         cif->cif_ifp = ifp;
1588         TAILQ_INIT(&cif->cif_vrs);
1589
1590         IF_ADDR_WLOCK(ifp);
1591         ifp->if_carp = cif;
1592         if_ref(ifp);
1593         IF_ADDR_WUNLOCK(ifp);
1594
1595         return (cif);
1596 }
1597
1598 static void
1599 carp_free_if(struct carp_if *cif)
1600 {
1601         struct ifnet *ifp = cif->cif_ifp;
1602
1603         CIF_LOCK_ASSERT(cif);
1604         KASSERT(TAILQ_EMPTY(&cif->cif_vrs), ("%s: softc list not empty",
1605             __func__));
1606
1607         IF_ADDR_WLOCK(ifp);
1608         ifp->if_carp = NULL;
1609         IF_ADDR_WUNLOCK(ifp);
1610
1611         CIF_LOCK_DESTROY(cif);
1612
1613         if (cif->cif_flags & CIF_PROMISC)
1614                 ifpromisc(ifp, 0);
1615         if_rele(ifp);
1616
1617         free(cif, M_CARP);
1618 }
1619
1620 static void
1621 carp_carprcp(struct carpreq *carpr, struct carp_softc *sc, int priv)
1622 {
1623
1624         CARP_LOCK(sc);
1625         carpr->carpr_state = sc->sc_state;
1626         carpr->carpr_vhid = sc->sc_vhid;
1627         carpr->carpr_advbase = sc->sc_advbase;
1628         carpr->carpr_advskew = sc->sc_advskew;
1629         if (priv)
1630                 bcopy(sc->sc_key, carpr->carpr_key, sizeof(carpr->carpr_key));
1631         else
1632                 bzero(carpr->carpr_key, sizeof(carpr->carpr_key));
1633         CARP_UNLOCK(sc);
1634 }
1635
1636 int
1637 carp_ioctl(struct ifreq *ifr, u_long cmd, struct thread *td)
1638 {
1639         struct carpreq carpr;
1640         struct ifnet *ifp;
1641         struct carp_softc *sc = NULL;
1642         int error = 0, locked = 0;
1643
1644         if ((error = copyin(ifr->ifr_data, &carpr, sizeof carpr)))
1645                 return (error);
1646
1647         ifp = ifunit_ref(ifr->ifr_name);
1648         if (ifp == NULL)
1649                 return (ENXIO);
1650
1651         switch (ifp->if_type) {
1652         case IFT_ETHER:
1653         case IFT_L2VLAN:
1654         case IFT_BRIDGE:
1655         case IFT_FDDI:
1656         case IFT_ISO88025:
1657                 break;
1658         default:
1659                 error = EOPNOTSUPP;
1660                 goto out;
1661         }
1662
1663         if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1664                 error = EADDRNOTAVAIL;
1665                 goto out;
1666         }
1667
1668         switch (cmd) {
1669         case SIOCSVH:
1670                 if ((error = priv_check(td, PRIV_NETINET_CARP)))
1671                         break;
1672                 if (carpr.carpr_vhid <= 0 || carpr.carpr_vhid > CARP_MAXVHID ||
1673                     carpr.carpr_advbase < 0 || carpr.carpr_advskew < 0) {
1674                         error = EINVAL;
1675                         break;
1676                 }
1677
1678                 if (ifp->if_carp) {
1679                         CIF_LOCK(ifp->if_carp);
1680                         IFNET_FOREACH_CARP(ifp, sc)
1681                                 if (sc->sc_vhid == carpr.carpr_vhid)
1682                                         break;
1683                         CIF_UNLOCK(ifp->if_carp);
1684                 }
1685                 if (sc == NULL) {
1686                         sc = carp_alloc(ifp);
1687                         CARP_LOCK(sc);
1688                         sc->sc_vhid = carpr.carpr_vhid;
1689                         LLADDR(&sc->sc_addr)[0] = 0;
1690                         LLADDR(&sc->sc_addr)[1] = 0;
1691                         LLADDR(&sc->sc_addr)[2] = 0x5e;
1692                         LLADDR(&sc->sc_addr)[3] = 0;
1693                         LLADDR(&sc->sc_addr)[4] = 1;
1694                         LLADDR(&sc->sc_addr)[5] = sc->sc_vhid;
1695                 } else
1696                         CARP_LOCK(sc);
1697                 locked = 1;
1698                 if (carpr.carpr_advbase > 0) {
1699                         if (carpr.carpr_advbase > 255 ||
1700                             carpr.carpr_advbase < CARP_DFLTINTV) {
1701                                 error = EINVAL;
1702                                 break;
1703                         }
1704                         sc->sc_advbase = carpr.carpr_advbase;
1705                 }
1706                 if (carpr.carpr_advskew > 0) {
1707                         if (carpr.carpr_advskew >= 255) {
1708                                 error = EINVAL;
1709                                 break;
1710                         }
1711                         sc->sc_advskew = carpr.carpr_advskew;
1712                 }
1713                 if (carpr.carpr_key[0] != '\0') {
1714                         bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1715                         carp_hmac_prepare(sc);
1716                 }
1717                 if (sc->sc_state != INIT &&
1718                     carpr.carpr_state != sc->sc_state) {
1719                         switch (carpr.carpr_state) {
1720                         case BACKUP:
1721                                 callout_stop(&sc->sc_ad_tmo);
1722                                 carp_set_state(sc, BACKUP);
1723                                 carp_setrun(sc, 0);
1724                                 carp_delroute(sc);
1725                                 break;
1726                         case MASTER:
1727                                 carp_master_down_locked(sc);
1728                                 break;
1729                         default:
1730                                 break;
1731                         }
1732                 }
1733                 break;
1734
1735         case SIOCGVH:
1736             {
1737                 int priveleged;
1738
1739                 if (carpr.carpr_vhid < 0 || carpr.carpr_vhid > CARP_MAXVHID) {
1740                         error = EINVAL;
1741                         break;
1742                 }
1743                 if (carpr.carpr_count < 1) {
1744                         error = EMSGSIZE;
1745                         break;
1746                 }
1747                 if (ifp->if_carp == NULL) {
1748                         error = ENOENT;
1749                         break;
1750                 }
1751
1752                 priveleged = (priv_check(td, PRIV_NETINET_CARP) == 0);
1753                 if (carpr.carpr_vhid != 0) {
1754                         CIF_LOCK(ifp->if_carp);
1755                         IFNET_FOREACH_CARP(ifp, sc)
1756                                 if (sc->sc_vhid == carpr.carpr_vhid)
1757                                         break;
1758                         CIF_UNLOCK(ifp->if_carp);
1759                         if (sc == NULL) {
1760                                 error = ENOENT;
1761                                 break;
1762                         }
1763                         carp_carprcp(&carpr, sc, priveleged);
1764                         error = copyout(&carpr, ifr->ifr_data, sizeof(carpr));
1765                 } else  {
1766                         int i, count;
1767
1768                         count = 0;
1769                         CIF_LOCK(ifp->if_carp);
1770                         IFNET_FOREACH_CARP(ifp, sc)
1771                                 count++;
1772
1773                         if (count > carpr.carpr_count) {
1774                                 CIF_UNLOCK(ifp->if_carp);
1775                                 error = EMSGSIZE;
1776                                 break;
1777                         }
1778
1779                         i = 0;
1780                         IFNET_FOREACH_CARP(ifp, sc) {
1781                                 carp_carprcp(&carpr, sc, priveleged);
1782                                 carpr.carpr_count = count;
1783                                 error = copyout(&carpr, ifr->ifr_data +
1784                                     (i * sizeof(carpr)), sizeof(carpr));
1785                                 if (error) {
1786                                         CIF_UNLOCK(ifp->if_carp);
1787                                         break;
1788                                 }
1789                                 i++;
1790                         }
1791                         CIF_UNLOCK(ifp->if_carp);
1792                 }
1793                 break;
1794             }
1795         default:
1796                 error = EINVAL;
1797         }
1798
1799 out:
1800         if (locked)
1801                 CARP_UNLOCK(sc);
1802         if_rele(ifp);
1803
1804         return (error);
1805 }
1806
1807 static int
1808 carp_get_vhid(struct ifaddr *ifa)
1809 {
1810
1811         if (ifa == NULL || ifa->ifa_carp == NULL)
1812                 return (0);
1813
1814         return (ifa->ifa_carp->sc_vhid);
1815 }
1816
1817 int
1818 carp_attach(struct ifaddr *ifa, int vhid)
1819 {
1820         struct ifnet *ifp = ifa->ifa_ifp;
1821         struct carp_if *cif = ifp->if_carp;
1822         struct carp_softc *sc;
1823         int index, error;
1824
1825         if (ifp->if_carp == NULL)
1826                 return (ENOPROTOOPT);
1827
1828         switch (ifa->ifa_addr->sa_family) {
1829 #ifdef INET
1830         case AF_INET:
1831 #endif
1832 #ifdef INET6
1833         case AF_INET6:
1834 #endif
1835                 break;
1836         default:
1837                 return (EPROTOTYPE);
1838         }
1839
1840         CIF_LOCK(cif);
1841         IFNET_FOREACH_CARP(ifp, sc)
1842                 if (sc->sc_vhid == vhid)
1843                         break;
1844         if (sc == NULL) {
1845                 CIF_UNLOCK(cif);
1846                 return (ENOENT);
1847         }
1848
1849         if (ifa->ifa_carp) {
1850                 if (ifa->ifa_carp->sc_vhid != vhid)
1851                         carp_detach_locked(ifa);
1852                 else {
1853                         CIF_UNLOCK(cif);
1854                         return (0);
1855                 }
1856         }
1857
1858         error = carp_multicast_setup(cif, ifa->ifa_addr->sa_family);
1859         if (error) {
1860                 CIF_FREE(cif);
1861                 return (error);
1862         }
1863
1864         CARP_LOCK(sc);
1865         index = sc->sc_naddrs + sc->sc_naddrs6 + 1;
1866         if (index > sc->sc_ifasiz / sizeof(struct ifaddr *))
1867                 if ((error = carp_grow_ifas(sc)) != 0) {
1868                         carp_multicast_cleanup(cif,
1869                             ifa->ifa_addr->sa_family);
1870                         CARP_UNLOCK(sc);
1871                         CIF_FREE(cif);
1872                         return (error);
1873                 }
1874
1875         switch (ifa->ifa_addr->sa_family) {
1876 #ifdef INET
1877         case AF_INET:
1878                 cif->cif_naddrs++;
1879                 sc->sc_naddrs++;
1880                 break;
1881 #endif
1882 #ifdef INET6
1883         case AF_INET6:
1884                 cif->cif_naddrs6++;
1885                 sc->sc_naddrs6++;
1886                 break;
1887 #endif
1888         }
1889
1890         ifa_ref(ifa);
1891         sc->sc_ifas[index - 1] = ifa;
1892         ifa->ifa_carp = sc;
1893
1894         carp_hmac_prepare(sc);
1895         carp_sc_state(sc);
1896
1897         CARP_UNLOCK(sc);
1898         CIF_UNLOCK(cif);
1899
1900         return (0);
1901 }
1902
1903 void
1904 carp_detach(struct ifaddr *ifa)
1905 {
1906         struct ifnet *ifp = ifa->ifa_ifp;
1907         struct carp_if *cif = ifp->if_carp;
1908
1909         CIF_LOCK(cif);
1910         carp_detach_locked(ifa);
1911         CIF_FREE(cif);
1912 }
1913
1914 static void
1915 carp_detach_locked(struct ifaddr *ifa)
1916 {
1917         struct ifnet *ifp = ifa->ifa_ifp;
1918         struct carp_if *cif = ifp->if_carp;
1919         struct carp_softc *sc = ifa->ifa_carp;
1920         int i, index;
1921
1922         KASSERT(sc != NULL, ("%s: %p not attached", __func__, ifa));
1923
1924         CIF_LOCK_ASSERT(cif);
1925         CARP_LOCK(sc);
1926
1927         /* Shift array. */
1928         index = sc->sc_naddrs + sc->sc_naddrs6;
1929         for (i = 0; i < index; i++)
1930                 if (sc->sc_ifas[i] == ifa)
1931                         break;
1932         KASSERT(i < index, ("%s: %p no backref", __func__, ifa));
1933         for (; i < index - 1; i++)
1934                 sc->sc_ifas[i] = sc->sc_ifas[i+1];
1935         sc->sc_ifas[index - 1] = NULL;
1936
1937         switch (ifa->ifa_addr->sa_family) {
1938 #ifdef INET
1939         case AF_INET:
1940                 cif->cif_naddrs--;
1941                 sc->sc_naddrs--;
1942                 break;
1943 #endif
1944 #ifdef INET6
1945         case AF_INET6:
1946                 cif->cif_naddrs6--;
1947                 sc->sc_naddrs6--;
1948                 break;
1949 #endif
1950         }
1951
1952         carp_ifa_delroute(ifa);
1953         carp_multicast_cleanup(cif, ifa->ifa_addr->sa_family);
1954
1955         ifa->ifa_carp = NULL;
1956         ifa_free(ifa);
1957
1958         carp_hmac_prepare(sc);
1959         carp_sc_state(sc);
1960
1961         if (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0) {
1962                 CARP_UNLOCK(sc);
1963                 carp_destroy(sc);
1964         } else
1965                 CARP_UNLOCK(sc);
1966 }
1967
1968 static void
1969 carp_set_state(struct carp_softc *sc, int state)
1970 {
1971
1972         CARP_LOCK_ASSERT(sc);
1973
1974         if (sc->sc_state != state) {
1975                 const char *carp_states[] = { CARP_STATES };
1976                 char subsys[IFNAMSIZ+5];
1977
1978                 sc->sc_state = state;
1979
1980                 snprintf(subsys, IFNAMSIZ+5, "%u@%s", sc->sc_vhid,
1981                     sc->sc_carpdev->if_xname);
1982                 devctl_notify("CARP", subsys, carp_states[state], NULL);
1983         }
1984 }
1985
1986 static void
1987 carp_linkstate(struct ifnet *ifp)
1988 {
1989         struct carp_softc *sc;
1990
1991         CIF_LOCK(ifp->if_carp);
1992         IFNET_FOREACH_CARP(ifp, sc) {
1993                 CARP_LOCK(sc);
1994                 carp_sc_state(sc);
1995                 CARP_UNLOCK(sc);
1996         }
1997         CIF_UNLOCK(ifp->if_carp);
1998 }
1999
2000 static void
2001 carp_sc_state(struct carp_softc *sc)
2002 {
2003
2004         CARP_LOCK_ASSERT(sc);
2005
2006         if (sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
2007             !(sc->sc_carpdev->if_flags & IFF_UP)) {
2008                 callout_stop(&sc->sc_ad_tmo);
2009 #ifdef INET
2010                 callout_stop(&sc->sc_md_tmo);
2011 #endif
2012 #ifdef INET6
2013                 callout_stop(&sc->sc_md6_tmo);
2014 #endif
2015                 carp_set_state(sc, INIT);
2016                 carp_setrun(sc, 0);
2017                 if (!sc->sc_suppress)
2018                         carp_demote_adj(V_carp_ifdown_adj, "interface down");
2019                 sc->sc_suppress = 1;
2020         } else {
2021                 carp_set_state(sc, INIT);
2022                 carp_setrun(sc, 0);
2023                 if (sc->sc_suppress)
2024                         carp_demote_adj(-V_carp_ifdown_adj, "interface up");
2025                 sc->sc_suppress = 0;
2026         }
2027 }
2028
2029 static void
2030 carp_demote_adj(int adj, char *reason)
2031 {
2032         atomic_add_int(&V_carp_demotion, adj);
2033         CARP_LOG("demoted by %d to %d (%s)\n", adj, V_carp_demotion, reason);
2034         taskqueue_enqueue(taskqueue_swi, &carp_sendall_task);
2035 }
2036
2037 static int
2038 carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS)
2039 {
2040         int new, error;
2041
2042         new = V_carp_demotion;
2043         error = sysctl_handle_int(oidp, &new, 0, req);
2044         if (error || !req->newptr)
2045                 return (error);
2046
2047         carp_demote_adj(new, "sysctl");
2048
2049         return (0);
2050 }
2051
2052 #ifdef INET
2053 extern  struct domain inetdomain;
2054 static struct protosw in_carp_protosw = {
2055         .pr_type =              SOCK_RAW,
2056         .pr_domain =            &inetdomain,
2057         .pr_protocol =          IPPROTO_CARP,
2058         .pr_flags =             PR_ATOMIC|PR_ADDR,
2059         .pr_input =             carp_input,
2060         .pr_output =            rip_output,
2061         .pr_ctloutput =         rip_ctloutput,
2062         .pr_usrreqs =           &rip_usrreqs
2063 };
2064 #endif
2065
2066 #ifdef INET6
2067 extern  struct domain inet6domain;
2068 static struct protosw in6_carp_protosw = {
2069         .pr_type =              SOCK_RAW,
2070         .pr_domain =            &inet6domain,
2071         .pr_protocol =          IPPROTO_CARP,
2072         .pr_flags =             PR_ATOMIC|PR_ADDR,
2073         .pr_input =             carp6_input,
2074         .pr_output =            rip6_output,
2075         .pr_ctloutput =         rip6_ctloutput,
2076         .pr_usrreqs =           &rip6_usrreqs
2077 };
2078 #endif
2079
2080 static void
2081 carp_mod_cleanup(void)
2082 {
2083
2084 #ifdef INET
2085         if (proto_reg[CARP_INET] == 0) {
2086                 (void)ipproto_unregister(IPPROTO_CARP);
2087                 pf_proto_unregister(PF_INET, IPPROTO_CARP, SOCK_RAW);
2088                 proto_reg[CARP_INET] = -1;
2089         }
2090         carp_iamatch_p = NULL;
2091 #endif
2092 #ifdef INET6
2093         if (proto_reg[CARP_INET6] == 0) {
2094                 (void)ip6proto_unregister(IPPROTO_CARP);
2095                 pf_proto_unregister(PF_INET6, IPPROTO_CARP, SOCK_RAW);
2096                 proto_reg[CARP_INET6] = -1;
2097         }
2098         carp_iamatch6_p = NULL;
2099         carp_macmatch6_p = NULL;
2100 #endif
2101         carp_ioctl_p = NULL;
2102         carp_attach_p = NULL;
2103         carp_detach_p = NULL;
2104         carp_get_vhid_p = NULL;
2105         carp_linkstate_p = NULL;
2106         carp_forus_p = NULL;
2107         carp_output_p = NULL;
2108         carp_demote_adj_p = NULL;
2109         carp_master_p = NULL;
2110         mtx_unlock(&carp_mtx);
2111         taskqueue_drain(taskqueue_swi, &carp_sendall_task);
2112         mtx_destroy(&carp_mtx);
2113 }
2114
2115 static int
2116 carp_mod_load(void)
2117 {
2118         int err;
2119
2120         mtx_init(&carp_mtx, "carp_mtx", NULL, MTX_DEF);
2121         LIST_INIT(&carp_list);
2122         carp_get_vhid_p = carp_get_vhid;
2123         carp_forus_p = carp_forus;
2124         carp_output_p = carp_output;
2125         carp_linkstate_p = carp_linkstate;
2126         carp_ioctl_p = carp_ioctl;
2127         carp_attach_p = carp_attach;
2128         carp_detach_p = carp_detach;
2129         carp_demote_adj_p = carp_demote_adj;
2130         carp_master_p = carp_master;
2131 #ifdef INET6
2132         carp_iamatch6_p = carp_iamatch6;
2133         carp_macmatch6_p = carp_macmatch6;
2134         proto_reg[CARP_INET6] = pf_proto_register(PF_INET6,
2135             (struct protosw *)&in6_carp_protosw);
2136         if (proto_reg[CARP_INET6]) {
2137                 printf("carp: error %d attaching to PF_INET6\n",
2138                     proto_reg[CARP_INET6]);
2139                 carp_mod_cleanup();
2140                 return (proto_reg[CARP_INET6]);
2141         }
2142         err = ip6proto_register(IPPROTO_CARP);
2143         if (err) {
2144                 printf("carp: error %d registering with INET6\n", err);
2145                 carp_mod_cleanup();
2146                 return (err);
2147         }
2148 #endif
2149 #ifdef INET
2150         carp_iamatch_p = carp_iamatch;
2151         proto_reg[CARP_INET] = pf_proto_register(PF_INET, &in_carp_protosw);
2152         if (proto_reg[CARP_INET]) {
2153                 printf("carp: error %d attaching to PF_INET\n",
2154                     proto_reg[CARP_INET]);
2155                 carp_mod_cleanup();
2156                 return (proto_reg[CARP_INET]);
2157         }
2158         err = ipproto_register(IPPROTO_CARP);
2159         if (err) {
2160                 printf("carp: error %d registering with INET\n", err);
2161                 carp_mod_cleanup();
2162                 return (err);
2163         }
2164 #endif
2165         return (0);
2166 }
2167
2168 static int
2169 carp_modevent(module_t mod, int type, void *data)
2170 {
2171         switch (type) {
2172         case MOD_LOAD:
2173                 return carp_mod_load();
2174                 /* NOTREACHED */
2175         case MOD_UNLOAD:
2176                 mtx_lock(&carp_mtx);
2177                 if (LIST_EMPTY(&carp_list))
2178                         carp_mod_cleanup();
2179                 else {
2180                         mtx_unlock(&carp_mtx);
2181                         return (EBUSY);
2182                 }
2183                 break;
2184
2185         default:
2186                 return (EINVAL);
2187         }
2188
2189         return (0);
2190 }
2191
2192 static moduledata_t carp_mod = {
2193         "carp",
2194         carp_modevent,
2195         0
2196 };
2197
2198 DECLARE_MODULE(carp, carp_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);