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