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