xref: /freebsd/sys/netinet6/in6.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
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  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	$KAME: in6.c,v 1.259 2002/01/21 11:37:50 keiichi Exp $
32  */
33 
34 /*-
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)in.c	8.2 (Berkeley) 11/15/93
63  */
64 
65 #include <sys/cdefs.h>
66 __FBSDID("$FreeBSD$");
67 
68 #include "opt_inet.h"
69 #include "opt_inet6.h"
70 
71 #include <sys/param.h>
72 #include <sys/eventhandler.h>
73 #include <sys/errno.h>
74 #include <sys/jail.h>
75 #include <sys/malloc.h>
76 #include <sys/socket.h>
77 #include <sys/socketvar.h>
78 #include <sys/sockio.h>
79 #include <sys/systm.h>
80 #include <sys/priv.h>
81 #include <sys/proc.h>
82 #include <sys/protosw.h>
83 #include <sys/time.h>
84 #include <sys/kernel.h>
85 #include <sys/lock.h>
86 #include <sys/rmlock.h>
87 #include <sys/syslog.h>
88 
89 #include <net/if.h>
90 #include <net/if_var.h>
91 #include <net/if_types.h>
92 #include <net/route.h>
93 #include <net/if_dl.h>
94 #include <net/vnet.h>
95 
96 #include <netinet/in.h>
97 #include <netinet/in_var.h>
98 #include <net/if_llatbl.h>
99 #include <netinet/if_ether.h>
100 #include <netinet/in_systm.h>
101 #include <netinet/ip.h>
102 #include <netinet/in_pcb.h>
103 #include <netinet/ip_carp.h>
104 
105 #include <netinet/ip6.h>
106 #include <netinet6/ip6_var.h>
107 #include <netinet6/nd6.h>
108 #include <netinet6/mld6_var.h>
109 #include <netinet6/ip6_mroute.h>
110 #include <netinet6/in6_ifattach.h>
111 #include <netinet6/scope6_var.h>
112 #include <netinet6/in6_fib.h>
113 #include <netinet6/in6_pcb.h>
114 
115 
116 /*
117  * struct in6_ifreq and struct ifreq must be type punnable for common members
118  * of ifr_ifru to allow accessors to be shared.
119  */
120 _Static_assert(offsetof(struct in6_ifreq, ifr_ifru) ==
121     offsetof(struct ifreq, ifr_ifru),
122     "struct in6_ifreq and struct ifreq are not type punnable");
123 
124 VNET_DECLARE(int, icmp6_nodeinfo_oldmcprefix);
125 #define V_icmp6_nodeinfo_oldmcprefix	VNET(icmp6_nodeinfo_oldmcprefix)
126 
127 /*
128  * Definitions of some costant IP6 addresses.
129  */
130 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
131 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
132 const struct in6_addr in6addr_nodelocal_allnodes =
133 	IN6ADDR_NODELOCAL_ALLNODES_INIT;
134 const struct in6_addr in6addr_linklocal_allnodes =
135 	IN6ADDR_LINKLOCAL_ALLNODES_INIT;
136 const struct in6_addr in6addr_linklocal_allrouters =
137 	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
138 const struct in6_addr in6addr_linklocal_allv2routers =
139 	IN6ADDR_LINKLOCAL_ALLV2ROUTERS_INIT;
140 
141 const struct in6_addr in6mask0 = IN6MASK0;
142 const struct in6_addr in6mask32 = IN6MASK32;
143 const struct in6_addr in6mask64 = IN6MASK64;
144 const struct in6_addr in6mask96 = IN6MASK96;
145 const struct in6_addr in6mask128 = IN6MASK128;
146 
147 const struct sockaddr_in6 sa6_any =
148 	{ sizeof(sa6_any), AF_INET6, 0, 0, IN6ADDR_ANY_INIT, 0 };
149 
150 static int in6_notify_ifa(struct ifnet *, struct in6_ifaddr *,
151 	struct in6_aliasreq *, int);
152 static void in6_unlink_ifa(struct in6_ifaddr *, struct ifnet *);
153 
154 static int in6_validate_ifra(struct ifnet *, struct in6_aliasreq *,
155     struct in6_ifaddr *, int);
156 static struct in6_ifaddr *in6_alloc_ifa(struct ifnet *,
157     struct in6_aliasreq *, int flags);
158 static int in6_update_ifa_internal(struct ifnet *, struct in6_aliasreq *,
159     struct in6_ifaddr *, int, int);
160 static int in6_broadcast_ifa(struct ifnet *, struct in6_aliasreq *,
161     struct in6_ifaddr *, int);
162 
163 #define ifa2ia6(ifa)	((struct in6_ifaddr *)(ifa))
164 #define ia62ifa(ia6)	(&((ia6)->ia_ifa))
165 
166 
167 void
168 in6_newaddrmsg(struct in6_ifaddr *ia, int cmd)
169 {
170 	struct sockaddr_dl gateway;
171 	struct sockaddr_in6 mask, addr;
172 	struct rtentry rt;
173 	int fibnum;
174 
175 	/*
176 	 * initialize for rtmsg generation
177 	 */
178 	bzero(&gateway, sizeof(gateway));
179 	gateway.sdl_len = sizeof(gateway);
180 	gateway.sdl_family = AF_LINK;
181 
182 	bzero(&rt, sizeof(rt));
183 	rt.rt_gateway = (struct sockaddr *)&gateway;
184 	memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
185 	memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
186 	rt_mask(&rt) = (struct sockaddr *)&mask;
187 	rt_key(&rt) = (struct sockaddr *)&addr;
188 	rt.rt_flags = RTF_HOST | RTF_STATIC;
189 	if (cmd == RTM_ADD)
190 		rt.rt_flags |= RTF_UP;
191 	fibnum = V_rt_add_addr_allfibs ? RT_ALL_FIBS : ia62ifa(ia)->ifa_ifp->if_fib;
192 	/* Announce arrival of local address to this FIB. */
193 	rt_newaddrmsg_fib(cmd, &ia->ia_ifa, 0, &rt, fibnum);
194 }
195 
196 int
197 in6_mask2len(struct in6_addr *mask, u_char *lim0)
198 {
199 	int x = 0, y;
200 	u_char *lim = lim0, *p;
201 
202 	/* ignore the scope_id part */
203 	if (lim0 == NULL || lim0 - (u_char *)mask > sizeof(*mask))
204 		lim = (u_char *)mask + sizeof(*mask);
205 	for (p = (u_char *)mask; p < lim; x++, p++) {
206 		if (*p != 0xff)
207 			break;
208 	}
209 	y = 0;
210 	if (p < lim) {
211 		for (y = 0; y < 8; y++) {
212 			if ((*p & (0x80 >> y)) == 0)
213 				break;
214 		}
215 	}
216 
217 	/*
218 	 * when the limit pointer is given, do a stricter check on the
219 	 * remaining bits.
220 	 */
221 	if (p < lim) {
222 		if (y != 0 && (*p & (0x00ff >> y)) != 0)
223 			return (-1);
224 		for (p = p + 1; p < lim; p++)
225 			if (*p != 0)
226 				return (-1);
227 	}
228 
229 	return x * 8 + y;
230 }
231 
232 #ifdef COMPAT_FREEBSD32
233 struct in6_ndifreq32 {
234 	char ifname[IFNAMSIZ];
235 	uint32_t ifindex;
236 };
237 #define	SIOCGDEFIFACE32_IN6	_IOWR('i', 86, struct in6_ndifreq32)
238 #endif
239 
240 int
241 in6_control(struct socket *so, u_long cmd, caddr_t data,
242     struct ifnet *ifp, struct thread *td)
243 {
244 	struct	in6_ifreq *ifr = (struct in6_ifreq *)data;
245 	struct	in6_ifaddr *ia = NULL;
246 	struct	in6_aliasreq *ifra = (struct in6_aliasreq *)data;
247 	struct sockaddr_in6 *sa6;
248 	int carp_attached = 0;
249 	int error;
250 	u_long ocmd = cmd;
251 
252 	/*
253 	 * Compat to make pre-10.x ifconfig(8) operable.
254 	 */
255 	if (cmd == OSIOCAIFADDR_IN6)
256 		cmd = SIOCAIFADDR_IN6;
257 
258 	switch (cmd) {
259 	case SIOCGETSGCNT_IN6:
260 	case SIOCGETMIFCNT_IN6:
261 		/*
262 		 * XXX mrt_ioctl has a 3rd, unused, FIB argument in route.c.
263 		 * We cannot see how that would be needed, so do not adjust the
264 		 * KPI blindly; more likely should clean up the IPv4 variant.
265 		 */
266 		return (mrt6_ioctl ? mrt6_ioctl(cmd, data) : EOPNOTSUPP);
267 	}
268 
269 	switch (cmd) {
270 	case SIOCAADDRCTL_POLICY:
271 	case SIOCDADDRCTL_POLICY:
272 		if (td != NULL) {
273 			error = priv_check(td, PRIV_NETINET_ADDRCTRL6);
274 			if (error)
275 				return (error);
276 		}
277 		return (in6_src_ioctl(cmd, data));
278 	}
279 
280 	if (ifp == NULL)
281 		return (EOPNOTSUPP);
282 
283 	switch (cmd) {
284 	case SIOCSNDFLUSH_IN6:
285 	case SIOCSPFXFLUSH_IN6:
286 	case SIOCSRTRFLUSH_IN6:
287 	case SIOCSDEFIFACE_IN6:
288 	case SIOCSIFINFO_FLAGS:
289 	case SIOCSIFINFO_IN6:
290 		if (td != NULL) {
291 			error = priv_check(td, PRIV_NETINET_ND6);
292 			if (error)
293 				return (error);
294 		}
295 		/* FALLTHROUGH */
296 	case OSIOCGIFINFO_IN6:
297 	case SIOCGIFINFO_IN6:
298 	case SIOCGNBRINFO_IN6:
299 	case SIOCGDEFIFACE_IN6:
300 		return (nd6_ioctl(cmd, data, ifp));
301 
302 #ifdef COMPAT_FREEBSD32
303 	case SIOCGDEFIFACE32_IN6:
304 		{
305 			struct in6_ndifreq ndif;
306 			struct in6_ndifreq32 *ndif32;
307 
308 			error = nd6_ioctl(SIOCGDEFIFACE_IN6, (caddr_t)&ndif,
309 			    ifp);
310 			if (error)
311 				return (error);
312 			ndif32 = (struct in6_ndifreq32 *)data;
313 			ndif32->ifindex = ndif.ifindex;
314 			return (0);
315 		}
316 #endif
317 	}
318 
319 	switch (cmd) {
320 	case SIOCSIFPREFIX_IN6:
321 	case SIOCDIFPREFIX_IN6:
322 	case SIOCAIFPREFIX_IN6:
323 	case SIOCCIFPREFIX_IN6:
324 	case SIOCSGIFPREFIX_IN6:
325 	case SIOCGIFPREFIX_IN6:
326 		log(LOG_NOTICE,
327 		    "prefix ioctls are now invalidated. "
328 		    "please use ifconfig.\n");
329 		return (EOPNOTSUPP);
330 	}
331 
332 	switch (cmd) {
333 	case SIOCSSCOPE6:
334 		if (td != NULL) {
335 			error = priv_check(td, PRIV_NETINET_SCOPE6);
336 			if (error)
337 				return (error);
338 		}
339 		/* FALLTHROUGH */
340 	case SIOCGSCOPE6:
341 	case SIOCGSCOPE6DEF:
342 		return (scope6_ioctl(cmd, data, ifp));
343 	}
344 
345 	/*
346 	 * Find address for this interface, if it exists.
347 	 *
348 	 * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
349 	 * only, and used the first interface address as the target of other
350 	 * operations (without checking ifra_addr).  This was because netinet
351 	 * code/API assumed at most 1 interface address per interface.
352 	 * Since IPv6 allows a node to assign multiple addresses
353 	 * on a single interface, we almost always look and check the
354 	 * presence of ifra_addr, and reject invalid ones here.
355 	 * It also decreases duplicated code among SIOC*_IN6 operations.
356 	 */
357 	switch (cmd) {
358 	case SIOCAIFADDR_IN6:
359 	case SIOCSIFPHYADDR_IN6:
360 		sa6 = &ifra->ifra_addr;
361 		break;
362 	case SIOCSIFADDR_IN6:
363 	case SIOCGIFADDR_IN6:
364 	case SIOCSIFDSTADDR_IN6:
365 	case SIOCSIFNETMASK_IN6:
366 	case SIOCGIFDSTADDR_IN6:
367 	case SIOCGIFNETMASK_IN6:
368 	case SIOCDIFADDR_IN6:
369 	case SIOCGIFPSRCADDR_IN6:
370 	case SIOCGIFPDSTADDR_IN6:
371 	case SIOCGIFAFLAG_IN6:
372 	case SIOCSNDFLUSH_IN6:
373 	case SIOCSPFXFLUSH_IN6:
374 	case SIOCSRTRFLUSH_IN6:
375 	case SIOCGIFALIFETIME_IN6:
376 	case SIOCGIFSTAT_IN6:
377 	case SIOCGIFSTAT_ICMP6:
378 		sa6 = &ifr->ifr_addr;
379 		break;
380 	case SIOCSIFADDR:
381 	case SIOCSIFBRDADDR:
382 	case SIOCSIFDSTADDR:
383 	case SIOCSIFNETMASK:
384 		/*
385 		 * Although we should pass any non-INET6 ioctl requests
386 		 * down to driver, we filter some legacy INET requests.
387 		 * Drivers trust SIOCSIFADDR et al to come from an already
388 		 * privileged layer, and do not perform any credentials
389 		 * checks or input validation.
390 		 */
391 		return (EINVAL);
392 	default:
393 		sa6 = NULL;
394 		break;
395 	}
396 	if (sa6 && sa6->sin6_family == AF_INET6) {
397 		if (sa6->sin6_scope_id != 0)
398 			error = sa6_embedscope(sa6, 0);
399 		else
400 			error = in6_setscope(&sa6->sin6_addr, ifp, NULL);
401 		if (error != 0)
402 			return (error);
403 		if (td != NULL && (error = prison_check_ip6(td->td_ucred,
404 		    &sa6->sin6_addr)) != 0)
405 			return (error);
406 		ia = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
407 	} else
408 		ia = NULL;
409 
410 	switch (cmd) {
411 	case SIOCSIFADDR_IN6:
412 	case SIOCSIFDSTADDR_IN6:
413 	case SIOCSIFNETMASK_IN6:
414 		/*
415 		 * Since IPv6 allows a node to assign multiple addresses
416 		 * on a single interface, SIOCSIFxxx ioctls are deprecated.
417 		 */
418 		/* we decided to obsolete this command (20000704) */
419 		error = EINVAL;
420 		goto out;
421 
422 	case SIOCDIFADDR_IN6:
423 		/*
424 		 * for IPv4, we look for existing in_ifaddr here to allow
425 		 * "ifconfig if0 delete" to remove the first IPv4 address on
426 		 * the interface.  For IPv6, as the spec allows multiple
427 		 * interface address from the day one, we consider "remove the
428 		 * first one" semantics to be not preferable.
429 		 */
430 		if (ia == NULL) {
431 			error = EADDRNOTAVAIL;
432 			goto out;
433 		}
434 		/* FALLTHROUGH */
435 	case SIOCAIFADDR_IN6:
436 		/*
437 		 * We always require users to specify a valid IPv6 address for
438 		 * the corresponding operation.
439 		 */
440 		if (ifra->ifra_addr.sin6_family != AF_INET6 ||
441 		    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6)) {
442 			error = EAFNOSUPPORT;
443 			goto out;
444 		}
445 
446 		if (td != NULL) {
447 			error = priv_check(td, (cmd == SIOCDIFADDR_IN6) ?
448 			    PRIV_NET_DELIFADDR : PRIV_NET_ADDIFADDR);
449 			if (error)
450 				goto out;
451 		}
452 		/* FALLTHROUGH */
453 	case SIOCGIFSTAT_IN6:
454 	case SIOCGIFSTAT_ICMP6:
455 		if (ifp->if_afdata[AF_INET6] == NULL) {
456 			error = EPFNOSUPPORT;
457 			goto out;
458 		}
459 		break;
460 
461 	case SIOCGIFADDR_IN6:
462 		/* This interface is basically deprecated. use SIOCGIFCONF. */
463 		/* FALLTHROUGH */
464 	case SIOCGIFAFLAG_IN6:
465 	case SIOCGIFNETMASK_IN6:
466 	case SIOCGIFDSTADDR_IN6:
467 	case SIOCGIFALIFETIME_IN6:
468 		/* must think again about its semantics */
469 		if (ia == NULL) {
470 			error = EADDRNOTAVAIL;
471 			goto out;
472 		}
473 		break;
474 	}
475 
476 	switch (cmd) {
477 	case SIOCGIFADDR_IN6:
478 		ifr->ifr_addr = ia->ia_addr;
479 		if ((error = sa6_recoverscope(&ifr->ifr_addr)) != 0)
480 			goto out;
481 		break;
482 
483 	case SIOCGIFDSTADDR_IN6:
484 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
485 			error = EINVAL;
486 			goto out;
487 		}
488 		ifr->ifr_dstaddr = ia->ia_dstaddr;
489 		if ((error = sa6_recoverscope(&ifr->ifr_dstaddr)) != 0)
490 			goto out;
491 		break;
492 
493 	case SIOCGIFNETMASK_IN6:
494 		ifr->ifr_addr = ia->ia_prefixmask;
495 		break;
496 
497 	case SIOCGIFAFLAG_IN6:
498 		ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
499 		break;
500 
501 	case SIOCGIFSTAT_IN6:
502 		COUNTER_ARRAY_COPY(((struct in6_ifextra *)
503 		    ifp->if_afdata[AF_INET6])->in6_ifstat,
504 		    &ifr->ifr_ifru.ifru_stat,
505 		    sizeof(struct in6_ifstat) / sizeof(uint64_t));
506 		break;
507 
508 	case SIOCGIFSTAT_ICMP6:
509 		COUNTER_ARRAY_COPY(((struct in6_ifextra *)
510 		    ifp->if_afdata[AF_INET6])->icmp6_ifstat,
511 		    &ifr->ifr_ifru.ifru_icmp6stat,
512 		    sizeof(struct icmp6_ifstat) / sizeof(uint64_t));
513 		break;
514 
515 	case SIOCGIFALIFETIME_IN6:
516 		ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
517 		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
518 			time_t maxexpire;
519 			struct in6_addrlifetime *retlt =
520 			    &ifr->ifr_ifru.ifru_lifetime;
521 
522 			/*
523 			 * XXX: adjust expiration time assuming time_t is
524 			 * signed.
525 			 */
526 			maxexpire = (-1) &
527 			    ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
528 			if (ia->ia6_lifetime.ia6t_vltime <
529 			    maxexpire - ia->ia6_updatetime) {
530 				retlt->ia6t_expire = ia->ia6_updatetime +
531 				    ia->ia6_lifetime.ia6t_vltime;
532 			} else
533 				retlt->ia6t_expire = maxexpire;
534 		}
535 		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
536 			time_t maxexpire;
537 			struct in6_addrlifetime *retlt =
538 			    &ifr->ifr_ifru.ifru_lifetime;
539 
540 			/*
541 			 * XXX: adjust expiration time assuming time_t is
542 			 * signed.
543 			 */
544 			maxexpire = (-1) &
545 			    ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
546 			if (ia->ia6_lifetime.ia6t_pltime <
547 			    maxexpire - ia->ia6_updatetime) {
548 				retlt->ia6t_preferred = ia->ia6_updatetime +
549 				    ia->ia6_lifetime.ia6t_pltime;
550 			} else
551 				retlt->ia6t_preferred = maxexpire;
552 		}
553 		break;
554 
555 	case SIOCAIFADDR_IN6:
556 	{
557 		struct nd_prefixctl pr0;
558 		struct nd_prefix *pr;
559 
560 		/*
561 		 * first, make or update the interface address structure,
562 		 * and link it to the list.
563 		 */
564 		if ((error = in6_update_ifa(ifp, ifra, ia, 0)) != 0)
565 			goto out;
566 		if (ia != NULL) {
567 			if (ia->ia_ifa.ifa_carp)
568 				(*carp_detach_p)(&ia->ia_ifa, true);
569 			ifa_free(&ia->ia_ifa);
570 		}
571 		if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
572 		    == NULL) {
573 			/*
574 			 * this can happen when the user specify the 0 valid
575 			 * lifetime.
576 			 */
577 			break;
578 		}
579 
580 		if (cmd == ocmd && ifra->ifra_vhid > 0) {
581 			if (carp_attach_p != NULL)
582 				error = (*carp_attach_p)(&ia->ia_ifa,
583 				    ifra->ifra_vhid);
584 			else
585 				error = EPROTONOSUPPORT;
586 			if (error)
587 				goto out;
588 			else
589 				carp_attached = 1;
590 		}
591 
592 		/*
593 		 * then, make the prefix on-link on the interface.
594 		 * XXX: we'd rather create the prefix before the address, but
595 		 * we need at least one address to install the corresponding
596 		 * interface route, so we configure the address first.
597 		 */
598 
599 		/*
600 		 * convert mask to prefix length (prefixmask has already
601 		 * been validated in in6_update_ifa().
602 		 */
603 		bzero(&pr0, sizeof(pr0));
604 		pr0.ndpr_ifp = ifp;
605 		pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
606 		    NULL);
607 		if (pr0.ndpr_plen == 128) {
608 			/* we don't need to install a host route. */
609 			goto aifaddr_out;
610 		}
611 		pr0.ndpr_prefix = ifra->ifra_addr;
612 		/* apply the mask for safety. */
613 		IN6_MASK_ADDR(&pr0.ndpr_prefix.sin6_addr,
614 		    &ifra->ifra_prefixmask.sin6_addr);
615 
616 		/*
617 		 * XXX: since we don't have an API to set prefix (not address)
618 		 * lifetimes, we just use the same lifetimes as addresses.
619 		 * The (temporarily) installed lifetimes can be overridden by
620 		 * later advertised RAs (when accept_rtadv is non 0), which is
621 		 * an intended behavior.
622 		 */
623 		pr0.ndpr_raf_onlink = 1; /* should be configurable? */
624 		pr0.ndpr_raf_auto =
625 		    ((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
626 		pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
627 		pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
628 
629 		/* add the prefix if not yet. */
630 		if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
631 			/*
632 			 * nd6_prelist_add will install the corresponding
633 			 * interface route.
634 			 */
635 			if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0) {
636 				if (carp_attached)
637 					(*carp_detach_p)(&ia->ia_ifa, false);
638 				goto out;
639 			}
640 		}
641 
642 		/* relate the address to the prefix */
643 		if (ia->ia6_ndpr == NULL) {
644 			ia->ia6_ndpr = pr;
645 			pr->ndpr_addrcnt++;
646 
647 			/*
648 			 * If this is the first autoconf address from the
649 			 * prefix, create a temporary address as well
650 			 * (when required).
651 			 */
652 			if ((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
653 			    V_ip6_use_tempaddr && pr->ndpr_addrcnt == 1) {
654 				int e;
655 				if ((e = in6_tmpifadd(ia, 1, 0)) != 0) {
656 					log(LOG_NOTICE, "in6_control: failed "
657 					    "to create a temporary address, "
658 					    "errno=%d\n", e);
659 				}
660 			}
661 		}
662 		nd6_prefix_rele(pr);
663 
664 		/*
665 		 * this might affect the status of autoconfigured addresses,
666 		 * that is, this address might make other addresses detached.
667 		 */
668 		pfxlist_onlink_check();
669 
670 aifaddr_out:
671 		/*
672 		 * Try to clear the flag when a new IPv6 address is added
673 		 * onto an IFDISABLED interface and it succeeds.
674 		 */
675 		if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) {
676 			struct in6_ndireq nd;
677 
678 			memset(&nd, 0, sizeof(nd));
679 			nd.ndi.flags = ND_IFINFO(ifp)->flags;
680 			nd.ndi.flags &= ~ND6_IFF_IFDISABLED;
681 			if (nd6_ioctl(SIOCSIFINFO_FLAGS, (caddr_t)&nd, ifp) < 0)
682 				log(LOG_NOTICE, "SIOCAIFADDR_IN6: "
683 				    "SIOCSIFINFO_FLAGS for -ifdisabled "
684 				    "failed.");
685 			/*
686 			 * Ignore failure of clearing the flag intentionally.
687 			 * The failure means address duplication was detected.
688 			 */
689 		}
690 		break;
691 	}
692 
693 	case SIOCDIFADDR_IN6:
694 	{
695 		struct nd_prefix *pr;
696 
697 		/*
698 		 * If the address being deleted is the only one that owns
699 		 * the corresponding prefix, expire the prefix as well.
700 		 * XXX: theoretically, we don't have to worry about such
701 		 * relationship, since we separate the address management
702 		 * and the prefix management.  We do this, however, to provide
703 		 * as much backward compatibility as possible in terms of
704 		 * the ioctl operation.
705 		 * Note that in6_purgeaddr() will decrement ndpr_addrcnt.
706 		 */
707 		pr = ia->ia6_ndpr;
708 		in6_purgeaddr(&ia->ia_ifa);
709 		if (pr != NULL && pr->ndpr_addrcnt == 0) {
710 			ND6_WLOCK();
711 			nd6_prefix_unlink(pr, NULL);
712 			ND6_WUNLOCK();
713 			nd6_prefix_del(pr);
714 		}
715 		EVENTHANDLER_INVOKE(ifaddr_event_ext, ifp, &ia->ia_ifa,
716 		    IFADDR_EVENT_DEL);
717 		break;
718 	}
719 
720 	default:
721 		if (ifp->if_ioctl == NULL) {
722 			error = EOPNOTSUPP;
723 			goto out;
724 		}
725 		error = (*ifp->if_ioctl)(ifp, cmd, data);
726 		goto out;
727 	}
728 
729 	error = 0;
730 out:
731 	if (ia != NULL)
732 		ifa_free(&ia->ia_ifa);
733 	return (error);
734 }
735 
736 
737 static struct in6_multi_mship *
738 in6_joingroup_legacy(struct ifnet *ifp, const struct in6_addr *mcaddr,
739     int *errorp, int delay)
740 {
741 	struct in6_multi_mship *imm;
742 	int error;
743 
744 	imm = malloc(sizeof(*imm), M_IP6MADDR, M_NOWAIT);
745 	if (imm == NULL) {
746 		*errorp = ENOBUFS;
747 		return (NULL);
748 	}
749 
750 	delay = (delay * PR_FASTHZ) / hz;
751 
752 	error = in6_joingroup(ifp, mcaddr, NULL, &imm->i6mm_maddr, delay);
753 	if (error) {
754 		*errorp = error;
755 		free(imm, M_IP6MADDR);
756 		return (NULL);
757 	}
758 
759 	return (imm);
760 }
761 /*
762  * Join necessary multicast groups.  Factored out from in6_update_ifa().
763  * This entire work should only be done once, for the default FIB.
764  */
765 static int
766 in6_update_ifa_join_mc(struct ifnet *ifp, struct in6_aliasreq *ifra,
767     struct in6_ifaddr *ia, int flags, struct in6_multi **in6m_sol)
768 {
769 	char ip6buf[INET6_ADDRSTRLEN];
770 	struct in6_addr mltaddr;
771 	struct in6_multi_mship *imm;
772 	int delay, error;
773 
774 	KASSERT(in6m_sol != NULL, ("%s: in6m_sol is NULL", __func__));
775 
776 	/* Join solicited multicast addr for new host id. */
777 	bzero(&mltaddr, sizeof(struct in6_addr));
778 	mltaddr.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
779 	mltaddr.s6_addr32[2] = htonl(1);
780 	mltaddr.s6_addr32[3] = ifra->ifra_addr.sin6_addr.s6_addr32[3];
781 	mltaddr.s6_addr8[12] = 0xff;
782 	if ((error = in6_setscope(&mltaddr, ifp, NULL)) != 0) {
783 		/* XXX: should not happen */
784 		log(LOG_ERR, "%s: in6_setscope failed\n", __func__);
785 		goto cleanup;
786 	}
787 	delay = error = 0;
788 	if ((flags & IN6_IFAUPDATE_DADDELAY)) {
789 		/*
790 		 * We need a random delay for DAD on the address being
791 		 * configured.  It also means delaying transmission of the
792 		 * corresponding MLD report to avoid report collision.
793 		 * [RFC 4861, Section 6.3.7]
794 		 */
795 		delay = arc4random() % (MAX_RTR_SOLICITATION_DELAY * hz);
796 	}
797 	imm = in6_joingroup_legacy(ifp, &mltaddr, &error, delay);
798 	if (imm == NULL) {
799 		nd6log((LOG_WARNING, "%s: in6_joingroup failed for %s on %s "
800 		    "(errno=%d)\n", __func__, ip6_sprintf(ip6buf, &mltaddr),
801 		    if_name(ifp), error));
802 		goto cleanup;
803 	}
804 	LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
805 	*in6m_sol = imm->i6mm_maddr;
806 
807 	/*
808 	 * Join link-local all-nodes address.
809 	 */
810 	mltaddr = in6addr_linklocal_allnodes;
811 	if ((error = in6_setscope(&mltaddr, ifp, NULL)) != 0)
812 		goto cleanup; /* XXX: should not fail */
813 
814 	imm = in6_joingroup_legacy(ifp, &mltaddr, &error, 0);
815 	if (imm == NULL) {
816 		nd6log((LOG_WARNING, "%s: in6_joingroup failed for %s on %s "
817 		    "(errno=%d)\n", __func__, ip6_sprintf(ip6buf, &mltaddr),
818 		    if_name(ifp), error));
819 		goto cleanup;
820 	}
821 	LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
822 
823 	/*
824 	 * Join node information group address.
825 	 */
826 	delay = 0;
827 	if ((flags & IN6_IFAUPDATE_DADDELAY)) {
828 		/*
829 		 * The spec does not say anything about delay for this group,
830 		 * but the same logic should apply.
831 		 */
832 		delay = arc4random() % (MAX_RTR_SOLICITATION_DELAY * hz);
833 	}
834 	if (in6_nigroup(ifp, NULL, -1, &mltaddr) == 0) {
835 		/* XXX jinmei */
836 		imm = in6_joingroup_legacy(ifp, &mltaddr, &error, delay);
837 		if (imm == NULL)
838 			nd6log((LOG_WARNING,
839 			    "%s: in6_joingroup failed for %s on %s "
840 			    "(errno=%d)\n", __func__, ip6_sprintf(ip6buf,
841 			    &mltaddr), if_name(ifp), error));
842 			/* XXX not very fatal, go on... */
843 		else
844 			LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
845 	}
846 	if (V_icmp6_nodeinfo_oldmcprefix &&
847 	    in6_nigroup_oldmcprefix(ifp, NULL, -1, &mltaddr) == 0) {
848 		imm = in6_joingroup_legacy(ifp, &mltaddr, &error, delay);
849 		if (imm == NULL)
850 			nd6log((LOG_WARNING,
851 			    "%s: in6_joingroup failed for %s on %s "
852 			    "(errno=%d)\n", __func__, ip6_sprintf(ip6buf,
853 			    &mltaddr), if_name(ifp), error));
854 			/* XXX not very fatal, go on... */
855 		else
856 			LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
857 	}
858 
859 	/*
860 	 * Join interface-local all-nodes address.
861 	 * (ff01::1%ifN, and ff01::%ifN/32)
862 	 */
863 	mltaddr = in6addr_nodelocal_allnodes;
864 	if ((error = in6_setscope(&mltaddr, ifp, NULL)) != 0)
865 		goto cleanup; /* XXX: should not fail */
866 
867 	imm = in6_joingroup_legacy(ifp, &mltaddr, &error, 0);
868 	if (imm == NULL) {
869 		nd6log((LOG_WARNING, "%s: in6_joingroup failed for %s on %s "
870 		    "(errno=%d)\n", __func__, ip6_sprintf(ip6buf,
871 		    &mltaddr), if_name(ifp), error));
872 		goto cleanup;
873 	}
874 	LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
875 
876 cleanup:
877 	return (error);
878 }
879 
880 /*
881  * Update parameters of an IPv6 interface address.
882  * If necessary, a new entry is created and linked into address chains.
883  * This function is separated from in6_control().
884  */
885 int
886 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
887     struct in6_ifaddr *ia, int flags)
888 {
889 	int error, hostIsNew = 0;
890 
891 	if ((error = in6_validate_ifra(ifp, ifra, ia, flags)) != 0)
892 		return (error);
893 
894 	if (ia == NULL) {
895 		hostIsNew = 1;
896 		if ((ia = in6_alloc_ifa(ifp, ifra, flags)) == NULL)
897 			return (ENOBUFS);
898 	}
899 
900 	error = in6_update_ifa_internal(ifp, ifra, ia, hostIsNew, flags);
901 	if (error != 0) {
902 		if (hostIsNew != 0) {
903 			in6_unlink_ifa(ia, ifp);
904 			ifa_free(&ia->ia_ifa);
905 		}
906 		return (error);
907 	}
908 
909 	if (hostIsNew)
910 		error = in6_broadcast_ifa(ifp, ifra, ia, flags);
911 
912 	return (error);
913 }
914 
915 /*
916  * Fill in basic IPv6 address request info.
917  */
918 void
919 in6_prepare_ifra(struct in6_aliasreq *ifra, const struct in6_addr *addr,
920     const struct in6_addr *mask)
921 {
922 
923 	memset(ifra, 0, sizeof(struct in6_aliasreq));
924 
925 	ifra->ifra_addr.sin6_family = AF_INET6;
926 	ifra->ifra_addr.sin6_len = sizeof(struct sockaddr_in6);
927 	if (addr != NULL)
928 		ifra->ifra_addr.sin6_addr = *addr;
929 
930 	ifra->ifra_prefixmask.sin6_family = AF_INET6;
931 	ifra->ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
932 	if (mask != NULL)
933 		ifra->ifra_prefixmask.sin6_addr = *mask;
934 }
935 
936 static int
937 in6_validate_ifra(struct ifnet *ifp, struct in6_aliasreq *ifra,
938     struct in6_ifaddr *ia, int flags)
939 {
940 	int plen = -1;
941 	struct sockaddr_in6 dst6;
942 	struct in6_addrlifetime *lt;
943 	char ip6buf[INET6_ADDRSTRLEN];
944 
945 	/* Validate parameters */
946 	if (ifp == NULL || ifra == NULL) /* this maybe redundant */
947 		return (EINVAL);
948 
949 	/*
950 	 * The destination address for a p2p link must have a family
951 	 * of AF_UNSPEC or AF_INET6.
952 	 */
953 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
954 	    ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
955 	    ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
956 		return (EAFNOSUPPORT);
957 
958 	/*
959 	 * Validate address
960 	 */
961 	if (ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6) ||
962 	    ifra->ifra_addr.sin6_family != AF_INET6)
963 		return (EINVAL);
964 
965 	/*
966 	 * validate ifra_prefixmask.  don't check sin6_family, netmask
967 	 * does not carry fields other than sin6_len.
968 	 */
969 	if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
970 		return (EINVAL);
971 	/*
972 	 * Because the IPv6 address architecture is classless, we require
973 	 * users to specify a (non 0) prefix length (mask) for a new address.
974 	 * We also require the prefix (when specified) mask is valid, and thus
975 	 * reject a non-consecutive mask.
976 	 */
977 	if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
978 		return (EINVAL);
979 	if (ifra->ifra_prefixmask.sin6_len != 0) {
980 		plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
981 		    (u_char *)&ifra->ifra_prefixmask +
982 		    ifra->ifra_prefixmask.sin6_len);
983 		if (plen <= 0)
984 			return (EINVAL);
985 	} else {
986 		/*
987 		 * In this case, ia must not be NULL.  We just use its prefix
988 		 * length.
989 		 */
990 		plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
991 	}
992 	/*
993 	 * If the destination address on a p2p interface is specified,
994 	 * and the address is a scoped one, validate/set the scope
995 	 * zone identifier.
996 	 */
997 	dst6 = ifra->ifra_dstaddr;
998 	if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) != 0 &&
999 	    (dst6.sin6_family == AF_INET6)) {
1000 		struct in6_addr in6_tmp;
1001 		u_int32_t zoneid;
1002 
1003 		in6_tmp = dst6.sin6_addr;
1004 		if (in6_setscope(&in6_tmp, ifp, &zoneid))
1005 			return (EINVAL); /* XXX: should be impossible */
1006 
1007 		if (dst6.sin6_scope_id != 0) {
1008 			if (dst6.sin6_scope_id != zoneid)
1009 				return (EINVAL);
1010 		} else		/* user omit to specify the ID. */
1011 			dst6.sin6_scope_id = zoneid;
1012 
1013 		/* convert into the internal form */
1014 		if (sa6_embedscope(&dst6, 0))
1015 			return (EINVAL); /* XXX: should be impossible */
1016 	}
1017 	/* Modify original ifra_dstaddr to reflect changes */
1018 	ifra->ifra_dstaddr = dst6;
1019 
1020 	/*
1021 	 * The destination address can be specified only for a p2p or a
1022 	 * loopback interface.  If specified, the corresponding prefix length
1023 	 * must be 128.
1024 	 */
1025 	if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
1026 		if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) == 0) {
1027 			/* XXX: noisy message */
1028 			nd6log((LOG_INFO, "in6_update_ifa: a destination can "
1029 			    "be specified for a p2p or a loopback IF only\n"));
1030 			return (EINVAL);
1031 		}
1032 		if (plen != 128) {
1033 			nd6log((LOG_INFO, "in6_update_ifa: prefixlen should "
1034 			    "be 128 when dstaddr is specified\n"));
1035 			return (EINVAL);
1036 		}
1037 	}
1038 	/* lifetime consistency check */
1039 	lt = &ifra->ifra_lifetime;
1040 	if (lt->ia6t_pltime > lt->ia6t_vltime)
1041 		return (EINVAL);
1042 	if (lt->ia6t_vltime == 0) {
1043 		/*
1044 		 * the following log might be noisy, but this is a typical
1045 		 * configuration mistake or a tool's bug.
1046 		 */
1047 		nd6log((LOG_INFO,
1048 		    "in6_update_ifa: valid lifetime is 0 for %s\n",
1049 		    ip6_sprintf(ip6buf, &ifra->ifra_addr.sin6_addr)));
1050 
1051 		if (ia == NULL)
1052 			return (0); /* there's nothing to do */
1053 	}
1054 
1055 	/* Check prefix mask */
1056 	if (ia != NULL && ifra->ifra_prefixmask.sin6_len != 0) {
1057 		/*
1058 		 * We prohibit changing the prefix length of an existing
1059 		 * address, because
1060 		 * + such an operation should be rare in IPv6, and
1061 		 * + the operation would confuse prefix management.
1062 		 */
1063 		if (ia->ia_prefixmask.sin6_len != 0 &&
1064 		    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
1065 			nd6log((LOG_INFO, "in6_validate_ifa: the prefix length "
1066 			    "of an existing %s address should not be changed\n",
1067 			    ip6_sprintf(ip6buf, &ia->ia_addr.sin6_addr)));
1068 
1069 			return (EINVAL);
1070 		}
1071 	}
1072 
1073 	return (0);
1074 }
1075 
1076 
1077 /*
1078  * Allocate a new ifaddr and link it into chains.
1079  */
1080 static struct in6_ifaddr *
1081 in6_alloc_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra, int flags)
1082 {
1083 	struct in6_ifaddr *ia;
1084 
1085 	/*
1086 	 * When in6_alloc_ifa() is called in a process of a received
1087 	 * RA, it is called under an interrupt context.  So, we should
1088 	 * call malloc with M_NOWAIT.
1089 	 */
1090 	ia = (struct in6_ifaddr *)ifa_alloc(sizeof(*ia), M_NOWAIT);
1091 	if (ia == NULL)
1092 		return (NULL);
1093 	LIST_INIT(&ia->ia6_memberships);
1094 	/* Initialize the address and masks, and put time stamp */
1095 	ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
1096 	ia->ia_addr.sin6_family = AF_INET6;
1097 	ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
1098 	/* XXX: Can we assign ,sin6_addr and skip the rest? */
1099 	ia->ia_addr = ifra->ifra_addr;
1100 	ia->ia6_createtime = time_uptime;
1101 	if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
1102 		/*
1103 		 * Some functions expect that ifa_dstaddr is not
1104 		 * NULL for p2p interfaces.
1105 		 */
1106 		ia->ia_ifa.ifa_dstaddr =
1107 		    (struct sockaddr *)&ia->ia_dstaddr;
1108 	} else {
1109 		ia->ia_ifa.ifa_dstaddr = NULL;
1110 	}
1111 
1112 	/* set prefix mask if any */
1113 	ia->ia_ifa.ifa_netmask = (struct sockaddr *)&ia->ia_prefixmask;
1114 	if (ifra->ifra_prefixmask.sin6_len != 0) {
1115 		ia->ia_prefixmask.sin6_family = AF_INET6;
1116 		ia->ia_prefixmask.sin6_len = ifra->ifra_prefixmask.sin6_len;
1117 		ia->ia_prefixmask.sin6_addr = ifra->ifra_prefixmask.sin6_addr;
1118 	}
1119 
1120 	ia->ia_ifp = ifp;
1121 	ifa_ref(&ia->ia_ifa);			/* if_addrhead */
1122 	IF_ADDR_WLOCK(ifp);
1123 	CK_STAILQ_INSERT_TAIL(&ifp->if_addrhead, &ia->ia_ifa, ifa_link);
1124 	IF_ADDR_WUNLOCK(ifp);
1125 
1126 	ifa_ref(&ia->ia_ifa);			/* in6_ifaddrhead */
1127 	IN6_IFADDR_WLOCK();
1128 	CK_STAILQ_INSERT_TAIL(&V_in6_ifaddrhead, ia, ia_link);
1129 	CK_LIST_INSERT_HEAD(IN6ADDR_HASH(&ia->ia_addr.sin6_addr), ia, ia6_hash);
1130 	IN6_IFADDR_WUNLOCK();
1131 
1132 	return (ia);
1133 }
1134 
1135 /*
1136  * Update/configure interface address parameters:
1137  *
1138  * 1) Update lifetime
1139  * 2) Update interface metric ad flags
1140  * 3) Notify other subsystems
1141  */
1142 static int
1143 in6_update_ifa_internal(struct ifnet *ifp, struct in6_aliasreq *ifra,
1144     struct in6_ifaddr *ia, int hostIsNew, int flags)
1145 {
1146 	int error;
1147 
1148 	/* update timestamp */
1149 	ia->ia6_updatetime = time_uptime;
1150 
1151 	/*
1152 	 * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
1153 	 * to see if the address is deprecated or invalidated, but initialize
1154 	 * these members for applications.
1155 	 */
1156 	ia->ia6_lifetime = ifra->ifra_lifetime;
1157 	if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1158 		ia->ia6_lifetime.ia6t_expire =
1159 		    time_uptime + ia->ia6_lifetime.ia6t_vltime;
1160 	} else
1161 		ia->ia6_lifetime.ia6t_expire = 0;
1162 	if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1163 		ia->ia6_lifetime.ia6t_preferred =
1164 		    time_uptime + ia->ia6_lifetime.ia6t_pltime;
1165 	} else
1166 		ia->ia6_lifetime.ia6t_preferred = 0;
1167 
1168 	/*
1169 	 * backward compatibility - if IN6_IFF_DEPRECATED is set from the
1170 	 * userland, make it deprecated.
1171 	 */
1172 	if ((ifra->ifra_flags & IN6_IFF_DEPRECATED) != 0) {
1173 		ia->ia6_lifetime.ia6t_pltime = 0;
1174 		ia->ia6_lifetime.ia6t_preferred = time_uptime;
1175 	}
1176 
1177 	/*
1178 	 * configure address flags.
1179 	 */
1180 	ia->ia6_flags = ifra->ifra_flags;
1181 
1182 	/*
1183 	 * Make the address tentative before joining multicast addresses,
1184 	 * so that corresponding MLD responses would not have a tentative
1185 	 * source address.
1186 	 */
1187 	ia->ia6_flags &= ~IN6_IFF_DUPLICATED;	/* safety */
1188 
1189 	/*
1190 	 * DAD should be performed for an new address or addresses on
1191 	 * an interface with ND6_IFF_IFDISABLED.
1192 	 */
1193 	if (in6if_do_dad(ifp) &&
1194 	    (hostIsNew || (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)))
1195 		ia->ia6_flags |= IN6_IFF_TENTATIVE;
1196 
1197 	/* notify other subsystems */
1198 	error = in6_notify_ifa(ifp, ia, ifra, hostIsNew);
1199 
1200 	return (error);
1201 }
1202 
1203 /*
1204  * Do link-level ifa job:
1205  * 1) Add lle entry for added address
1206  * 2) Notifies routing socket users about new address
1207  * 3) join appropriate multicast group
1208  * 4) start DAD if enabled
1209  */
1210 static int
1211 in6_broadcast_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
1212     struct in6_ifaddr *ia, int flags)
1213 {
1214 	struct in6_multi *in6m_sol;
1215 	int error = 0;
1216 
1217 	/* Add local address to lltable, if necessary (ex. on p2p link). */
1218 	if ((error = nd6_add_ifa_lle(ia)) != 0) {
1219 		in6_purgeaddr(&ia->ia_ifa);
1220 		ifa_free(&ia->ia_ifa);
1221 		return (error);
1222 	}
1223 
1224 	/* Join necessary multicast groups. */
1225 	in6m_sol = NULL;
1226 	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
1227 		error = in6_update_ifa_join_mc(ifp, ifra, ia, flags, &in6m_sol);
1228 		if (error != 0) {
1229 			in6_purgeaddr(&ia->ia_ifa);
1230 			ifa_free(&ia->ia_ifa);
1231 			return (error);
1232 		}
1233 	}
1234 
1235 	/* Perform DAD, if the address is TENTATIVE. */
1236 	if ((ia->ia6_flags & IN6_IFF_TENTATIVE)) {
1237 		int delay, mindelay, maxdelay;
1238 
1239 		delay = 0;
1240 		if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1241 			/*
1242 			 * We need to impose a delay before sending an NS
1243 			 * for DAD.  Check if we also needed a delay for the
1244 			 * corresponding MLD message.  If we did, the delay
1245 			 * should be larger than the MLD delay (this could be
1246 			 * relaxed a bit, but this simple logic is at least
1247 			 * safe).
1248 			 * XXX: Break data hiding guidelines and look at
1249 			 * state for the solicited multicast group.
1250 			 */
1251 			mindelay = 0;
1252 			if (in6m_sol != NULL &&
1253 			    in6m_sol->in6m_state == MLD_REPORTING_MEMBER) {
1254 				mindelay = in6m_sol->in6m_timer;
1255 			}
1256 			maxdelay = MAX_RTR_SOLICITATION_DELAY * hz;
1257 			if (maxdelay - mindelay == 0)
1258 				delay = 0;
1259 			else {
1260 				delay =
1261 				    (arc4random() % (maxdelay - mindelay)) +
1262 				    mindelay;
1263 			}
1264 		}
1265 		nd6_dad_start((struct ifaddr *)ia, delay);
1266 	}
1267 
1268 	in6_newaddrmsg(ia, RTM_ADD);
1269 	ifa_free(&ia->ia_ifa);
1270 	return (error);
1271 }
1272 
1273 void
1274 in6_purgeaddr(struct ifaddr *ifa)
1275 {
1276 	struct ifnet *ifp = ifa->ifa_ifp;
1277 	struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1278 	struct in6_multi_mship *imm;
1279 	int plen, error;
1280 
1281 	if (ifa->ifa_carp)
1282 		(*carp_detach_p)(ifa, false);
1283 
1284 	/*
1285 	 * Remove the loopback route to the interface address.
1286 	 * The check for the current setting of "nd6_useloopback"
1287 	 * is not needed.
1288 	 */
1289 	if (ia->ia_flags & IFA_RTSELF) {
1290 		error = ifa_del_loopback_route((struct ifaddr *)ia,
1291 		    (struct sockaddr *)&ia->ia_addr);
1292 		if (error == 0)
1293 			ia->ia_flags &= ~IFA_RTSELF;
1294 	}
1295 
1296 	/* stop DAD processing */
1297 	nd6_dad_stop(ifa);
1298 
1299 	/* Leave multicast groups. */
1300 	while ((imm = LIST_FIRST(&ia->ia6_memberships)) != NULL) {
1301 		LIST_REMOVE(imm, i6mm_chain);
1302 		if (imm->i6mm_maddr != NULL)
1303 			in6_leavegroup(imm->i6mm_maddr, NULL);
1304 		free(imm, M_IP6MADDR);
1305 	}
1306 	plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1307 	if ((ia->ia_flags & IFA_ROUTE) && plen == 128) {
1308 		error = rtinit(&(ia->ia_ifa), RTM_DELETE, ia->ia_flags |
1309 		    (ia->ia_dstaddr.sin6_family == AF_INET6 ? RTF_HOST : 0));
1310 		if (error != 0)
1311 			log(LOG_INFO, "%s: err=%d, destination address delete "
1312 			    "failed\n", __func__, error);
1313 		ia->ia_flags &= ~IFA_ROUTE;
1314 	}
1315 
1316 	in6_newaddrmsg(ia, RTM_DELETE);
1317 	in6_unlink_ifa(ia, ifp);
1318 }
1319 
1320 static void
1321 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1322 {
1323 	char ip6buf[INET6_ADDRSTRLEN];
1324 	int remove_lle;
1325 
1326 	IF_ADDR_WLOCK(ifp);
1327 	CK_STAILQ_REMOVE(&ifp->if_addrhead, &ia->ia_ifa, ifaddr, ifa_link);
1328 	IF_ADDR_WUNLOCK(ifp);
1329 	ifa_free(&ia->ia_ifa);			/* if_addrhead */
1330 
1331 	/*
1332 	 * Defer the release of what might be the last reference to the
1333 	 * in6_ifaddr so that it can't be freed before the remainder of the
1334 	 * cleanup.
1335 	 */
1336 	IN6_IFADDR_WLOCK();
1337 	CK_STAILQ_REMOVE(&V_in6_ifaddrhead, ia, in6_ifaddr, ia_link);
1338 	CK_LIST_REMOVE(ia, ia6_hash);
1339 	IN6_IFADDR_WUNLOCK();
1340 
1341 	/*
1342 	 * Release the reference to the base prefix.  There should be a
1343 	 * positive reference.
1344 	 */
1345 	remove_lle = 0;
1346 	if (ia->ia6_ndpr == NULL) {
1347 		nd6log((LOG_NOTICE,
1348 		    "in6_unlink_ifa: autoconf'ed address "
1349 		    "%s has no prefix\n", ip6_sprintf(ip6buf, IA6_IN6(ia))));
1350 	} else {
1351 		ia->ia6_ndpr->ndpr_addrcnt--;
1352 		/* Do not delete lles within prefix if refcont != 0 */
1353 		if (ia->ia6_ndpr->ndpr_addrcnt == 0)
1354 			remove_lle = 1;
1355 		ia->ia6_ndpr = NULL;
1356 	}
1357 
1358 	nd6_rem_ifa_lle(ia, remove_lle);
1359 
1360 	/*
1361 	 * Also, if the address being removed is autoconf'ed, call
1362 	 * pfxlist_onlink_check() since the release might affect the status of
1363 	 * other (detached) addresses.
1364 	 */
1365 	if ((ia->ia6_flags & IN6_IFF_AUTOCONF)) {
1366 		pfxlist_onlink_check();
1367 	}
1368 	ifa_free(&ia->ia_ifa);			/* in6_ifaddrhead */
1369 }
1370 
1371 /*
1372  * Notifies other subsystems about address change/arrival:
1373  * 1) Notifies device handler on the first IPv6 address assignment
1374  * 2) Handle routing table changes for P2P links and route
1375  * 3) Handle routing table changes for address host route
1376  */
1377 static int
1378 in6_notify_ifa(struct ifnet *ifp, struct in6_ifaddr *ia,
1379     struct in6_aliasreq *ifra, int hostIsNew)
1380 {
1381 	int	error = 0, plen, ifacount = 0;
1382 	struct ifaddr *ifa;
1383 	struct sockaddr_in6 *pdst;
1384 	char ip6buf[INET6_ADDRSTRLEN];
1385 
1386 	/*
1387 	 * Give the interface a chance to initialize
1388 	 * if this is its first address,
1389 	 */
1390 	if (hostIsNew != 0) {
1391 		struct epoch_tracker et;
1392 
1393 		NET_EPOCH_ENTER(et);
1394 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1395 			if (ifa->ifa_addr->sa_family != AF_INET6)
1396 				continue;
1397 			ifacount++;
1398 		}
1399 		NET_EPOCH_EXIT(et);
1400 	}
1401 
1402 	if (ifacount <= 1 && ifp->if_ioctl) {
1403 		error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia);
1404 		if (error)
1405 			goto done;
1406 	}
1407 
1408 	/*
1409 	 * If a new destination address is specified, scrub the old one and
1410 	 * install the new destination.  Note that the interface must be
1411 	 * p2p or loopback.
1412 	 */
1413 	pdst = &ifra->ifra_dstaddr;
1414 	if (pdst->sin6_family == AF_INET6 &&
1415 	    !IN6_ARE_ADDR_EQUAL(&pdst->sin6_addr, &ia->ia_dstaddr.sin6_addr)) {
1416 		if ((ia->ia_flags & IFA_ROUTE) != 0 &&
1417 		    (rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST) != 0)) {
1418 			nd6log((LOG_ERR, "in6_update_ifa_internal: failed to "
1419 			    "remove a route to the old destination: %s\n",
1420 			    ip6_sprintf(ip6buf, &ia->ia_addr.sin6_addr)));
1421 			/* proceed anyway... */
1422 		} else
1423 			ia->ia_flags &= ~IFA_ROUTE;
1424 		ia->ia_dstaddr = *pdst;
1425 	}
1426 
1427 	/*
1428 	 * If a new destination address is specified for a point-to-point
1429 	 * interface, install a route to the destination as an interface
1430 	 * direct route.
1431 	 * XXX: the logic below rejects assigning multiple addresses on a p2p
1432 	 * interface that share the same destination.
1433 	 */
1434 	plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1435 	if (!(ia->ia_flags & IFA_ROUTE) && plen == 128 &&
1436 	    ia->ia_dstaddr.sin6_family == AF_INET6) {
1437 		int rtflags = RTF_UP | RTF_HOST;
1438 		/*
1439 		 * Handle the case for ::1 .
1440 		 */
1441 		if (ifp->if_flags & IFF_LOOPBACK)
1442 			ia->ia_flags |= IFA_RTSELF;
1443 		error = rtinit(&ia->ia_ifa, RTM_ADD, ia->ia_flags | rtflags);
1444 		if (error)
1445 			goto done;
1446 		ia->ia_flags |= IFA_ROUTE;
1447 	}
1448 
1449 	/*
1450 	 * add a loopback route to self if not exists
1451 	 */
1452 	if (!(ia->ia_flags & IFA_RTSELF) && V_nd6_useloopback) {
1453 		error = ifa_add_loopback_route((struct ifaddr *)ia,
1454 		    (struct sockaddr *)&ia->ia_addr);
1455 		if (error == 0)
1456 			ia->ia_flags |= IFA_RTSELF;
1457 	}
1458 done:
1459 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1460 	    "Invoking IPv6 network device address event may sleep");
1461 
1462 	ifa_ref(&ia->ia_ifa);
1463 	EVENTHANDLER_INVOKE(ifaddr_event_ext, ifp, &ia->ia_ifa,
1464 	    IFADDR_EVENT_ADD);
1465 	ifa_free(&ia->ia_ifa);
1466 
1467 	return (error);
1468 }
1469 
1470 /*
1471  * Find an IPv6 interface link-local address specific to an interface.
1472  * ifaddr is returned referenced.
1473  */
1474 struct in6_ifaddr *
1475 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
1476 {
1477 	struct epoch_tracker et;
1478 	struct ifaddr *ifa;
1479 
1480 	NET_EPOCH_ENTER(et);
1481 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1482 		if (ifa->ifa_addr->sa_family != AF_INET6)
1483 			continue;
1484 		if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1485 			if ((((struct in6_ifaddr *)ifa)->ia6_flags &
1486 			    ignoreflags) != 0)
1487 				continue;
1488 			ifa_ref(ifa);
1489 			break;
1490 		}
1491 	}
1492 	NET_EPOCH_EXIT(et);
1493 
1494 	return ((struct in6_ifaddr *)ifa);
1495 }
1496 
1497 
1498 /*
1499  * find the interface address corresponding to a given IPv6 address.
1500  * ifaddr is returned referenced.
1501  */
1502 struct in6_ifaddr *
1503 in6ifa_ifwithaddr(const struct in6_addr *addr, uint32_t zoneid)
1504 {
1505 	struct rm_priotracker in6_ifa_tracker;
1506 	struct in6_ifaddr *ia;
1507 
1508 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
1509 	CK_LIST_FOREACH(ia, IN6ADDR_HASH(addr), ia6_hash) {
1510 		if (IN6_ARE_ADDR_EQUAL(IA6_IN6(ia), addr)) {
1511 			if (zoneid != 0 &&
1512 			    zoneid != ia->ia_addr.sin6_scope_id)
1513 				continue;
1514 			ifa_ref(&ia->ia_ifa);
1515 			break;
1516 		}
1517 	}
1518 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
1519 	return (ia);
1520 }
1521 
1522 /*
1523  * find the internet address corresponding to a given interface and address.
1524  * ifaddr is returned referenced.
1525  */
1526 struct in6_ifaddr *
1527 in6ifa_ifpwithaddr(struct ifnet *ifp, const struct in6_addr *addr)
1528 {
1529 	struct epoch_tracker et;
1530 	struct ifaddr *ifa;
1531 
1532 	NET_EPOCH_ENTER(et);
1533 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1534 		if (ifa->ifa_addr->sa_family != AF_INET6)
1535 			continue;
1536 		if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa))) {
1537 			ifa_ref(ifa);
1538 			break;
1539 		}
1540 	}
1541 	NET_EPOCH_EXIT(et);
1542 
1543 	return ((struct in6_ifaddr *)ifa);
1544 }
1545 
1546 /*
1547  * Find a link-local scoped address on ifp and return it if any.
1548  */
1549 struct in6_ifaddr *
1550 in6ifa_llaonifp(struct ifnet *ifp)
1551 {
1552 	struct epoch_tracker et;
1553 	struct sockaddr_in6 *sin6;
1554 	struct ifaddr *ifa;
1555 
1556 	if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)
1557 		return (NULL);
1558 	NET_EPOCH_ENTER(et);
1559 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1560 		if (ifa->ifa_addr->sa_family != AF_INET6)
1561 			continue;
1562 		sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
1563 		if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr) ||
1564 		    IN6_IS_ADDR_MC_INTFACELOCAL(&sin6->sin6_addr) ||
1565 		    IN6_IS_ADDR_MC_NODELOCAL(&sin6->sin6_addr))
1566 			break;
1567 	}
1568 	NET_EPOCH_EXIT(et);
1569 
1570 	return ((struct in6_ifaddr *)ifa);
1571 }
1572 
1573 /*
1574  * Convert IP6 address to printable (loggable) representation. Caller
1575  * has to make sure that ip6buf is at least INET6_ADDRSTRLEN long.
1576  */
1577 static char digits[] = "0123456789abcdef";
1578 char *
1579 ip6_sprintf(char *ip6buf, const struct in6_addr *addr)
1580 {
1581 	int i, cnt = 0, maxcnt = 0, idx = 0, index = 0;
1582 	char *cp;
1583 	const u_int16_t *a = (const u_int16_t *)addr;
1584 	const u_int8_t *d;
1585 	int dcolon = 0, zero = 0;
1586 
1587 	cp = ip6buf;
1588 
1589 	for (i = 0; i < 8; i++) {
1590 		if (*(a + i) == 0) {
1591 			cnt++;
1592 			if (cnt == 1)
1593 				idx = i;
1594 		}
1595 		else if (maxcnt < cnt) {
1596 			maxcnt = cnt;
1597 			index = idx;
1598 			cnt = 0;
1599 		}
1600 	}
1601 	if (maxcnt < cnt) {
1602 		maxcnt = cnt;
1603 		index = idx;
1604 	}
1605 
1606 	for (i = 0; i < 8; i++) {
1607 		if (dcolon == 1) {
1608 			if (*a == 0) {
1609 				if (i == 7)
1610 					*cp++ = ':';
1611 				a++;
1612 				continue;
1613 			} else
1614 				dcolon = 2;
1615 		}
1616 		if (*a == 0) {
1617 			if (dcolon == 0 && *(a + 1) == 0 && i == index) {
1618 				if (i == 0)
1619 					*cp++ = ':';
1620 				*cp++ = ':';
1621 				dcolon = 1;
1622 			} else {
1623 				*cp++ = '0';
1624 				*cp++ = ':';
1625 			}
1626 			a++;
1627 			continue;
1628 		}
1629 		d = (const u_char *)a;
1630 		/* Try to eliminate leading zeros in printout like in :0001. */
1631 		zero = 1;
1632 		*cp = digits[*d >> 4];
1633 		if (*cp != '0') {
1634 			zero = 0;
1635 			cp++;
1636 		}
1637 		*cp = digits[*d++ & 0xf];
1638 		if (zero == 0 || (*cp != '0')) {
1639 			zero = 0;
1640 			cp++;
1641 		}
1642 		*cp = digits[*d >> 4];
1643 		if (zero == 0 || (*cp != '0')) {
1644 			zero = 0;
1645 			cp++;
1646 		}
1647 		*cp++ = digits[*d & 0xf];
1648 		*cp++ = ':';
1649 		a++;
1650 	}
1651 	*--cp = '\0';
1652 	return (ip6buf);
1653 }
1654 
1655 int
1656 in6_localaddr(struct in6_addr *in6)
1657 {
1658 	struct rm_priotracker in6_ifa_tracker;
1659 	struct in6_ifaddr *ia;
1660 
1661 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
1662 		return 1;
1663 
1664 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
1665 	CK_STAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
1666 		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
1667 		    &ia->ia_prefixmask.sin6_addr)) {
1668 			IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
1669 			return 1;
1670 		}
1671 	}
1672 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
1673 
1674 	return (0);
1675 }
1676 
1677 /*
1678  * Return 1 if an internet address is for the local host and configured
1679  * on one of its interfaces.
1680  */
1681 int
1682 in6_localip(struct in6_addr *in6)
1683 {
1684 	struct rm_priotracker in6_ifa_tracker;
1685 	struct in6_ifaddr *ia;
1686 
1687 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
1688 	CK_LIST_FOREACH(ia, IN6ADDR_HASH(in6), ia6_hash) {
1689 		if (IN6_ARE_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr)) {
1690 			IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
1691 			return (1);
1692 		}
1693 	}
1694 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
1695 	return (0);
1696 }
1697 
1698 /*
1699  * Return 1 if an internet address is configured on an interface.
1700  */
1701 int
1702 in6_ifhasaddr(struct ifnet *ifp, struct in6_addr *addr)
1703 {
1704 	struct in6_addr in6;
1705 	struct epoch_tracker et;
1706 	struct ifaddr *ifa;
1707 	struct in6_ifaddr *ia6;
1708 
1709 	in6 = *addr;
1710 	if (in6_clearscope(&in6))
1711 		return (0);
1712 	in6_setscope(&in6, ifp, NULL);
1713 
1714 	NET_EPOCH_ENTER(et);
1715 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1716 		if (ifa->ifa_addr->sa_family != AF_INET6)
1717 			continue;
1718 		ia6 = (struct in6_ifaddr *)ifa;
1719 		if (IN6_ARE_ADDR_EQUAL(&ia6->ia_addr.sin6_addr, &in6)) {
1720 			NET_EPOCH_EXIT(et);
1721 			return (1);
1722 		}
1723 	}
1724 	NET_EPOCH_EXIT(et);
1725 
1726 	return (0);
1727 }
1728 
1729 int
1730 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
1731 {
1732 	struct rm_priotracker in6_ifa_tracker;
1733 	struct in6_ifaddr *ia;
1734 
1735 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
1736 	CK_LIST_FOREACH(ia, IN6ADDR_HASH(&sa6->sin6_addr), ia6_hash) {
1737 		if (IN6_ARE_ADDR_EQUAL(IA6_IN6(ia), &sa6->sin6_addr)) {
1738 			if (ia->ia6_flags & IN6_IFF_DEPRECATED) {
1739 				IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
1740 				return (1); /* true */
1741 			}
1742 			break;
1743 		}
1744 	}
1745 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
1746 
1747 	return (0);		/* false */
1748 }
1749 
1750 /*
1751  * return length of part which dst and src are equal
1752  * hard coding...
1753  */
1754 int
1755 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
1756 {
1757 	int match = 0;
1758 	u_char *s = (u_char *)src, *d = (u_char *)dst;
1759 	u_char *lim = s + 16, r;
1760 
1761 	while (s < lim)
1762 		if ((r = (*d++ ^ *s++)) != 0) {
1763 			while (r < 128) {
1764 				match++;
1765 				r <<= 1;
1766 			}
1767 			break;
1768 		} else
1769 			match += 8;
1770 	return match;
1771 }
1772 
1773 /* XXX: to be scope conscious */
1774 int
1775 in6_are_prefix_equal(struct in6_addr *p1, struct in6_addr *p2, int len)
1776 {
1777 	int bytelen, bitlen;
1778 
1779 	/* sanity check */
1780 	if (0 > len || len > 128) {
1781 		log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
1782 		    len);
1783 		return (0);
1784 	}
1785 
1786 	bytelen = len / 8;
1787 	bitlen = len % 8;
1788 
1789 	if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
1790 		return (0);
1791 	if (bitlen != 0 &&
1792 	    p1->s6_addr[bytelen] >> (8 - bitlen) !=
1793 	    p2->s6_addr[bytelen] >> (8 - bitlen))
1794 		return (0);
1795 
1796 	return (1);
1797 }
1798 
1799 void
1800 in6_prefixlen2mask(struct in6_addr *maskp, int len)
1801 {
1802 	u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
1803 	int bytelen, bitlen, i;
1804 
1805 	/* sanity check */
1806 	if (0 > len || len > 128) {
1807 		log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
1808 		    len);
1809 		return;
1810 	}
1811 
1812 	bzero(maskp, sizeof(*maskp));
1813 	bytelen = len / 8;
1814 	bitlen = len % 8;
1815 	for (i = 0; i < bytelen; i++)
1816 		maskp->s6_addr[i] = 0xff;
1817 	if (bitlen)
1818 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
1819 }
1820 
1821 /*
1822  * return the best address out of the same scope. if no address was
1823  * found, return the first valid address from designated IF.
1824  */
1825 struct in6_ifaddr *
1826 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
1827 {
1828 	struct epoch_tracker et;
1829 	int dst_scope =	in6_addrscope(dst), blen = -1, tlen;
1830 	struct ifaddr *ifa;
1831 	struct in6_ifaddr *besta = NULL;
1832 	struct in6_ifaddr *dep[2];	/* last-resort: deprecated */
1833 
1834 	dep[0] = dep[1] = NULL;
1835 
1836 	/*
1837 	 * We first look for addresses in the same scope.
1838 	 * If there is one, return it.
1839 	 * If two or more, return one which matches the dst longest.
1840 	 * If none, return one of global addresses assigned other ifs.
1841 	 */
1842 	NET_EPOCH_ENTER(et);
1843 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1844 		if (ifa->ifa_addr->sa_family != AF_INET6)
1845 			continue;
1846 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
1847 			continue; /* XXX: is there any case to allow anycast? */
1848 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
1849 			continue; /* don't use this interface */
1850 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
1851 			continue;
1852 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
1853 			if (V_ip6_use_deprecated)
1854 				dep[0] = (struct in6_ifaddr *)ifa;
1855 			continue;
1856 		}
1857 
1858 		if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
1859 			/*
1860 			 * call in6_matchlen() as few as possible
1861 			 */
1862 			if (besta) {
1863 				if (blen == -1)
1864 					blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
1865 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
1866 				if (tlen > blen) {
1867 					blen = tlen;
1868 					besta = (struct in6_ifaddr *)ifa;
1869 				}
1870 			} else
1871 				besta = (struct in6_ifaddr *)ifa;
1872 		}
1873 	}
1874 	if (besta) {
1875 		ifa_ref(&besta->ia_ifa);
1876 		NET_EPOCH_EXIT(et);
1877 		return (besta);
1878 	}
1879 
1880 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1881 		if (ifa->ifa_addr->sa_family != AF_INET6)
1882 			continue;
1883 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
1884 			continue; /* XXX: is there any case to allow anycast? */
1885 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
1886 			continue; /* don't use this interface */
1887 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
1888 			continue;
1889 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
1890 			if (V_ip6_use_deprecated)
1891 				dep[1] = (struct in6_ifaddr *)ifa;
1892 			continue;
1893 		}
1894 
1895 		if (ifa != NULL)
1896 			ifa_ref(ifa);
1897 		NET_EPOCH_EXIT(et);
1898 		return (struct in6_ifaddr *)ifa;
1899 	}
1900 
1901 	/* use the last-resort values, that are, deprecated addresses */
1902 	if (dep[0]) {
1903 		ifa_ref((struct ifaddr *)dep[0]);
1904 		NET_EPOCH_EXIT(et);
1905 		return dep[0];
1906 	}
1907 	if (dep[1]) {
1908 		ifa_ref((struct ifaddr *)dep[1]);
1909 		NET_EPOCH_EXIT(et);
1910 		return dep[1];
1911 	}
1912 
1913 	NET_EPOCH_EXIT(et);
1914 	return NULL;
1915 }
1916 
1917 /*
1918  * perform DAD when interface becomes IFF_UP.
1919  */
1920 void
1921 in6_if_up(struct ifnet *ifp)
1922 {
1923 	struct epoch_tracker et;
1924 	struct ifaddr *ifa;
1925 	struct in6_ifaddr *ia;
1926 
1927 	NET_EPOCH_ENTER(et);
1928 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1929 		if (ifa->ifa_addr->sa_family != AF_INET6)
1930 			continue;
1931 		ia = (struct in6_ifaddr *)ifa;
1932 		if (ia->ia6_flags & IN6_IFF_TENTATIVE) {
1933 			/*
1934 			 * The TENTATIVE flag was likely set by hand
1935 			 * beforehand, implicitly indicating the need for DAD.
1936 			 * We may be able to skip the random delay in this
1937 			 * case, but we impose delays just in case.
1938 			 */
1939 			nd6_dad_start(ifa,
1940 			    arc4random() % (MAX_RTR_SOLICITATION_DELAY * hz));
1941 		}
1942 	}
1943 	NET_EPOCH_EXIT(et);
1944 
1945 	/*
1946 	 * special cases, like 6to4, are handled in in6_ifattach
1947 	 */
1948 	in6_ifattach(ifp, NULL);
1949 }
1950 
1951 int
1952 in6if_do_dad(struct ifnet *ifp)
1953 {
1954 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
1955 		return (0);
1956 
1957 	if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) ||
1958 	    (ND_IFINFO(ifp)->flags & ND6_IFF_NO_DAD))
1959 		return (0);
1960 
1961 	/*
1962 	 * Our DAD routine requires the interface up and running.
1963 	 * However, some interfaces can be up before the RUNNING
1964 	 * status.  Additionally, users may try to assign addresses
1965 	 * before the interface becomes up (or running).
1966 	 * This function returns EAGAIN in that case.
1967 	 * The caller should mark "tentative" on the address instead of
1968 	 * performing DAD immediately.
1969 	 */
1970 	if (!((ifp->if_flags & IFF_UP) &&
1971 	    (ifp->if_drv_flags & IFF_DRV_RUNNING)))
1972 		return (EAGAIN);
1973 
1974 	return (1);
1975 }
1976 
1977 /*
1978  * Calculate max IPv6 MTU through all the interfaces and store it
1979  * to in6_maxmtu.
1980  */
1981 void
1982 in6_setmaxmtu(void)
1983 {
1984 	struct epoch_tracker et;
1985 	unsigned long maxmtu = 0;
1986 	struct ifnet *ifp;
1987 
1988 	NET_EPOCH_ENTER(et);
1989 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1990 		/* this function can be called during ifnet initialization */
1991 		if (!ifp->if_afdata[AF_INET6])
1992 			continue;
1993 		if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
1994 		    IN6_LINKMTU(ifp) > maxmtu)
1995 			maxmtu = IN6_LINKMTU(ifp);
1996 	}
1997 	NET_EPOCH_EXIT(et);
1998 	if (maxmtu)	/* update only when maxmtu is positive */
1999 		V_in6_maxmtu = maxmtu;
2000 }
2001 
2002 /*
2003  * Provide the length of interface identifiers to be used for the link attached
2004  * to the given interface.  The length should be defined in "IPv6 over
2005  * xxx-link" document.  Note that address architecture might also define
2006  * the length for a particular set of address prefixes, regardless of the
2007  * link type.  As clarified in rfc2462bis, those two definitions should be
2008  * consistent, and those really are as of August 2004.
2009  */
2010 int
2011 in6_if2idlen(struct ifnet *ifp)
2012 {
2013 	switch (ifp->if_type) {
2014 	case IFT_ETHER:		/* RFC2464 */
2015 	case IFT_PROPVIRTUAL:	/* XXX: no RFC. treat it as ether */
2016 	case IFT_L2VLAN:	/* ditto */
2017 	case IFT_BRIDGE:	/* bridge(4) only does Ethernet-like links */
2018 	case IFT_INFINIBAND:
2019 		return (64);
2020 	case IFT_PPP:		/* RFC2472 */
2021 		return (64);
2022 	case IFT_FRELAY:	/* RFC2590 */
2023 		return (64);
2024 	case IFT_IEEE1394:	/* RFC3146 */
2025 		return (64);
2026 	case IFT_GIF:
2027 		return (64);	/* draft-ietf-v6ops-mech-v2-07 */
2028 	case IFT_LOOP:
2029 		return (64);	/* XXX: is this really correct? */
2030 	default:
2031 		/*
2032 		 * Unknown link type:
2033 		 * It might be controversial to use the today's common constant
2034 		 * of 64 for these cases unconditionally.  For full compliance,
2035 		 * we should return an error in this case.  On the other hand,
2036 		 * if we simply miss the standard for the link type or a new
2037 		 * standard is defined for a new link type, the IFID length
2038 		 * is very likely to be the common constant.  As a compromise,
2039 		 * we always use the constant, but make an explicit notice
2040 		 * indicating the "unknown" case.
2041 		 */
2042 		printf("in6_if2idlen: unknown link type (%d)\n", ifp->if_type);
2043 		return (64);
2044 	}
2045 }
2046 
2047 #include <sys/sysctl.h>
2048 
2049 struct in6_llentry {
2050 	struct llentry		base;
2051 };
2052 
2053 #define	IN6_LLTBL_DEFAULT_HSIZE	32
2054 #define	IN6_LLTBL_HASH(k, h) \
2055 	(((((((k >> 8) ^ k) >> 8) ^ k) >> 8) ^ k) & ((h) - 1))
2056 
2057 /*
2058  * Do actual deallocation of @lle.
2059  */
2060 static void
2061 in6_lltable_destroy_lle_unlocked(epoch_context_t ctx)
2062 {
2063 	struct llentry *lle;
2064 
2065 	lle = __containerof(ctx, struct llentry, lle_epoch_ctx);
2066 	LLE_LOCK_DESTROY(lle);
2067 	LLE_REQ_DESTROY(lle);
2068 	free(lle, M_LLTABLE);
2069 }
2070 
2071 /*
2072  * Called by LLE_FREE_LOCKED when number of references
2073  * drops to zero.
2074  */
2075 static void
2076 in6_lltable_destroy_lle(struct llentry *lle)
2077 {
2078 
2079 	LLE_WUNLOCK(lle);
2080 	epoch_call(net_epoch_preempt,  &lle->lle_epoch_ctx, in6_lltable_destroy_lle_unlocked);
2081 }
2082 
2083 static struct llentry *
2084 in6_lltable_new(const struct in6_addr *addr6, u_int flags)
2085 {
2086 	struct in6_llentry *lle;
2087 
2088 	lle = malloc(sizeof(struct in6_llentry), M_LLTABLE, M_NOWAIT | M_ZERO);
2089 	if (lle == NULL)		/* NB: caller generates msg */
2090 		return NULL;
2091 
2092 	lle->base.r_l3addr.addr6 = *addr6;
2093 	lle->base.lle_refcnt = 1;
2094 	lle->base.lle_free = in6_lltable_destroy_lle;
2095 	LLE_LOCK_INIT(&lle->base);
2096 	LLE_REQ_INIT(&lle->base);
2097 	callout_init(&lle->base.lle_timer, 1);
2098 
2099 	return (&lle->base);
2100 }
2101 
2102 static int
2103 in6_lltable_match_prefix(const struct sockaddr *saddr,
2104     const struct sockaddr *smask, u_int flags, struct llentry *lle)
2105 {
2106 	const struct in6_addr *addr, *mask, *lle_addr;
2107 
2108 	addr = &((const struct sockaddr_in6 *)saddr)->sin6_addr;
2109 	mask = &((const struct sockaddr_in6 *)smask)->sin6_addr;
2110 	lle_addr = &lle->r_l3addr.addr6;
2111 
2112 	if (IN6_ARE_MASKED_ADDR_EQUAL(lle_addr, addr, mask) == 0)
2113 		return (0);
2114 
2115 	if (lle->la_flags & LLE_IFADDR) {
2116 
2117 		/*
2118 		 * Delete LLE_IFADDR records IFF address & flag matches.
2119 		 * Note that addr is the interface address within prefix
2120 		 * being matched.
2121 		 */
2122 		if (IN6_ARE_ADDR_EQUAL(addr, lle_addr) &&
2123 		    (flags & LLE_STATIC) != 0)
2124 			return (1);
2125 		return (0);
2126 	}
2127 
2128 	/* flags & LLE_STATIC means deleting both dynamic and static entries */
2129 	if ((flags & LLE_STATIC) || !(lle->la_flags & LLE_STATIC))
2130 		return (1);
2131 
2132 	return (0);
2133 }
2134 
2135 static void
2136 in6_lltable_free_entry(struct lltable *llt, struct llentry *lle)
2137 {
2138 	struct ifnet *ifp;
2139 
2140 	LLE_WLOCK_ASSERT(lle);
2141 	KASSERT(llt != NULL, ("lltable is NULL"));
2142 
2143 	/* Unlink entry from table */
2144 	if ((lle->la_flags & LLE_LINKED) != 0) {
2145 
2146 		ifp = llt->llt_ifp;
2147 		IF_AFDATA_WLOCK_ASSERT(ifp);
2148 		lltable_unlink_entry(llt, lle);
2149 	}
2150 
2151 	llentry_free(lle);
2152 }
2153 
2154 static int
2155 in6_lltable_rtcheck(struct ifnet *ifp,
2156 		    u_int flags,
2157 		    const struct sockaddr *l3addr)
2158 {
2159 	const struct sockaddr_in6 *sin6;
2160 	struct nhop6_basic nh6;
2161 	struct in6_addr dst;
2162 	uint32_t scopeid;
2163 	int error;
2164 	char ip6buf[INET6_ADDRSTRLEN];
2165 	int fibnum;
2166 
2167 	KASSERT(l3addr->sa_family == AF_INET6,
2168 	    ("sin_family %d", l3addr->sa_family));
2169 
2170 	sin6 = (const struct sockaddr_in6 *)l3addr;
2171 	in6_splitscope(&sin6->sin6_addr, &dst, &scopeid);
2172 	fibnum = V_rt_add_addr_allfibs ? RT_DEFAULT_FIB : ifp->if_fib;
2173 	error = fib6_lookup_nh_basic(fibnum, &dst, scopeid, 0, 0, &nh6);
2174 	if (error != 0 || (nh6.nh_flags & NHF_GATEWAY) || nh6.nh_ifp != ifp) {
2175 		struct epoch_tracker et;
2176 		struct ifaddr *ifa;
2177 		/*
2178 		 * Create an ND6 cache for an IPv6 neighbor
2179 		 * that is not covered by our own prefix.
2180 		 */
2181 		NET_EPOCH_ENTER(et);
2182 		ifa = ifaof_ifpforaddr(l3addr, ifp);
2183 		if (ifa != NULL) {
2184 			NET_EPOCH_EXIT(et);
2185 			return 0;
2186 		}
2187 		NET_EPOCH_EXIT(et);
2188 		log(LOG_INFO, "IPv6 address: \"%s\" is not on the network\n",
2189 		    ip6_sprintf(ip6buf, &sin6->sin6_addr));
2190 		return EINVAL;
2191 	}
2192 	return 0;
2193 }
2194 
2195 /*
2196  * Called by the datapath to indicate that the entry was used.
2197  */
2198 static void
2199 in6_lltable_mark_used(struct llentry *lle)
2200 {
2201 
2202 	LLE_REQ_LOCK(lle);
2203 	lle->r_skip_req = 0;
2204 
2205 	/*
2206 	 * Set the hit time so the callback function
2207 	 * can determine the remaining time before
2208 	 * transiting to the DELAY state.
2209 	 */
2210 	lle->lle_hittime = time_uptime;
2211 	LLE_REQ_UNLOCK(lle);
2212 }
2213 
2214 static inline uint32_t
2215 in6_lltable_hash_dst(const struct in6_addr *dst, uint32_t hsize)
2216 {
2217 
2218 	return (IN6_LLTBL_HASH(dst->s6_addr32[3], hsize));
2219 }
2220 
2221 static uint32_t
2222 in6_lltable_hash(const struct llentry *lle, uint32_t hsize)
2223 {
2224 
2225 	return (in6_lltable_hash_dst(&lle->r_l3addr.addr6, hsize));
2226 }
2227 
2228 static void
2229 in6_lltable_fill_sa_entry(const struct llentry *lle, struct sockaddr *sa)
2230 {
2231 	struct sockaddr_in6 *sin6;
2232 
2233 	sin6 = (struct sockaddr_in6 *)sa;
2234 	bzero(sin6, sizeof(*sin6));
2235 	sin6->sin6_family = AF_INET6;
2236 	sin6->sin6_len = sizeof(*sin6);
2237 	sin6->sin6_addr = lle->r_l3addr.addr6;
2238 }
2239 
2240 static inline struct llentry *
2241 in6_lltable_find_dst(struct lltable *llt, const struct in6_addr *dst)
2242 {
2243 	struct llentry *lle;
2244 	struct llentries *lleh;
2245 	u_int hashidx;
2246 
2247 	hashidx = in6_lltable_hash_dst(dst, llt->llt_hsize);
2248 	lleh = &llt->lle_head[hashidx];
2249 	CK_LIST_FOREACH(lle, lleh, lle_next) {
2250 		if (lle->la_flags & LLE_DELETED)
2251 			continue;
2252 		if (IN6_ARE_ADDR_EQUAL(&lle->r_l3addr.addr6, dst))
2253 			break;
2254 	}
2255 
2256 	return (lle);
2257 }
2258 
2259 static void
2260 in6_lltable_delete_entry(struct lltable *llt, struct llentry *lle)
2261 {
2262 
2263 	lle->la_flags |= LLE_DELETED;
2264 	EVENTHANDLER_INVOKE(lle_event, lle, LLENTRY_DELETED);
2265 #ifdef DIAGNOSTIC
2266 	log(LOG_INFO, "ifaddr cache = %p is deleted\n", lle);
2267 #endif
2268 	llentry_free(lle);
2269 }
2270 
2271 static struct llentry *
2272 in6_lltable_alloc(struct lltable *llt, u_int flags,
2273 	const struct sockaddr *l3addr)
2274 {
2275 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)l3addr;
2276 	struct ifnet *ifp = llt->llt_ifp;
2277 	struct llentry *lle;
2278 	char linkhdr[LLE_MAX_LINKHDR];
2279 	size_t linkhdrsize;
2280 	int lladdr_off;
2281 
2282 	KASSERT(l3addr->sa_family == AF_INET6,
2283 	    ("sin_family %d", l3addr->sa_family));
2284 
2285 	/*
2286 	 * A route that covers the given address must have
2287 	 * been installed 1st because we are doing a resolution,
2288 	 * verify this.
2289 	 */
2290 	if (!(flags & LLE_IFADDR) &&
2291 	    in6_lltable_rtcheck(ifp, flags, l3addr) != 0)
2292 		return (NULL);
2293 
2294 	lle = in6_lltable_new(&sin6->sin6_addr, flags);
2295 	if (lle == NULL) {
2296 		log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
2297 		return (NULL);
2298 	}
2299 	lle->la_flags = flags;
2300 	if ((flags & LLE_IFADDR) == LLE_IFADDR) {
2301 		linkhdrsize = LLE_MAX_LINKHDR;
2302 		if (lltable_calc_llheader(ifp, AF_INET6, IF_LLADDR(ifp),
2303 		    linkhdr, &linkhdrsize, &lladdr_off) != 0) {
2304 			epoch_call(net_epoch_preempt,  &lle->lle_epoch_ctx, in6_lltable_destroy_lle_unlocked);
2305 			return (NULL);
2306 		}
2307 		lltable_set_entry_addr(ifp, lle, linkhdr, linkhdrsize,
2308 		    lladdr_off);
2309 		lle->la_flags |= LLE_STATIC;
2310 	}
2311 
2312 	if ((lle->la_flags & LLE_STATIC) != 0)
2313 		lle->ln_state = ND6_LLINFO_REACHABLE;
2314 
2315 	return (lle);
2316 }
2317 
2318 static struct llentry *
2319 in6_lltable_lookup(struct lltable *llt, u_int flags,
2320 	const struct sockaddr *l3addr)
2321 {
2322 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)l3addr;
2323 	struct llentry *lle;
2324 
2325 	IF_AFDATA_LOCK_ASSERT(llt->llt_ifp);
2326 	KASSERT(l3addr->sa_family == AF_INET6,
2327 	    ("sin_family %d", l3addr->sa_family));
2328 	KASSERT((flags & (LLE_UNLOCKED | LLE_EXCLUSIVE)) !=
2329 	    (LLE_UNLOCKED | LLE_EXCLUSIVE),
2330 	    ("wrong lle request flags: %#x", flags));
2331 
2332 	lle = in6_lltable_find_dst(llt, &sin6->sin6_addr);
2333 	if (lle == NULL)
2334 		return (NULL);
2335 	if (flags & LLE_UNLOCKED)
2336 		return (lle);
2337 
2338 	if (flags & LLE_EXCLUSIVE)
2339 		LLE_WLOCK(lle);
2340 	else
2341 		LLE_RLOCK(lle);
2342 
2343 	/*
2344 	 * If the afdata lock is not held, the LLE may have been unlinked while
2345 	 * we were blocked on the LLE lock.  Check for this case.
2346 	 */
2347 	if (__predict_false((lle->la_flags & LLE_LINKED) == 0)) {
2348 		if (flags & LLE_EXCLUSIVE)
2349 			LLE_WUNLOCK(lle);
2350 		else
2351 			LLE_RUNLOCK(lle);
2352 		return (NULL);
2353 	}
2354 	return (lle);
2355 }
2356 
2357 static int
2358 in6_lltable_dump_entry(struct lltable *llt, struct llentry *lle,
2359     struct sysctl_req *wr)
2360 {
2361 	struct ifnet *ifp = llt->llt_ifp;
2362 	/* XXX stack use */
2363 	struct {
2364 		struct rt_msghdr	rtm;
2365 		struct sockaddr_in6	sin6;
2366 		/*
2367 		 * ndp.c assumes that sdl is word aligned
2368 		 */
2369 #ifdef __LP64__
2370 		uint32_t		pad;
2371 #endif
2372 		struct sockaddr_dl	sdl;
2373 	} ndpc;
2374 	struct sockaddr_dl *sdl;
2375 	int error;
2376 
2377 	bzero(&ndpc, sizeof(ndpc));
2378 	/* skip deleted entries */
2379 	if ((lle->la_flags & LLE_DELETED) == LLE_DELETED)
2380 		return (0);
2381 	/* Skip if jailed and not a valid IP of the prison. */
2382 	lltable_fill_sa_entry(lle, (struct sockaddr *)&ndpc.sin6);
2383 	if (prison_if(wr->td->td_ucred, (struct sockaddr *)&ndpc.sin6) != 0)
2384 		return (0);
2385 	/*
2386 	 * produce a msg made of:
2387 	 *  struct rt_msghdr;
2388 	 *  struct sockaddr_in6 (IPv6)
2389 	 *  struct sockaddr_dl;
2390 	 */
2391 	ndpc.rtm.rtm_msglen = sizeof(ndpc);
2392 	ndpc.rtm.rtm_version = RTM_VERSION;
2393 	ndpc.rtm.rtm_type = RTM_GET;
2394 	ndpc.rtm.rtm_flags = RTF_UP;
2395 	ndpc.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
2396 	if (V_deembed_scopeid)
2397 		sa6_recoverscope(&ndpc.sin6);
2398 
2399 	/* publish */
2400 	if (lle->la_flags & LLE_PUB)
2401 		ndpc.rtm.rtm_flags |= RTF_ANNOUNCE;
2402 
2403 	sdl = &ndpc.sdl;
2404 	sdl->sdl_family = AF_LINK;
2405 	sdl->sdl_len = sizeof(*sdl);
2406 	sdl->sdl_index = ifp->if_index;
2407 	sdl->sdl_type = ifp->if_type;
2408 	if ((lle->la_flags & LLE_VALID) == LLE_VALID) {
2409 		sdl->sdl_alen = ifp->if_addrlen;
2410 		bcopy(lle->ll_addr, LLADDR(sdl), ifp->if_addrlen);
2411 	} else {
2412 		sdl->sdl_alen = 0;
2413 		bzero(LLADDR(sdl), ifp->if_addrlen);
2414 	}
2415 	if (lle->la_expire != 0)
2416 		ndpc.rtm.rtm_rmx.rmx_expire = lle->la_expire +
2417 		    lle->lle_remtime / hz + time_second - time_uptime;
2418 	ndpc.rtm.rtm_flags |= (RTF_HOST | RTF_LLDATA);
2419 	if (lle->la_flags & LLE_STATIC)
2420 		ndpc.rtm.rtm_flags |= RTF_STATIC;
2421 	if (lle->la_flags & LLE_IFADDR)
2422 		ndpc.rtm.rtm_flags |= RTF_PINNED;
2423 	if (lle->ln_router != 0)
2424 		ndpc.rtm.rtm_flags |= RTF_GATEWAY;
2425 	ndpc.rtm.rtm_rmx.rmx_pksent = lle->la_asked;
2426 	/* Store state in rmx_weight value */
2427 	ndpc.rtm.rtm_rmx.rmx_state = lle->ln_state;
2428 	ndpc.rtm.rtm_index = ifp->if_index;
2429 	error = SYSCTL_OUT(wr, &ndpc, sizeof(ndpc));
2430 
2431 	return (error);
2432 }
2433 
2434 static struct lltable *
2435 in6_lltattach(struct ifnet *ifp)
2436 {
2437 	struct lltable *llt;
2438 
2439 	llt = lltable_allocate_htbl(IN6_LLTBL_DEFAULT_HSIZE);
2440 	llt->llt_af = AF_INET6;
2441 	llt->llt_ifp = ifp;
2442 
2443 	llt->llt_lookup = in6_lltable_lookup;
2444 	llt->llt_alloc_entry = in6_lltable_alloc;
2445 	llt->llt_delete_entry = in6_lltable_delete_entry;
2446 	llt->llt_dump_entry = in6_lltable_dump_entry;
2447 	llt->llt_hash = in6_lltable_hash;
2448 	llt->llt_fill_sa_entry = in6_lltable_fill_sa_entry;
2449 	llt->llt_free_entry = in6_lltable_free_entry;
2450 	llt->llt_match_prefix = in6_lltable_match_prefix;
2451 	llt->llt_mark_used = in6_lltable_mark_used;
2452  	lltable_link(llt);
2453 
2454 	return (llt);
2455 }
2456 
2457 void *
2458 in6_domifattach(struct ifnet *ifp)
2459 {
2460 	struct in6_ifextra *ext;
2461 
2462 	/* There are not IPv6-capable interfaces. */
2463 	switch (ifp->if_type) {
2464 	case IFT_PFLOG:
2465 	case IFT_PFSYNC:
2466 	case IFT_USB:
2467 		return (NULL);
2468 	}
2469 	ext = (struct in6_ifextra *)malloc(sizeof(*ext), M_IFADDR, M_WAITOK);
2470 	bzero(ext, sizeof(*ext));
2471 
2472 	ext->in6_ifstat = malloc(sizeof(counter_u64_t) *
2473 	    sizeof(struct in6_ifstat) / sizeof(uint64_t), M_IFADDR, M_WAITOK);
2474 	COUNTER_ARRAY_ALLOC(ext->in6_ifstat,
2475 	    sizeof(struct in6_ifstat) / sizeof(uint64_t), M_WAITOK);
2476 
2477 	ext->icmp6_ifstat = malloc(sizeof(counter_u64_t) *
2478 	    sizeof(struct icmp6_ifstat) / sizeof(uint64_t), M_IFADDR,
2479 	    M_WAITOK);
2480 	COUNTER_ARRAY_ALLOC(ext->icmp6_ifstat,
2481 	    sizeof(struct icmp6_ifstat) / sizeof(uint64_t), M_WAITOK);
2482 
2483 	ext->nd_ifinfo = nd6_ifattach(ifp);
2484 	ext->scope6_id = scope6_ifattach(ifp);
2485 	ext->lltable = in6_lltattach(ifp);
2486 
2487 	ext->mld_ifinfo = mld_domifattach(ifp);
2488 
2489 	return ext;
2490 }
2491 
2492 int
2493 in6_domifmtu(struct ifnet *ifp)
2494 {
2495 	if (ifp->if_afdata[AF_INET6] == NULL)
2496 		return ifp->if_mtu;
2497 
2498 	return (IN6_LINKMTU(ifp));
2499 }
2500 
2501 void
2502 in6_domifdetach(struct ifnet *ifp, void *aux)
2503 {
2504 	struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2505 
2506 	mld_domifdetach(ifp);
2507 	scope6_ifdetach(ext->scope6_id);
2508 	nd6_ifdetach(ifp, ext->nd_ifinfo);
2509 	lltable_free(ext->lltable);
2510 	COUNTER_ARRAY_FREE(ext->in6_ifstat,
2511 	    sizeof(struct in6_ifstat) / sizeof(uint64_t));
2512 	free(ext->in6_ifstat, M_IFADDR);
2513 	COUNTER_ARRAY_FREE(ext->icmp6_ifstat,
2514 	    sizeof(struct icmp6_ifstat) / sizeof(uint64_t));
2515 	free(ext->icmp6_ifstat, M_IFADDR);
2516 	free(ext, M_IFADDR);
2517 }
2518 
2519 /*
2520  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2521  * v4 mapped addr or v4 compat addr
2522  */
2523 void
2524 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2525 {
2526 
2527 	bzero(sin, sizeof(*sin));
2528 	sin->sin_len = sizeof(struct sockaddr_in);
2529 	sin->sin_family = AF_INET;
2530 	sin->sin_port = sin6->sin6_port;
2531 	sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
2532 }
2533 
2534 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2535 void
2536 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2537 {
2538 	bzero(sin6, sizeof(*sin6));
2539 	sin6->sin6_len = sizeof(struct sockaddr_in6);
2540 	sin6->sin6_family = AF_INET6;
2541 	sin6->sin6_port = sin->sin_port;
2542 	sin6->sin6_addr.s6_addr32[0] = 0;
2543 	sin6->sin6_addr.s6_addr32[1] = 0;
2544 	sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2545 	sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2546 }
2547 
2548 /* Convert sockaddr_in6 into sockaddr_in. */
2549 void
2550 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2551 {
2552 	struct sockaddr_in *sin_p;
2553 	struct sockaddr_in6 sin6;
2554 
2555 	/*
2556 	 * Save original sockaddr_in6 addr and convert it
2557 	 * to sockaddr_in.
2558 	 */
2559 	sin6 = *(struct sockaddr_in6 *)nam;
2560 	sin_p = (struct sockaddr_in *)nam;
2561 	in6_sin6_2_sin(sin_p, &sin6);
2562 }
2563 
2564 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2565 void
2566 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2567 {
2568 	struct sockaddr_in *sin_p;
2569 	struct sockaddr_in6 *sin6_p;
2570 
2571 	sin6_p = malloc(sizeof *sin6_p, M_SONAME, M_WAITOK);
2572 	sin_p = (struct sockaddr_in *)*nam;
2573 	in6_sin_2_v4mapsin6(sin_p, sin6_p);
2574 	free(*nam, M_SONAME);
2575 	*nam = (struct sockaddr *)sin6_p;
2576 }
2577