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