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