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