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