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