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