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