]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_carp.c
Add UPDATING entries and bump version.
[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_allow_sysctl(SYSCTL_HANDLER_ARGS);
218 static int carp_dscp_sysctl(SYSCTL_HANDLER_ARGS);
219 static int carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS);
220
221 SYSCTL_NODE(_net_inet, IPPROTO_CARP,    carp,   CTLFLAG_RW, 0,  "CARP");
222 SYSCTL_PROC(_net_inet_carp, OID_AUTO, allow,
223     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, 0, 0, carp_allow_sysctl, "I",
224     "Accept incoming CARP packets");
225 SYSCTL_PROC(_net_inet_carp, OID_AUTO, dscp,
226     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW, 0, 0, carp_dscp_sysctl, "I",
227     "DSCP value for carp packets");
228 SYSCTL_INT(_net_inet_carp, OID_AUTO, preempt, CTLFLAG_VNET | CTLFLAG_RW,
229     &VNET_NAME(carp_preempt), 0, "High-priority backup preemption mode");
230 SYSCTL_INT(_net_inet_carp, OID_AUTO, log, CTLFLAG_VNET | CTLFLAG_RW,
231     &VNET_NAME(carp_log), 0, "CARP log level");
232 SYSCTL_PROC(_net_inet_carp, OID_AUTO, demotion,
233     CTLFLAG_VNET | CTLTYPE_INT | CTLFLAG_RW,
234     0, 0, carp_demote_adj_sysctl, "I",
235     "Adjust demotion factor (skew of advskew)");
236 SYSCTL_INT(_net_inet_carp, OID_AUTO, senderr_demotion_factor,
237     CTLFLAG_VNET | CTLFLAG_RW,
238     &VNET_NAME(carp_senderr_adj), 0, "Send error demotion factor adjustment");
239 SYSCTL_INT(_net_inet_carp, OID_AUTO, ifdown_demotion_factor,
240     CTLFLAG_VNET | CTLFLAG_RW,
241     &VNET_NAME(carp_ifdown_adj), 0,
242     "Interface down demotion factor adjustment");
243
244 VNET_PCPUSTAT_DEFINE(struct carpstats, carpstats);
245 VNET_PCPUSTAT_SYSINIT(carpstats);
246 VNET_PCPUSTAT_SYSUNINIT(carpstats);
247
248 #define CARPSTATS_ADD(name, val)        \
249     counter_u64_add(VNET(carpstats)[offsetof(struct carpstats, name) / \
250         sizeof(uint64_t)], (val))
251 #define CARPSTATS_INC(name)             CARPSTATS_ADD(name, 1)
252
253 SYSCTL_VNET_PCPUSTAT(_net_inet_carp, OID_AUTO, stats, struct carpstats,
254     carpstats, "CARP statistics (struct carpstats, netinet/ip_carp.h)");
255
256 #define CARP_LOCK_INIT(sc)      mtx_init(&(sc)->sc_mtx, "carp_softc",   \
257         NULL, MTX_DEF)
258 #define CARP_LOCK_DESTROY(sc)   mtx_destroy(&(sc)->sc_mtx)
259 #define CARP_LOCK_ASSERT(sc)    mtx_assert(&(sc)->sc_mtx, MA_OWNED)
260 #define CARP_LOCK(sc)           mtx_lock(&(sc)->sc_mtx)
261 #define CARP_UNLOCK(sc)         mtx_unlock(&(sc)->sc_mtx)
262 #define CIF_LOCK_INIT(cif)      mtx_init(&(cif)->cif_mtx, "carp_if",   \
263         NULL, MTX_DEF)
264 #define CIF_LOCK_DESTROY(cif)   mtx_destroy(&(cif)->cif_mtx)
265 #define CIF_LOCK_ASSERT(cif)    mtx_assert(&(cif)->cif_mtx, MA_OWNED)
266 #define CIF_LOCK(cif)           mtx_lock(&(cif)->cif_mtx)
267 #define CIF_UNLOCK(cif)         mtx_unlock(&(cif)->cif_mtx)
268 #define CIF_FREE(cif)   do {                            \
269                 CIF_LOCK(cif);                          \
270                 if (TAILQ_EMPTY(&(cif)->cif_vrs))       \
271                         carp_free_if(cif);              \
272                 else                                    \
273                         CIF_UNLOCK(cif);                \
274 } while (0)
275
276 #define CARP_LOG(...)   do {                            \
277         if (V_carp_log > 0)                             \
278                 log(LOG_INFO, "carp: " __VA_ARGS__);    \
279 } while (0)
280
281 #define CARP_DEBUG(...) do {                            \
282         if (V_carp_log > 1)                             \
283                 log(LOG_DEBUG, __VA_ARGS__);            \
284 } while (0)
285
286 #define IFNET_FOREACH_IFA(ifp, ifa)                                     \
287         IF_ADDR_LOCK_ASSERT(ifp);                                       \
288         TAILQ_FOREACH((ifa), &(ifp)->if_addrhead, ifa_link)             \
289                 if ((ifa)->ifa_carp != NULL)
290
291 #define CARP_FOREACH_IFA(sc, ifa)                                       \
292         CARP_LOCK_ASSERT(sc);                                           \
293         for (int _i = 0;                                                \
294                 _i < (sc)->sc_naddrs + (sc)->sc_naddrs6 &&              \
295                 ((ifa) = sc->sc_ifas[_i]) != NULL;                      \
296                 ++_i)
297
298 #define IFNET_FOREACH_CARP(ifp, sc)                                     \
299         KASSERT(mtx_owned(&ifp->if_carp->cif_mtx) ||                    \
300             sx_xlocked(&carp_sx), ("cif_vrs not locked"));              \
301         TAILQ_FOREACH((sc), &(ifp)->if_carp->cif_vrs, sc_list)
302
303 #define DEMOTE_ADVSKEW(sc)                                      \
304     (((sc)->sc_advskew + V_carp_demotion > CARP_MAXSKEW) ?      \
305     CARP_MAXSKEW : ((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 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 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         len = m->m_len;
571         IP6_EXTHDR_GET(ch, struct carp_header *, m, *offp, sizeof(*ch));
572         if (ch == NULL) {
573                 CARPSTATS_INC(carps_badlen);
574                 CARP_DEBUG("%s: packet size %u too small\n", __func__, len);
575                 return (IPPROTO_DONE);
576         }
577
578
579         /* verify the CARP checksum */
580         m->m_data += *offp;
581         if (in_cksum(m, sizeof(*ch))) {
582                 CARPSTATS_INC(carps_badsum);
583                 CARP_DEBUG("%s: checksum failed, on %s\n", __func__,
584                     m->m_pkthdr.rcvif->if_xname);
585                 m_freem(m);
586                 return (IPPROTO_DONE);
587         }
588         m->m_data -= *offp;
589
590         carp_input_c(m, ch, AF_INET6);
591         return (IPPROTO_DONE);
592 }
593 #endif /* INET6 */
594
595 static void
596 carp_input_c(struct mbuf *m, struct carp_header *ch, sa_family_t af)
597 {
598         struct ifnet *ifp = m->m_pkthdr.rcvif;
599         struct ifaddr *ifa;
600         struct carp_softc *sc;
601         uint64_t tmp_counter;
602         struct timeval sc_tv, ch_tv;
603
604         /* verify that the VHID is valid on the receiving interface */
605         IF_ADDR_RLOCK(ifp);
606         IFNET_FOREACH_IFA(ifp, ifa)
607                 if (ifa->ifa_addr->sa_family == af &&
608                     ifa->ifa_carp->sc_vhid == ch->carp_vhid) {
609                         ifa_ref(ifa);
610                         break;
611                 }
612         IF_ADDR_RUNLOCK(ifp);
613
614         if (ifa == NULL) {
615                 CARPSTATS_INC(carps_badvhid);
616                 m_freem(m);
617                 return;
618         }
619
620         /* verify the CARP version. */
621         if (ch->carp_version != CARP_VERSION) {
622                 CARPSTATS_INC(carps_badver);
623                 CARP_DEBUG("%s: invalid version %d\n", ifp->if_xname,
624                     ch->carp_version);
625                 ifa_free(ifa);
626                 m_freem(m);
627                 return;
628         }
629
630         sc = ifa->ifa_carp;
631         CARP_LOCK(sc);
632         ifa_free(ifa);
633
634         if (carp_hmac_verify(sc, ch->carp_counter, ch->carp_md)) {
635                 CARPSTATS_INC(carps_badauth);
636                 CARP_DEBUG("%s: incorrect hash for VHID %u@%s\n", __func__,
637                     sc->sc_vhid, ifp->if_xname);
638                 goto out;
639         }
640
641         tmp_counter = ntohl(ch->carp_counter[0]);
642         tmp_counter = tmp_counter<<32;
643         tmp_counter += ntohl(ch->carp_counter[1]);
644
645         /* XXX Replay protection goes here */
646
647         sc->sc_init_counter = 0;
648         sc->sc_counter = tmp_counter;
649
650         sc_tv.tv_sec = sc->sc_advbase;
651         sc_tv.tv_usec = DEMOTE_ADVSKEW(sc) * 1000000 / 256;
652         ch_tv.tv_sec = ch->carp_advbase;
653         ch_tv.tv_usec = ch->carp_advskew * 1000000 / 256;
654
655         switch (sc->sc_state) {
656         case INIT:
657                 break;
658         case MASTER:
659                 /*
660                  * If we receive an advertisement from a master who's going to
661                  * be more frequent than us, go into BACKUP state.
662                  */
663                 if (timevalcmp(&sc_tv, &ch_tv, >) ||
664                     timevalcmp(&sc_tv, &ch_tv, ==)) {
665                         callout_stop(&sc->sc_ad_tmo);
666                         carp_set_state(sc, BACKUP,
667                             "more frequent advertisement received");
668                         carp_setrun(sc, 0);
669                         carp_delroute(sc);
670                 }
671                 break;
672         case BACKUP:
673                 /*
674                  * If we're pre-empting masters who advertise slower than us,
675                  * and this one claims to be slower, treat him as down.
676                  */
677                 if (V_carp_preempt && timevalcmp(&sc_tv, &ch_tv, <)) {
678                         carp_master_down_locked(sc,
679                             "preempting a slower master");
680                         break;
681                 }
682
683                 /*
684                  *  If the master is going to advertise at such a low frequency
685                  *  that he's guaranteed to time out, we'd might as well just
686                  *  treat him as timed out now.
687                  */
688                 sc_tv.tv_sec = sc->sc_advbase * 3;
689                 if (timevalcmp(&sc_tv, &ch_tv, <)) {
690                         carp_master_down_locked(sc, "master will time out");
691                         break;
692                 }
693
694                 /*
695                  * Otherwise, we reset the counter and wait for the next
696                  * advertisement.
697                  */
698                 carp_setrun(sc, af);
699                 break;
700         }
701
702 out:
703         CARP_UNLOCK(sc);
704         m_freem(m);
705 }
706
707 static int
708 carp_prepare_ad(struct mbuf *m, struct carp_softc *sc, struct carp_header *ch)
709 {
710         struct m_tag *mtag;
711
712         if (sc->sc_init_counter) {
713                 /* this could also be seconds since unix epoch */
714                 sc->sc_counter = arc4random();
715                 sc->sc_counter = sc->sc_counter << 32;
716                 sc->sc_counter += arc4random();
717         } else
718                 sc->sc_counter++;
719
720         ch->carp_counter[0] = htonl((sc->sc_counter>>32)&0xffffffff);
721         ch->carp_counter[1] = htonl(sc->sc_counter&0xffffffff);
722
723         carp_hmac_generate(sc, ch->carp_counter, ch->carp_md);
724
725         /* Tag packet for carp_output */
726         if ((mtag = m_tag_get(PACKET_TAG_CARP, sizeof(struct carp_softc *),
727             M_NOWAIT)) == NULL) {
728                 m_freem(m);
729                 CARPSTATS_INC(carps_onomem);
730                 return (ENOMEM);
731         }
732         bcopy(&sc, mtag + 1, sizeof(sc));
733         m_tag_prepend(m, mtag);
734
735         return (0);
736 }
737
738 /*
739  * To avoid LORs and possible recursions this function shouldn't
740  * be called directly, but scheduled via taskqueue.
741  */
742 static void
743 carp_send_ad_all(void *ctx __unused, int pending __unused)
744 {
745         struct carp_softc *sc;
746
747         mtx_lock(&carp_mtx);
748         LIST_FOREACH(sc, &carp_list, sc_next)
749                 if (sc->sc_state == MASTER) {
750                         CARP_LOCK(sc);
751                         CURVNET_SET(sc->sc_carpdev->if_vnet);
752                         carp_send_ad_locked(sc);
753                         CURVNET_RESTORE();
754                         CARP_UNLOCK(sc);
755                 }
756         mtx_unlock(&carp_mtx);
757 }
758
759 /* Send a periodic advertisement, executed in callout context. */
760 static void
761 carp_send_ad(void *v)
762 {
763         struct carp_softc *sc = v;
764
765         CARP_LOCK_ASSERT(sc);
766         CURVNET_SET(sc->sc_carpdev->if_vnet);
767         carp_send_ad_locked(sc);
768         CURVNET_RESTORE();
769         CARP_UNLOCK(sc);
770 }
771
772 static void
773 carp_send_ad_error(struct carp_softc *sc, int error)
774 {
775
776         if (error) {
777                 if (sc->sc_sendad_errors < INT_MAX)
778                         sc->sc_sendad_errors++;
779                 if (sc->sc_sendad_errors == CARP_SENDAD_MAX_ERRORS) {
780                         static const char fmt[] = "send error %d on %s";
781                         char msg[sizeof(fmt) + IFNAMSIZ];
782
783                         sprintf(msg, fmt, error, sc->sc_carpdev->if_xname);
784                         carp_demote_adj(V_carp_senderr_adj, msg);
785                 }
786                 sc->sc_sendad_success = 0;
787         } else {
788                 if (sc->sc_sendad_errors >= CARP_SENDAD_MAX_ERRORS &&
789                     ++sc->sc_sendad_success >= CARP_SENDAD_MIN_SUCCESS) {
790                         static const char fmt[] = "send ok on %s";
791                         char msg[sizeof(fmt) + IFNAMSIZ];
792
793                         sprintf(msg, fmt, sc->sc_carpdev->if_xname);
794                         carp_demote_adj(-V_carp_senderr_adj, msg);
795                         sc->sc_sendad_errors = 0;
796                 } else
797                         sc->sc_sendad_errors = 0;
798         }
799 }
800
801 static void
802 carp_send_ad_locked(struct carp_softc *sc)
803 {
804         struct carp_header ch;
805         struct timeval tv;
806         struct sockaddr sa;
807         struct ifaddr *ifa;
808         struct carp_header *ch_ptr;
809         struct mbuf *m;
810         int len, advskew;
811
812         CARP_LOCK_ASSERT(sc);
813
814         advskew = DEMOTE_ADVSKEW(sc);
815         tv.tv_sec = sc->sc_advbase;
816         tv.tv_usec = advskew * 1000000 / 256;
817
818         ch.carp_version = CARP_VERSION;
819         ch.carp_type = CARP_ADVERTISEMENT;
820         ch.carp_vhid = sc->sc_vhid;
821         ch.carp_advbase = sc->sc_advbase;
822         ch.carp_advskew = advskew;
823         ch.carp_authlen = 7;    /* XXX DEFINE */
824         ch.carp_pad1 = 0;       /* must be zero */
825         ch.carp_cksum = 0;
826
827         /* XXXGL: OpenBSD picks first ifaddr with needed family. */
828
829 #ifdef INET
830         if (sc->sc_naddrs) {
831                 struct ip *ip;
832
833                 m = m_gethdr(M_NOWAIT, MT_DATA);
834                 if (m == NULL) {
835                         CARPSTATS_INC(carps_onomem);
836                         goto resched;
837                 }
838                 len = sizeof(*ip) + sizeof(ch);
839                 m->m_pkthdr.len = len;
840                 m->m_pkthdr.rcvif = NULL;
841                 m->m_len = len;
842                 M_ALIGN(m, m->m_len);
843                 m->m_flags |= M_MCAST;
844                 ip = mtod(m, struct ip *);
845                 ip->ip_v = IPVERSION;
846                 ip->ip_hl = sizeof(*ip) >> 2;
847                 ip->ip_tos = V_carp_dscp << IPTOS_DSCP_OFFSET;
848                 ip->ip_len = htons(len);
849                 ip->ip_off = htons(IP_DF);
850                 ip->ip_ttl = CARP_DFLTTL;
851                 ip->ip_p = IPPROTO_CARP;
852                 ip->ip_sum = 0;
853                 ip_fillid(ip);
854
855                 bzero(&sa, sizeof(sa));
856                 sa.sa_family = AF_INET;
857                 ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
858                 if (ifa != NULL) {
859                         ip->ip_src.s_addr =
860                             ifatoia(ifa)->ia_addr.sin_addr.s_addr;
861                         ifa_free(ifa);
862                 } else
863                         ip->ip_src.s_addr = 0;
864                 ip->ip_dst.s_addr = htonl(INADDR_CARP_GROUP);
865
866                 ch_ptr = (struct carp_header *)(&ip[1]);
867                 bcopy(&ch, ch_ptr, sizeof(ch));
868                 if (carp_prepare_ad(m, sc, ch_ptr))
869                         goto resched;
870
871                 m->m_data += sizeof(*ip);
872                 ch_ptr->carp_cksum = in_cksum(m, len - sizeof(*ip));
873                 m->m_data -= sizeof(*ip);
874
875                 CARPSTATS_INC(carps_opackets);
876
877                 carp_send_ad_error(sc, ip_output(m, NULL, NULL, IP_RAWOUTPUT,
878                     &sc->sc_carpdev->if_carp->cif_imo, NULL));
879         }
880 #endif /* INET */
881 #ifdef INET6
882         if (sc->sc_naddrs6) {
883                 struct ip6_hdr *ip6;
884
885                 m = m_gethdr(M_NOWAIT, MT_DATA);
886                 if (m == NULL) {
887                         CARPSTATS_INC(carps_onomem);
888                         goto resched;
889                 }
890                 len = sizeof(*ip6) + sizeof(ch);
891                 m->m_pkthdr.len = len;
892                 m->m_pkthdr.rcvif = NULL;
893                 m->m_len = len;
894                 M_ALIGN(m, m->m_len);
895                 m->m_flags |= M_MCAST;
896                 ip6 = mtod(m, struct ip6_hdr *);
897                 bzero(ip6, sizeof(*ip6));
898                 ip6->ip6_vfc |= IPV6_VERSION;
899                 /* Traffic class isn't defined in ip6 struct instead
900                  * it gets offset into flowid field */
901                 ip6->ip6_flow |= htonl(V_carp_dscp << (IPV6_FLOWLABEL_LEN +
902                     IPTOS_DSCP_OFFSET));
903                 ip6->ip6_hlim = CARP_DFLTTL;
904                 ip6->ip6_nxt = IPPROTO_CARP;
905                 bzero(&sa, sizeof(sa));
906
907                 /* set the source address */
908                 sa.sa_family = AF_INET6;
909                 ifa = ifaof_ifpforaddr(&sa, sc->sc_carpdev);
910                 if (ifa != NULL) {
911                         bcopy(IFA_IN6(ifa), &ip6->ip6_src,
912                             sizeof(struct in6_addr));
913                         ifa_free(ifa);
914                 } else
915                         /* This should never happen with IPv6. */
916                         bzero(&ip6->ip6_src, sizeof(struct in6_addr));
917
918                 /* Set the multicast destination. */
919                 ip6->ip6_dst.s6_addr16[0] = htons(0xff02);
920                 ip6->ip6_dst.s6_addr8[15] = 0x12;
921                 if (in6_setscope(&ip6->ip6_dst, sc->sc_carpdev, NULL) != 0) {
922                         m_freem(m);
923                         CARP_DEBUG("%s: in6_setscope failed\n", __func__);
924                         goto resched;
925                 }
926
927                 ch_ptr = (struct carp_header *)(&ip6[1]);
928                 bcopy(&ch, ch_ptr, sizeof(ch));
929                 if (carp_prepare_ad(m, sc, ch_ptr))
930                         goto resched;
931
932                 m->m_data += sizeof(*ip6);
933                 ch_ptr->carp_cksum = in_cksum(m, len - sizeof(*ip6));
934                 m->m_data -= sizeof(*ip6);
935
936                 CARPSTATS_INC(carps_opackets6);
937
938                 carp_send_ad_error(sc, ip6_output(m, NULL, NULL, 0,
939                     &sc->sc_carpdev->if_carp->cif_im6o, NULL, NULL));
940         }
941 #endif /* INET6 */
942
943 resched:
944         callout_reset(&sc->sc_ad_tmo, tvtohz(&tv), carp_send_ad, sc);
945 }
946
947 static void
948 carp_addroute(struct carp_softc *sc)
949 {
950         struct ifaddr *ifa;
951
952         CARP_FOREACH_IFA(sc, ifa)
953                 carp_ifa_addroute(ifa);
954 }
955
956 static void
957 carp_ifa_addroute(struct ifaddr *ifa)
958 {
959
960         switch (ifa->ifa_addr->sa_family) {
961 #ifdef INET
962         case AF_INET:
963                 in_addprefix(ifatoia(ifa), RTF_UP);
964                 ifa_add_loopback_route(ifa,
965                     (struct sockaddr *)&ifatoia(ifa)->ia_addr);
966                 break;
967 #endif
968 #ifdef INET6
969         case AF_INET6:
970                 ifa_add_loopback_route(ifa,
971                     (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
972                 nd6_add_ifa_lle(ifatoia6(ifa));
973                 break;
974 #endif
975         }
976 }
977
978 static void
979 carp_delroute(struct carp_softc *sc)
980 {
981         struct ifaddr *ifa;
982
983         CARP_FOREACH_IFA(sc, ifa)
984                 carp_ifa_delroute(ifa);
985 }
986
987 static void
988 carp_ifa_delroute(struct ifaddr *ifa)
989 {
990
991         switch (ifa->ifa_addr->sa_family) {
992 #ifdef INET
993         case AF_INET:
994                 ifa_del_loopback_route(ifa,
995                     (struct sockaddr *)&ifatoia(ifa)->ia_addr);
996                 in_scrubprefix(ifatoia(ifa), LLE_STATIC);
997                 break;
998 #endif
999 #ifdef INET6
1000         case AF_INET6:
1001                 ifa_del_loopback_route(ifa,
1002                     (struct sockaddr *)&ifatoia6(ifa)->ia_addr);
1003                 nd6_rem_ifa_lle(ifatoia6(ifa), 1);
1004                 break;
1005 #endif
1006         }
1007 }
1008
1009 int
1010 carp_master(struct ifaddr *ifa)
1011 {
1012         struct carp_softc *sc = ifa->ifa_carp;
1013
1014         return (sc->sc_state == MASTER);
1015 }
1016
1017 #ifdef INET
1018 /*
1019  * Broadcast a gratuitous ARP request containing
1020  * the virtual router MAC address for each IP address
1021  * associated with the virtual router.
1022  */
1023 static void
1024 carp_send_arp(struct carp_softc *sc)
1025 {
1026         struct ifaddr *ifa;
1027         struct in_addr addr;
1028
1029         CARP_FOREACH_IFA(sc, ifa) {
1030                 if (ifa->ifa_addr->sa_family != AF_INET)
1031                         continue;
1032                 addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
1033                 arp_announce_ifaddr(sc->sc_carpdev, addr, LLADDR(&sc->sc_addr));
1034         }
1035 }
1036
1037 int
1038 carp_iamatch(struct ifaddr *ifa, uint8_t **enaddr)
1039 {
1040         struct carp_softc *sc = ifa->ifa_carp;
1041
1042         if (sc->sc_state == MASTER) {
1043                 *enaddr = LLADDR(&sc->sc_addr);
1044                 return (1);
1045         }
1046
1047         return (0);
1048 }
1049 #endif
1050
1051 #ifdef INET6
1052 static void
1053 carp_send_na(struct carp_softc *sc)
1054 {
1055         static struct in6_addr mcast = IN6ADDR_LINKLOCAL_ALLNODES_INIT;
1056         struct ifaddr *ifa;
1057         struct in6_addr *in6;
1058
1059         CARP_FOREACH_IFA(sc, ifa) {
1060                 if (ifa->ifa_addr->sa_family != AF_INET6)
1061                         continue;
1062
1063                 in6 = IFA_IN6(ifa);
1064                 nd6_na_output(sc->sc_carpdev, &mcast, in6,
1065                     ND_NA_FLAG_OVERRIDE, 1, NULL);
1066                 DELAY(1000);    /* XXX */
1067         }
1068 }
1069
1070 /*
1071  * Returns ifa in case it's a carp address and it is MASTER, or if the address
1072  * matches and is not a carp address.  Returns NULL otherwise.
1073  */
1074 struct ifaddr *
1075 carp_iamatch6(struct ifnet *ifp, struct in6_addr *taddr)
1076 {
1077         struct ifaddr *ifa;
1078
1079         ifa = NULL;
1080         IF_ADDR_RLOCK(ifp);
1081         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1082                 if (ifa->ifa_addr->sa_family != AF_INET6)
1083                         continue;
1084                 if (!IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa)))
1085                         continue;
1086                 if (ifa->ifa_carp && ifa->ifa_carp->sc_state != MASTER)
1087                         ifa = NULL;
1088                 else
1089                         ifa_ref(ifa);
1090                 break;
1091         }
1092         IF_ADDR_RUNLOCK(ifp);
1093
1094         return (ifa);
1095 }
1096
1097 caddr_t
1098 carp_macmatch6(struct ifnet *ifp, struct mbuf *m, const struct in6_addr *taddr)
1099 {
1100         struct ifaddr *ifa;
1101
1102         IF_ADDR_RLOCK(ifp);
1103         IFNET_FOREACH_IFA(ifp, ifa)
1104                 if (ifa->ifa_addr->sa_family == AF_INET6 &&
1105                     IN6_ARE_ADDR_EQUAL(taddr, IFA_IN6(ifa))) {
1106                         struct carp_softc *sc = ifa->ifa_carp;
1107                         struct m_tag *mtag;
1108
1109                         IF_ADDR_RUNLOCK(ifp);
1110
1111                         mtag = m_tag_get(PACKET_TAG_CARP,
1112                             sizeof(struct carp_softc *), M_NOWAIT);
1113                         if (mtag == NULL)
1114                                 /* Better a bit than nothing. */
1115                                 return (LLADDR(&sc->sc_addr));
1116
1117                         bcopy(&sc, mtag + 1, sizeof(sc));
1118                         m_tag_prepend(m, mtag);
1119
1120                         return (LLADDR(&sc->sc_addr));
1121                 }
1122         IF_ADDR_RUNLOCK(ifp);
1123
1124         return (NULL);
1125 }
1126 #endif /* INET6 */
1127
1128 int
1129 carp_forus(struct ifnet *ifp, u_char *dhost)
1130 {
1131         struct carp_softc *sc;
1132         uint8_t *ena = dhost;
1133
1134         if (ena[0] || ena[1] || ena[2] != 0x5e || ena[3] || ena[4] != 1)
1135                 return (0);
1136
1137         CIF_LOCK(ifp->if_carp);
1138         IFNET_FOREACH_CARP(ifp, sc) {
1139                 CARP_LOCK(sc);
1140                 if (sc->sc_state == MASTER && !bcmp(dhost, LLADDR(&sc->sc_addr),
1141                     ETHER_ADDR_LEN)) {
1142                         CARP_UNLOCK(sc);
1143                         CIF_UNLOCK(ifp->if_carp);
1144                         return (1);
1145                 }
1146                 CARP_UNLOCK(sc);
1147         }
1148         CIF_UNLOCK(ifp->if_carp);
1149
1150         return (0);
1151 }
1152
1153 /* Master down timeout event, executed in callout context. */
1154 static void
1155 carp_master_down(void *v)
1156 {
1157         struct carp_softc *sc = v;
1158
1159         CARP_LOCK_ASSERT(sc);
1160
1161         CURVNET_SET(sc->sc_carpdev->if_vnet);
1162         if (sc->sc_state == BACKUP) {
1163                 carp_master_down_locked(sc, "master timed out");
1164         }
1165         CURVNET_RESTORE();
1166
1167         CARP_UNLOCK(sc);
1168 }
1169
1170 static void
1171 carp_master_down_locked(struct carp_softc *sc, const char *reason)
1172 {
1173
1174         CARP_LOCK_ASSERT(sc);
1175
1176         switch (sc->sc_state) {
1177         case BACKUP:
1178                 carp_set_state(sc, MASTER, reason);
1179                 carp_send_ad_locked(sc);
1180 #ifdef INET
1181                 carp_send_arp(sc);
1182 #endif
1183 #ifdef INET6
1184                 carp_send_na(sc);
1185 #endif
1186                 carp_setrun(sc, 0);
1187                 carp_addroute(sc);
1188                 break;
1189         case INIT:
1190         case MASTER:
1191 #ifdef INVARIANTS
1192                 panic("carp: VHID %u@%s: master_down event in %s state\n",
1193                     sc->sc_vhid,
1194                     sc->sc_carpdev->if_xname,
1195                     sc->sc_state ? "MASTER" : "INIT");
1196 #endif
1197                 break;
1198         }
1199 }
1200
1201 /*
1202  * When in backup state, af indicates whether to reset the master down timer
1203  * for v4 or v6. If it's set to zero, reset the ones which are already pending.
1204  */
1205 static void
1206 carp_setrun(struct carp_softc *sc, sa_family_t af)
1207 {
1208         struct timeval tv;
1209
1210         CARP_LOCK_ASSERT(sc);
1211
1212         if ((sc->sc_carpdev->if_flags & IFF_UP) == 0 ||
1213             sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1214             (sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0) ||
1215             !V_carp_allow)
1216                 return;
1217
1218         switch (sc->sc_state) {
1219         case INIT:
1220                 carp_set_state(sc, BACKUP, "initialization complete");
1221                 carp_setrun(sc, 0);
1222                 break;
1223         case BACKUP:
1224                 callout_stop(&sc->sc_ad_tmo);
1225                 tv.tv_sec = 3 * sc->sc_advbase;
1226                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1227                 switch (af) {
1228 #ifdef INET
1229                 case AF_INET:
1230                         callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1231                             carp_master_down, sc);
1232                         break;
1233 #endif
1234 #ifdef INET6
1235                 case AF_INET6:
1236                         callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1237                             carp_master_down, sc);
1238                         break;
1239 #endif
1240                 default:
1241 #ifdef INET
1242                         if (sc->sc_naddrs)
1243                                 callout_reset(&sc->sc_md_tmo, tvtohz(&tv),
1244                                     carp_master_down, sc);
1245 #endif
1246 #ifdef INET6
1247                         if (sc->sc_naddrs6)
1248                                 callout_reset(&sc->sc_md6_tmo, tvtohz(&tv),
1249                                     carp_master_down, sc);
1250 #endif
1251                         break;
1252                 }
1253                 break;
1254         case MASTER:
1255                 tv.tv_sec = sc->sc_advbase;
1256                 tv.tv_usec = sc->sc_advskew * 1000000 / 256;
1257                 callout_reset(&sc->sc_ad_tmo, tvtohz(&tv),
1258                     carp_send_ad, sc);
1259                 break;
1260         }
1261 }
1262
1263 /*
1264  * Setup multicast structures.
1265  */
1266 static int
1267 carp_multicast_setup(struct carp_if *cif, sa_family_t sa)
1268 {
1269         struct ifnet *ifp = cif->cif_ifp;
1270         int error = 0;
1271
1272         switch (sa) {
1273 #ifdef INET
1274         case AF_INET:
1275             {
1276                 struct ip_moptions *imo = &cif->cif_imo;
1277                 struct in_addr addr;
1278
1279                 if (imo->imo_membership)
1280                         return (0);
1281
1282                 imo->imo_membership = (struct in_multi **)malloc(
1283                     (sizeof(struct in_multi *) * IP_MIN_MEMBERSHIPS), M_CARP,
1284                     M_WAITOK);
1285                 imo->imo_mfilters = NULL;
1286                 imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1287                 imo->imo_multicast_vif = -1;
1288
1289                 addr.s_addr = htonl(INADDR_CARP_GROUP);
1290                 if ((error = in_joingroup(ifp, &addr, NULL,
1291                     &imo->imo_membership[0])) != 0) {
1292                         free(imo->imo_membership, M_CARP);
1293                         break;
1294                 }
1295                 imo->imo_num_memberships++;
1296                 imo->imo_multicast_ifp = ifp;
1297                 imo->imo_multicast_ttl = CARP_DFLTTL;
1298                 imo->imo_multicast_loop = 0;
1299                 break;
1300            }
1301 #endif
1302 #ifdef INET6
1303         case AF_INET6:
1304             {
1305                 struct ip6_moptions *im6o = &cif->cif_im6o;
1306                 struct in6_addr in6;
1307                 struct in6_multi *in6m;
1308
1309                 if (im6o->im6o_membership)
1310                         return (0);
1311
1312                 im6o->im6o_membership = (struct in6_multi **)malloc(
1313                     (sizeof(struct in6_multi *) * IPV6_MIN_MEMBERSHIPS), M_CARP,
1314                     M_ZERO | M_WAITOK);
1315                 im6o->im6o_mfilters = NULL;
1316                 im6o->im6o_max_memberships = IPV6_MIN_MEMBERSHIPS;
1317                 im6o->im6o_multicast_hlim = CARP_DFLTTL;
1318                 im6o->im6o_multicast_ifp = ifp;
1319
1320                 /* Join IPv6 CARP multicast group. */
1321                 bzero(&in6, sizeof(in6));
1322                 in6.s6_addr16[0] = htons(0xff02);
1323                 in6.s6_addr8[15] = 0x12;
1324                 if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1325                         free(im6o->im6o_membership, M_CARP);
1326                         break;
1327                 }
1328                 in6m = NULL;
1329                 if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1330                         free(im6o->im6o_membership, M_CARP);
1331                         break;
1332                 }
1333                 im6o->im6o_membership[0] = in6m;
1334                 im6o->im6o_num_memberships++;
1335
1336                 /* Join solicited multicast address. */
1337                 bzero(&in6, sizeof(in6));
1338                 in6.s6_addr16[0] = htons(0xff02);
1339                 in6.s6_addr32[1] = 0;
1340                 in6.s6_addr32[2] = htonl(1);
1341                 in6.s6_addr32[3] = 0;
1342                 in6.s6_addr8[12] = 0xff;
1343                 if ((error = in6_setscope(&in6, ifp, NULL)) != 0) {
1344                         in6_mc_leave(im6o->im6o_membership[0], NULL);
1345                         free(im6o->im6o_membership, M_CARP);
1346                         break;
1347                 }
1348                 in6m = NULL;
1349                 if ((error = in6_mc_join(ifp, &in6, NULL, &in6m, 0)) != 0) {
1350                         in6_mc_leave(im6o->im6o_membership[0], NULL);
1351                         free(im6o->im6o_membership, M_CARP);
1352                         break;
1353                 }
1354                 im6o->im6o_membership[1] = in6m;
1355                 im6o->im6o_num_memberships++;
1356                 break;
1357             }
1358 #endif
1359         }
1360
1361         return (error);
1362 }
1363
1364 /*
1365  * Free multicast structures.
1366  */
1367 static void
1368 carp_multicast_cleanup(struct carp_if *cif, sa_family_t sa)
1369 {
1370
1371         sx_assert(&carp_sx, SA_XLOCKED);
1372
1373         switch (sa) {
1374 #ifdef INET
1375         case AF_INET:
1376                 if (cif->cif_naddrs == 0) {
1377                         struct ip_moptions *imo = &cif->cif_imo;
1378
1379                         in_leavegroup(imo->imo_membership[0], NULL);
1380                         KASSERT(imo->imo_mfilters == NULL,
1381                             ("%s: imo_mfilters != NULL", __func__));
1382                         free(imo->imo_membership, M_CARP);
1383                         imo->imo_membership = NULL;
1384
1385                 }
1386                 break;
1387 #endif
1388 #ifdef INET6
1389         case AF_INET6:
1390                 if (cif->cif_naddrs6 == 0) {
1391                         struct ip6_moptions *im6o = &cif->cif_im6o;
1392
1393                         in6_mc_leave(im6o->im6o_membership[0], NULL);
1394                         in6_mc_leave(im6o->im6o_membership[1], NULL);
1395                         KASSERT(im6o->im6o_mfilters == NULL,
1396                             ("%s: im6o_mfilters != NULL", __func__));
1397                         free(im6o->im6o_membership, M_CARP);
1398                         im6o->im6o_membership = NULL;
1399                 }
1400                 break;
1401 #endif
1402         }
1403 }
1404
1405 int
1406 carp_output(struct ifnet *ifp, struct mbuf *m, const struct sockaddr *sa)
1407 {
1408         struct m_tag *mtag;
1409         struct carp_softc *sc;
1410
1411         if (!sa)
1412                 return (0);
1413
1414         switch (sa->sa_family) {
1415 #ifdef INET
1416         case AF_INET:
1417                 break;
1418 #endif
1419 #ifdef INET6
1420         case AF_INET6:
1421                 break;
1422 #endif
1423         default:
1424                 return (0);
1425         }
1426
1427         mtag = m_tag_find(m, PACKET_TAG_CARP, NULL);
1428         if (mtag == NULL)
1429                 return (0);
1430
1431         bcopy(mtag + 1, &sc, sizeof(sc));
1432
1433         /* Set the source MAC address to the Virtual Router MAC Address. */
1434         switch (ifp->if_type) {
1435         case IFT_ETHER:
1436         case IFT_BRIDGE:
1437         case IFT_L2VLAN: {
1438                         struct ether_header *eh;
1439
1440                         eh = mtod(m, struct ether_header *);
1441                         eh->ether_shost[0] = 0;
1442                         eh->ether_shost[1] = 0;
1443                         eh->ether_shost[2] = 0x5e;
1444                         eh->ether_shost[3] = 0;
1445                         eh->ether_shost[4] = 1;
1446                         eh->ether_shost[5] = sc->sc_vhid;
1447                 }
1448                 break;
1449         case IFT_FDDI: {
1450                         struct fddi_header *fh;
1451
1452                         fh = mtod(m, struct fddi_header *);
1453                         fh->fddi_shost[0] = 0;
1454                         fh->fddi_shost[1] = 0;
1455                         fh->fddi_shost[2] = 0x5e;
1456                         fh->fddi_shost[3] = 0;
1457                         fh->fddi_shost[4] = 1;
1458                         fh->fddi_shost[5] = sc->sc_vhid;
1459                 }
1460                 break;
1461         case IFT_ISO88025: {
1462                         struct iso88025_header *th;
1463                         th = mtod(m, struct iso88025_header *);
1464                         th->iso88025_shost[0] = 3;
1465                         th->iso88025_shost[1] = 0;
1466                         th->iso88025_shost[2] = 0x40 >> (sc->sc_vhid - 1);
1467                         th->iso88025_shost[3] = 0x40000 >> (sc->sc_vhid - 1);
1468                         th->iso88025_shost[4] = 0;
1469                         th->iso88025_shost[5] = 0;
1470                 }
1471                 break;
1472         default:
1473                 printf("%s: carp is not supported for the %d interface type\n",
1474                     ifp->if_xname, ifp->if_type);
1475                 return (EOPNOTSUPP);
1476         }
1477
1478         return (0);
1479 }
1480
1481 static struct carp_softc*
1482 carp_alloc(struct ifnet *ifp)
1483 {
1484         struct carp_softc *sc;
1485         struct carp_if *cif;
1486
1487         sx_assert(&carp_sx, SA_XLOCKED);
1488
1489         if ((cif = ifp->if_carp) == NULL)
1490                 cif = carp_alloc_if(ifp);
1491
1492         sc = malloc(sizeof(*sc), M_CARP, M_WAITOK|M_ZERO);
1493
1494         sc->sc_advbase = CARP_DFLTINTV;
1495         sc->sc_vhid = -1;       /* required setting */
1496         sc->sc_init_counter = 1;
1497         sc->sc_state = INIT;
1498
1499         sc->sc_ifasiz = sizeof(struct ifaddr *);
1500         sc->sc_ifas = malloc(sc->sc_ifasiz, M_CARP, M_WAITOK|M_ZERO);
1501         sc->sc_carpdev = ifp;
1502
1503         CARP_LOCK_INIT(sc);
1504 #ifdef INET
1505         callout_init_mtx(&sc->sc_md_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1506 #endif
1507 #ifdef INET6
1508         callout_init_mtx(&sc->sc_md6_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1509 #endif
1510         callout_init_mtx(&sc->sc_ad_tmo, &sc->sc_mtx, CALLOUT_RETURNUNLOCKED);
1511
1512         CIF_LOCK(cif);
1513         TAILQ_INSERT_TAIL(&cif->cif_vrs, sc, sc_list);
1514         CIF_UNLOCK(cif);
1515
1516         mtx_lock(&carp_mtx);
1517         LIST_INSERT_HEAD(&carp_list, sc, sc_next);
1518         mtx_unlock(&carp_mtx);
1519
1520         return (sc);
1521 }
1522
1523 static void
1524 carp_grow_ifas(struct carp_softc *sc)
1525 {
1526         struct ifaddr **new;
1527
1528         new = malloc(sc->sc_ifasiz * 2, M_CARP, M_WAITOK | M_ZERO);
1529         CARP_LOCK(sc);
1530         bcopy(sc->sc_ifas, new, sc->sc_ifasiz);
1531         free(sc->sc_ifas, M_CARP);
1532         sc->sc_ifas = new;
1533         sc->sc_ifasiz *= 2;
1534         CARP_UNLOCK(sc);
1535 }
1536
1537 static void
1538 carp_destroy(struct carp_softc *sc)
1539 {
1540         struct ifnet *ifp = sc->sc_carpdev;
1541         struct carp_if *cif = ifp->if_carp;
1542
1543         sx_assert(&carp_sx, SA_XLOCKED);
1544
1545         if (sc->sc_suppress)
1546                 carp_demote_adj(-V_carp_ifdown_adj, "vhid removed");
1547         CARP_UNLOCK(sc);
1548
1549         CIF_LOCK(cif);
1550         TAILQ_REMOVE(&cif->cif_vrs, sc, sc_list);
1551         CIF_UNLOCK(cif);
1552
1553         mtx_lock(&carp_mtx);
1554         LIST_REMOVE(sc, sc_next);
1555         mtx_unlock(&carp_mtx);
1556
1557         callout_drain(&sc->sc_ad_tmo);
1558 #ifdef INET
1559         callout_drain(&sc->sc_md_tmo);
1560 #endif
1561 #ifdef INET6
1562         callout_drain(&sc->sc_md6_tmo);
1563 #endif
1564         CARP_LOCK_DESTROY(sc);
1565
1566         free(sc->sc_ifas, M_CARP);
1567         free(sc, M_CARP);
1568 }
1569
1570 static struct carp_if*
1571 carp_alloc_if(struct ifnet *ifp)
1572 {
1573         struct carp_if *cif;
1574         int error;
1575
1576         cif = malloc(sizeof(*cif), M_CARP, M_WAITOK|M_ZERO);
1577
1578         if ((error = ifpromisc(ifp, 1)) != 0)
1579                 printf("%s: ifpromisc(%s) failed: %d\n",
1580                     __func__, ifp->if_xname, error);
1581         else
1582                 cif->cif_flags |= CIF_PROMISC;
1583
1584         CIF_LOCK_INIT(cif);
1585         cif->cif_ifp = ifp;
1586         TAILQ_INIT(&cif->cif_vrs);
1587
1588         IF_ADDR_WLOCK(ifp);
1589         ifp->if_carp = cif;
1590         if_ref(ifp);
1591         IF_ADDR_WUNLOCK(ifp);
1592
1593         return (cif);
1594 }
1595
1596 static void
1597 carp_free_if(struct carp_if *cif)
1598 {
1599         struct ifnet *ifp = cif->cif_ifp;
1600
1601         CIF_LOCK_ASSERT(cif);
1602         KASSERT(TAILQ_EMPTY(&cif->cif_vrs), ("%s: softc list not empty",
1603             __func__));
1604
1605         IF_ADDR_WLOCK(ifp);
1606         ifp->if_carp = NULL;
1607         IF_ADDR_WUNLOCK(ifp);
1608
1609         CIF_LOCK_DESTROY(cif);
1610
1611         if (cif->cif_flags & CIF_PROMISC)
1612                 ifpromisc(ifp, 0);
1613         if_rele(ifp);
1614
1615         free(cif, M_CARP);
1616 }
1617
1618 static void
1619 carp_carprcp(struct carpreq *carpr, struct carp_softc *sc, int priv)
1620 {
1621
1622         CARP_LOCK(sc);
1623         carpr->carpr_state = sc->sc_state;
1624         carpr->carpr_vhid = sc->sc_vhid;
1625         carpr->carpr_advbase = sc->sc_advbase;
1626         carpr->carpr_advskew = sc->sc_advskew;
1627         if (priv)
1628                 bcopy(sc->sc_key, carpr->carpr_key, sizeof(carpr->carpr_key));
1629         else
1630                 bzero(carpr->carpr_key, sizeof(carpr->carpr_key));
1631         CARP_UNLOCK(sc);
1632 }
1633
1634 int
1635 carp_ioctl(struct ifreq *ifr, u_long cmd, struct thread *td)
1636 {
1637         struct carpreq carpr;
1638         struct ifnet *ifp;
1639         struct carp_softc *sc = NULL;
1640         int error = 0, locked = 0;
1641
1642         if ((error = copyin(ifr_data_get_ptr(ifr), &carpr, sizeof carpr)))
1643                 return (error);
1644
1645         ifp = ifunit_ref(ifr->ifr_name);
1646         if (ifp == NULL)
1647                 return (ENXIO);
1648
1649         switch (ifp->if_type) {
1650         case IFT_ETHER:
1651         case IFT_L2VLAN:
1652         case IFT_BRIDGE:
1653         case IFT_FDDI:
1654         case IFT_ISO88025:
1655                 break;
1656         default:
1657                 error = EOPNOTSUPP;
1658                 goto out;
1659         }
1660
1661         if ((ifp->if_flags & IFF_MULTICAST) == 0) {
1662                 error = EADDRNOTAVAIL;
1663                 goto out;
1664         }
1665
1666         sx_xlock(&carp_sx);
1667         switch (cmd) {
1668         case SIOCSVH:
1669                 if ((error = priv_check(td, PRIV_NETINET_CARP)))
1670                         break;
1671                 if (carpr.carpr_vhid <= 0 || carpr.carpr_vhid > CARP_MAXVHID ||
1672                     carpr.carpr_advbase < 0 || carpr.carpr_advskew < 0) {
1673                         error = EINVAL;
1674                         break;
1675                 }
1676
1677                 if (ifp->if_carp) {
1678                         IFNET_FOREACH_CARP(ifp, sc)
1679                                 if (sc->sc_vhid == carpr.carpr_vhid)
1680                                         break;
1681                 }
1682                 if (sc == NULL) {
1683                         sc = carp_alloc(ifp);
1684                         CARP_LOCK(sc);
1685                         sc->sc_vhid = carpr.carpr_vhid;
1686                         LLADDR(&sc->sc_addr)[0] = 0;
1687                         LLADDR(&sc->sc_addr)[1] = 0;
1688                         LLADDR(&sc->sc_addr)[2] = 0x5e;
1689                         LLADDR(&sc->sc_addr)[3] = 0;
1690                         LLADDR(&sc->sc_addr)[4] = 1;
1691                         LLADDR(&sc->sc_addr)[5] = sc->sc_vhid;
1692                 } else
1693                         CARP_LOCK(sc);
1694                 locked = 1;
1695                 if (carpr.carpr_advbase > 0) {
1696                         if (carpr.carpr_advbase > 255 ||
1697                             carpr.carpr_advbase < CARP_DFLTINTV) {
1698                                 error = EINVAL;
1699                                 break;
1700                         }
1701                         sc->sc_advbase = carpr.carpr_advbase;
1702                 }
1703                 if (carpr.carpr_advskew >= 255) {
1704                         error = EINVAL;
1705                         break;
1706                 }
1707                 sc->sc_advskew = carpr.carpr_advskew;
1708                 if (carpr.carpr_key[0] != '\0') {
1709                         bcopy(carpr.carpr_key, sc->sc_key, sizeof(sc->sc_key));
1710                         carp_hmac_prepare(sc);
1711                 }
1712                 if (sc->sc_state != INIT &&
1713                     carpr.carpr_state != sc->sc_state) {
1714                         switch (carpr.carpr_state) {
1715                         case BACKUP:
1716                                 callout_stop(&sc->sc_ad_tmo);
1717                                 carp_set_state(sc, BACKUP,
1718                                     "user requested via ifconfig");
1719                                 carp_setrun(sc, 0);
1720                                 carp_delroute(sc);
1721                                 break;
1722                         case MASTER:
1723                                 carp_master_down_locked(sc,
1724                                     "user requested via ifconfig");
1725                                 break;
1726                         default:
1727                                 break;
1728                         }
1729                 }
1730                 break;
1731
1732         case SIOCGVH:
1733             {
1734                 int priveleged;
1735
1736                 if (carpr.carpr_vhid < 0 || carpr.carpr_vhid > CARP_MAXVHID) {
1737                         error = EINVAL;
1738                         break;
1739                 }
1740                 if (carpr.carpr_count < 1) {
1741                         error = EMSGSIZE;
1742                         break;
1743                 }
1744                 if (ifp->if_carp == NULL) {
1745                         error = ENOENT;
1746                         break;
1747                 }
1748
1749                 priveleged = (priv_check(td, PRIV_NETINET_CARP) == 0);
1750                 if (carpr.carpr_vhid != 0) {
1751                         IFNET_FOREACH_CARP(ifp, sc)
1752                                 if (sc->sc_vhid == carpr.carpr_vhid)
1753                                         break;
1754                         if (sc == NULL) {
1755                                 error = ENOENT;
1756                                 break;
1757                         }
1758                         carp_carprcp(&carpr, sc, priveleged);
1759                         error = copyout(&carpr, ifr_data_get_ptr(ifr),
1760                             sizeof(carpr));
1761                 } else  {
1762                         int i, count;
1763
1764                         count = 0;
1765                         IFNET_FOREACH_CARP(ifp, sc)
1766                                 count++;
1767
1768                         if (count > carpr.carpr_count) {
1769                                 CIF_UNLOCK(ifp->if_carp);
1770                                 error = EMSGSIZE;
1771                                 break;
1772                         }
1773
1774                         i = 0;
1775                         IFNET_FOREACH_CARP(ifp, sc) {
1776                                 carp_carprcp(&carpr, sc, priveleged);
1777                                 carpr.carpr_count = count;
1778                                 error = copyout(&carpr,
1779                                     (caddr_t)ifr_data_get_ptr(ifr) +
1780                                     (i * sizeof(carpr)), sizeof(carpr));
1781                                 if (error) {
1782                                         CIF_UNLOCK(ifp->if_carp);
1783                                         break;
1784                                 }
1785                                 i++;
1786                         }
1787                 }
1788                 break;
1789             }
1790         default:
1791                 error = EINVAL;
1792         }
1793         sx_xunlock(&carp_sx);
1794
1795 out:
1796         if (locked)
1797                 CARP_UNLOCK(sc);
1798         if_rele(ifp);
1799
1800         return (error);
1801 }
1802
1803 static int
1804 carp_get_vhid(struct ifaddr *ifa)
1805 {
1806
1807         if (ifa == NULL || ifa->ifa_carp == NULL)
1808                 return (0);
1809
1810         return (ifa->ifa_carp->sc_vhid);
1811 }
1812
1813 int
1814 carp_attach(struct ifaddr *ifa, int vhid)
1815 {
1816         struct ifnet *ifp = ifa->ifa_ifp;
1817         struct carp_if *cif = ifp->if_carp;
1818         struct carp_softc *sc;
1819         int index, error;
1820
1821         KASSERT(ifa->ifa_carp == NULL, ("%s: ifa %p attached", __func__, ifa));
1822
1823         switch (ifa->ifa_addr->sa_family) {
1824 #ifdef INET
1825         case AF_INET:
1826 #endif
1827 #ifdef INET6
1828         case AF_INET6:
1829 #endif
1830                 break;
1831         default:
1832                 return (EPROTOTYPE);
1833         }
1834
1835         sx_xlock(&carp_sx);
1836         if (ifp->if_carp == NULL) {
1837                 sx_xunlock(&carp_sx);
1838                 return (ENOPROTOOPT);
1839         }
1840
1841         IFNET_FOREACH_CARP(ifp, sc)
1842                 if (sc->sc_vhid == vhid)
1843                         break;
1844         if (sc == NULL) {
1845                 sx_xunlock(&carp_sx);
1846                 return (ENOENT);
1847         }
1848
1849         error = carp_multicast_setup(cif, ifa->ifa_addr->sa_family);
1850         if (error) {
1851                 CIF_FREE(cif);
1852                 sx_xunlock(&carp_sx);
1853                 return (error);
1854         }
1855
1856         index = sc->sc_naddrs + sc->sc_naddrs6 + 1;
1857         if (index > sc->sc_ifasiz / sizeof(struct ifaddr *))
1858                 carp_grow_ifas(sc);
1859
1860         switch (ifa->ifa_addr->sa_family) {
1861 #ifdef INET
1862         case AF_INET:
1863                 cif->cif_naddrs++;
1864                 sc->sc_naddrs++;
1865                 break;
1866 #endif
1867 #ifdef INET6
1868         case AF_INET6:
1869                 cif->cif_naddrs6++;
1870                 sc->sc_naddrs6++;
1871                 break;
1872 #endif
1873         }
1874
1875         ifa_ref(ifa);
1876
1877         CARP_LOCK(sc);
1878         sc->sc_ifas[index - 1] = ifa;
1879         ifa->ifa_carp = sc;
1880         carp_hmac_prepare(sc);
1881         carp_sc_state(sc);
1882         CARP_UNLOCK(sc);
1883
1884         sx_xunlock(&carp_sx);
1885
1886         return (0);
1887 }
1888
1889 void
1890 carp_detach(struct ifaddr *ifa, bool keep_cif)
1891 {
1892         struct ifnet *ifp = ifa->ifa_ifp;
1893         struct carp_if *cif = ifp->if_carp;
1894         struct carp_softc *sc = ifa->ifa_carp;
1895         int i, index;
1896
1897         KASSERT(sc != NULL, ("%s: %p not attached", __func__, ifa));
1898
1899         sx_xlock(&carp_sx);
1900
1901         CARP_LOCK(sc);
1902         /* Shift array. */
1903         index = sc->sc_naddrs + sc->sc_naddrs6;
1904         for (i = 0; i < index; i++)
1905                 if (sc->sc_ifas[i] == ifa)
1906                         break;
1907         KASSERT(i < index, ("%s: %p no backref", __func__, ifa));
1908         for (; i < index - 1; i++)
1909                 sc->sc_ifas[i] = sc->sc_ifas[i+1];
1910         sc->sc_ifas[index - 1] = NULL;
1911
1912         switch (ifa->ifa_addr->sa_family) {
1913 #ifdef INET
1914         case AF_INET:
1915                 cif->cif_naddrs--;
1916                 sc->sc_naddrs--;
1917                 break;
1918 #endif
1919 #ifdef INET6
1920         case AF_INET6:
1921                 cif->cif_naddrs6--;
1922                 sc->sc_naddrs6--;
1923                 break;
1924 #endif
1925         }
1926
1927         carp_ifa_delroute(ifa);
1928         carp_multicast_cleanup(cif, ifa->ifa_addr->sa_family);
1929
1930         ifa->ifa_carp = NULL;
1931         ifa_free(ifa);
1932
1933         carp_hmac_prepare(sc);
1934         carp_sc_state(sc);
1935
1936         if (!keep_cif && sc->sc_naddrs == 0 && sc->sc_naddrs6 == 0)
1937                 carp_destroy(sc);
1938         else
1939                 CARP_UNLOCK(sc);
1940
1941         if (!keep_cif)
1942                 CIF_FREE(cif);
1943
1944         sx_xunlock(&carp_sx);
1945 }
1946
1947 static void
1948 carp_set_state(struct carp_softc *sc, int state, const char *reason)
1949 {
1950
1951         CARP_LOCK_ASSERT(sc);
1952
1953         if (sc->sc_state != state) {
1954                 const char *carp_states[] = { CARP_STATES };
1955                 char subsys[IFNAMSIZ+5];
1956
1957                 snprintf(subsys, IFNAMSIZ+5, "%u@%s", sc->sc_vhid,
1958                     sc->sc_carpdev->if_xname);
1959
1960                 CARP_LOG("%s: %s -> %s (%s)\n", subsys,
1961                     carp_states[sc->sc_state], carp_states[state], reason);
1962
1963                 sc->sc_state = state;
1964
1965                 devctl_notify("CARP", subsys, carp_states[state], NULL);
1966         }
1967 }
1968
1969 static void
1970 carp_linkstate(struct ifnet *ifp)
1971 {
1972         struct carp_softc *sc;
1973
1974         CIF_LOCK(ifp->if_carp);
1975         IFNET_FOREACH_CARP(ifp, sc) {
1976                 CARP_LOCK(sc);
1977                 carp_sc_state(sc);
1978                 CARP_UNLOCK(sc);
1979         }
1980         CIF_UNLOCK(ifp->if_carp);
1981 }
1982
1983 static void
1984 carp_sc_state(struct carp_softc *sc)
1985 {
1986
1987         CARP_LOCK_ASSERT(sc);
1988
1989         if (sc->sc_carpdev->if_link_state != LINK_STATE_UP ||
1990             !(sc->sc_carpdev->if_flags & IFF_UP) ||
1991             !V_carp_allow) {
1992                 callout_stop(&sc->sc_ad_tmo);
1993 #ifdef INET
1994                 callout_stop(&sc->sc_md_tmo);
1995 #endif
1996 #ifdef INET6
1997                 callout_stop(&sc->sc_md6_tmo);
1998 #endif
1999                 carp_set_state(sc, INIT, "hardware interface down");
2000                 carp_setrun(sc, 0);
2001                 if (!sc->sc_suppress)
2002                         carp_demote_adj(V_carp_ifdown_adj, "interface down");
2003                 sc->sc_suppress = 1;
2004         } else {
2005                 carp_set_state(sc, INIT, "hardware interface up");
2006                 carp_setrun(sc, 0);
2007                 if (sc->sc_suppress)
2008                         carp_demote_adj(-V_carp_ifdown_adj, "interface up");
2009                 sc->sc_suppress = 0;
2010         }
2011 }
2012
2013 static void
2014 carp_demote_adj(int adj, char *reason)
2015 {
2016         atomic_add_int(&V_carp_demotion, adj);
2017         CARP_LOG("demoted by %d to %d (%s)\n", adj, V_carp_demotion, reason);
2018         taskqueue_enqueue(taskqueue_swi, &carp_sendall_task);
2019 }
2020
2021 static int
2022 carp_allow_sysctl(SYSCTL_HANDLER_ARGS)
2023 {
2024         int new, error;
2025         struct carp_softc *sc;
2026
2027         new = V_carp_allow;
2028         error = sysctl_handle_int(oidp, &new, 0, req);
2029         if (error || !req->newptr)
2030                 return (error);
2031
2032         if (V_carp_allow != new) {
2033                 V_carp_allow = new;
2034
2035                 mtx_lock(&carp_mtx);
2036                 LIST_FOREACH(sc, &carp_list, sc_next) {
2037                         CARP_LOCK(sc);
2038                         if (curvnet == sc->sc_carpdev->if_vnet)
2039                                 carp_sc_state(sc);
2040                         CARP_UNLOCK(sc);
2041                 }
2042                 mtx_unlock(&carp_mtx);
2043         }
2044
2045         return (0);
2046 }
2047
2048 static int
2049 carp_dscp_sysctl(SYSCTL_HANDLER_ARGS)
2050 {
2051         int new, error;
2052
2053         new = V_carp_dscp;
2054         error = sysctl_handle_int(oidp, &new, 0, req);
2055         if (error || !req->newptr)
2056                 return (error);
2057
2058         if (new < 0 || new > 63)
2059                 return (EINVAL);
2060
2061         V_carp_dscp = new;
2062
2063         return (0);
2064 }
2065
2066 static int
2067 carp_demote_adj_sysctl(SYSCTL_HANDLER_ARGS)
2068 {
2069         int new, error;
2070
2071         new = V_carp_demotion;
2072         error = sysctl_handle_int(oidp, &new, 0, req);
2073         if (error || !req->newptr)
2074                 return (error);
2075
2076         carp_demote_adj(new, "sysctl");
2077
2078         return (0);
2079 }
2080
2081 #ifdef INET
2082 extern  struct domain inetdomain;
2083 static struct protosw in_carp_protosw = {
2084         .pr_type =              SOCK_RAW,
2085         .pr_domain =            &inetdomain,
2086         .pr_protocol =          IPPROTO_CARP,
2087         .pr_flags =             PR_ATOMIC|PR_ADDR,
2088         .pr_input =             carp_input,
2089         .pr_output =            rip_output,
2090         .pr_ctloutput =         rip_ctloutput,
2091         .pr_usrreqs =           &rip_usrreqs
2092 };
2093 #endif
2094
2095 #ifdef INET6
2096 extern  struct domain inet6domain;
2097 static struct protosw in6_carp_protosw = {
2098         .pr_type =              SOCK_RAW,
2099         .pr_domain =            &inet6domain,
2100         .pr_protocol =          IPPROTO_CARP,
2101         .pr_flags =             PR_ATOMIC|PR_ADDR,
2102         .pr_input =             carp6_input,
2103         .pr_output =            rip6_output,
2104         .pr_ctloutput =         rip6_ctloutput,
2105         .pr_usrreqs =           &rip6_usrreqs
2106 };
2107 #endif
2108
2109 static void
2110 carp_mod_cleanup(void)
2111 {
2112
2113 #ifdef INET
2114         if (proto_reg[CARP_INET] == 0) {
2115                 (void)ipproto_unregister(IPPROTO_CARP);
2116                 pf_proto_unregister(PF_INET, IPPROTO_CARP, SOCK_RAW);
2117                 proto_reg[CARP_INET] = -1;
2118         }
2119         carp_iamatch_p = NULL;
2120 #endif
2121 #ifdef INET6
2122         if (proto_reg[CARP_INET6] == 0) {
2123                 (void)ip6proto_unregister(IPPROTO_CARP);
2124                 pf_proto_unregister(PF_INET6, IPPROTO_CARP, SOCK_RAW);
2125                 proto_reg[CARP_INET6] = -1;
2126         }
2127         carp_iamatch6_p = NULL;
2128         carp_macmatch6_p = NULL;
2129 #endif
2130         carp_ioctl_p = NULL;
2131         carp_attach_p = NULL;
2132         carp_detach_p = NULL;
2133         carp_get_vhid_p = NULL;
2134         carp_linkstate_p = NULL;
2135         carp_forus_p = NULL;
2136         carp_output_p = NULL;
2137         carp_demote_adj_p = NULL;
2138         carp_master_p = NULL;
2139         mtx_unlock(&carp_mtx);
2140         taskqueue_drain(taskqueue_swi, &carp_sendall_task);
2141         mtx_destroy(&carp_mtx);
2142         sx_destroy(&carp_sx);
2143 }
2144
2145 static int
2146 carp_mod_load(void)
2147 {
2148         int err;
2149
2150         mtx_init(&carp_mtx, "carp_mtx", NULL, MTX_DEF);
2151         sx_init(&carp_sx, "carp_sx");
2152         LIST_INIT(&carp_list);
2153         carp_get_vhid_p = carp_get_vhid;
2154         carp_forus_p = carp_forus;
2155         carp_output_p = carp_output;
2156         carp_linkstate_p = carp_linkstate;
2157         carp_ioctl_p = carp_ioctl;
2158         carp_attach_p = carp_attach;
2159         carp_detach_p = carp_detach;
2160         carp_demote_adj_p = carp_demote_adj;
2161         carp_master_p = carp_master;
2162 #ifdef INET6
2163         carp_iamatch6_p = carp_iamatch6;
2164         carp_macmatch6_p = carp_macmatch6;
2165         proto_reg[CARP_INET6] = pf_proto_register(PF_INET6,
2166             (struct protosw *)&in6_carp_protosw);
2167         if (proto_reg[CARP_INET6]) {
2168                 printf("carp: error %d attaching to PF_INET6\n",
2169                     proto_reg[CARP_INET6]);
2170                 carp_mod_cleanup();
2171                 return (proto_reg[CARP_INET6]);
2172         }
2173         err = ip6proto_register(IPPROTO_CARP);
2174         if (err) {
2175                 printf("carp: error %d registering with INET6\n", err);
2176                 carp_mod_cleanup();
2177                 return (err);
2178         }
2179 #endif
2180 #ifdef INET
2181         carp_iamatch_p = carp_iamatch;
2182         proto_reg[CARP_INET] = pf_proto_register(PF_INET, &in_carp_protosw);
2183         if (proto_reg[CARP_INET]) {
2184                 printf("carp: error %d attaching to PF_INET\n",
2185                     proto_reg[CARP_INET]);
2186                 carp_mod_cleanup();
2187                 return (proto_reg[CARP_INET]);
2188         }
2189         err = ipproto_register(IPPROTO_CARP);
2190         if (err) {
2191                 printf("carp: error %d registering with INET\n", err);
2192                 carp_mod_cleanup();
2193                 return (err);
2194         }
2195 #endif
2196         return (0);
2197 }
2198
2199 static int
2200 carp_modevent(module_t mod, int type, void *data)
2201 {
2202         switch (type) {
2203         case MOD_LOAD:
2204                 return carp_mod_load();
2205                 /* NOTREACHED */
2206         case MOD_UNLOAD:
2207                 mtx_lock(&carp_mtx);
2208                 if (LIST_EMPTY(&carp_list))
2209                         carp_mod_cleanup();
2210                 else {
2211                         mtx_unlock(&carp_mtx);
2212                         return (EBUSY);
2213                 }
2214                 break;
2215
2216         default:
2217                 return (EINVAL);
2218         }
2219
2220         return (0);
2221 }
2222
2223 static moduledata_t carp_mod = {
2224         "carp",
2225         carp_modevent,
2226         0
2227 };
2228
2229 DECLARE_MODULE(carp, carp_mod, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY);