xref: /netbsd-src/sys/netinet6/in6.c (revision aef5eb5f59cdfe8314f1b5f78ac04eb144e44010)
1 /*	$NetBSD: in6.c,v 1.286 2022/09/20 02:23:37 knakahara Exp $	*/
2 /*	$KAME: in6.c,v 1.198 2001/07/18 09:12:38 itojun Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)in.c	8.2 (Berkeley) 11/15/93
62  */
63 
64 #include <sys/cdefs.h>
65 __KERNEL_RCSID(0, "$NetBSD: in6.c,v 1.286 2022/09/20 02:23:37 knakahara Exp $");
66 
67 #ifdef _KERNEL_OPT
68 #include "opt_inet.h"
69 #include "opt_compat_netbsd.h"
70 #include "opt_net_mpsafe.h"
71 #endif
72 
73 #include <sys/param.h>
74 #include <sys/ioctl.h>
75 #include <sys/errno.h>
76 #include <sys/malloc.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/sockio.h>
80 #include <sys/systm.h>
81 #include <sys/proc.h>
82 #include <sys/time.h>
83 #include <sys/kernel.h>
84 #include <sys/syslog.h>
85 #include <sys/kauth.h>
86 #include <sys/cprng.h>
87 #include <sys/kmem.h>
88 
89 #include <net/if.h>
90 #include <net/if_types.h>
91 #include <net/if_llatbl.h>
92 #include <net/if_ether.h>
93 #include <net/if_dl.h>
94 #include <net/pfil.h>
95 #include <net/route.h>
96 
97 #include <netinet/in.h>
98 #include <netinet/in_var.h>
99 
100 #include <netinet/ip6.h>
101 #include <netinet6/ip6_var.h>
102 #include <netinet6/nd6.h>
103 #include <netinet6/mld6_var.h>
104 #include <netinet6/ip6_mroute.h>
105 #include <netinet6/in6_ifattach.h>
106 #include <netinet6/scope6_var.h>
107 
108 #ifdef COMPAT_50
109 #include <compat/netinet6/in6_var.h>
110 #endif
111 #ifdef COMPAT_90
112 #include <compat/netinet6/in6_var.h>
113 #include <compat/netinet6/nd6.h>
114 #endif
115 
116 MALLOC_DEFINE(M_IP6OPT, "ip6_options", "IPv6 options");
117 
118 /* enable backward compatibility code for obsoleted ioctls */
119 #define COMPAT_IN6IFIOCTL
120 
121 #ifdef	IN6_DEBUG
122 #define	IN6_DPRINTF(__fmt, ...)	printf(__fmt, __VA_ARGS__)
123 #else
124 #define	IN6_DPRINTF(__fmt, ...)	do { } while (/*CONSTCOND*/0)
125 #endif /* IN6_DEBUG */
126 
127 /*
128  * Definitions of some constant IP6 addresses.
129  */
130 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
131 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
132 const struct in6_addr in6addr_nodelocal_allnodes =
133 	IN6ADDR_NODELOCAL_ALLNODES_INIT;
134 const struct in6_addr in6addr_linklocal_allnodes =
135 	IN6ADDR_LINKLOCAL_ALLNODES_INIT;
136 const struct in6_addr in6addr_linklocal_allrouters =
137 	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
138 
139 const struct in6_addr in6mask0 = IN6MASK0;
140 const struct in6_addr in6mask32 = IN6MASK32;
141 const struct in6_addr in6mask64 = IN6MASK64;
142 const struct in6_addr in6mask96 = IN6MASK96;
143 const struct in6_addr in6mask128 = IN6MASK128;
144 
145 const struct sockaddr_in6 sa6_any = {sizeof(sa6_any), AF_INET6,
146 				     0, 0, IN6ADDR_ANY_INIT, 0};
147 
148 struct pslist_head	in6_ifaddr_list;
149 kmutex_t		in6_ifaddr_lock;
150 
151 static int in6_lifaddr_ioctl(struct socket *, u_long, void *,
152 	struct ifnet *);
153 static int in6_ifaddprefix(struct in6_ifaddr *);
154 static int in6_ifremprefix(struct in6_ifaddr *);
155 static int in6_ifinit(struct ifnet *, struct in6_ifaddr *,
156 	const struct sockaddr_in6 *, int);
157 static void in6_unlink_ifa(struct in6_ifaddr *, struct ifnet *);
158 static int in6_update_ifa1(struct ifnet *, struct in6_aliasreq *,
159     struct in6_ifaddr **, struct psref *, int);
160 
161 void
162 in6_init(void)
163 {
164 
165 	PSLIST_INIT(&in6_ifaddr_list);
166 	mutex_init(&in6_ifaddr_lock, MUTEX_DEFAULT, IPL_NONE);
167 
168 	in6_sysctl_multicast_setup(NULL);
169 }
170 
171 /*
172  * Add ownaddr as loopback rtentry.  We previously add the route only if
173  * necessary (ex. on a p2p link).  However, since we now manage addresses
174  * separately from prefixes, we should always add the route.  We can't
175  * rely on the cloning mechanism from the corresponding interface route
176  * any more.
177  */
178 void
179 in6_ifaddlocal(struct ifaddr *ifa)
180 {
181 
182 	if (IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &in6addr_any) ||
183 	    (ifa->ifa_ifp->if_flags & IFF_POINTOPOINT &&
184 	    IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), IFA_DSTIN6(ifa))))
185 	{
186 		rt_addrmsg(RTM_NEWADDR, ifa);
187 		return;
188 	}
189 
190 	rt_ifa_addlocal(ifa);
191 }
192 
193 /*
194  * Remove loopback rtentry of ownaddr generated by in6_ifaddlocal(),
195  * if it exists.
196  */
197 void
198 in6_ifremlocal(struct ifaddr *ifa)
199 {
200 	struct in6_ifaddr *ia;
201 	struct ifaddr *alt_ifa = NULL;
202 	int ia_count = 0;
203 	struct psref psref;
204 	int s;
205 
206 	/*
207 	 * Some of BSD variants do not remove cloned routes
208 	 * from an interface direct route, when removing the direct route
209 	 * (see comments in net/net_osdep.h).  Even for variants that do remove
210 	 * cloned routes, they could fail to remove the cloned routes when
211 	 * we handle multiple addresses that share a common prefix.
212 	 * So, we should remove the route corresponding to the deleted address.
213 	 */
214 
215 	/*
216 	 * Delete the entry only if exactly one ifaddr matches the
217 	 * address, ifa->ifa_addr.
218 	 *
219 	 * If more than one ifaddr matches, replace the ifaddr in
220 	 * the routing table, rt_ifa, with a different ifaddr than
221 	 * the one we are purging, ifa.  It is important to do
222 	 * this, or else the routing table can accumulate dangling
223 	 * pointers rt->rt_ifa->ifa_ifp to destroyed interfaces,
224 	 * which will lead to crashes, later.  (More than one ifaddr
225 	 * can match if we assign the same address to multiple---probably
226 	 * p2p---interfaces.)
227 	 *
228 	 * XXX An old comment at this place said, "we should avoid
229 	 * XXX such a configuration [i.e., interfaces with the same
230 	 * XXX addressed assigned --ed.] in IPv6...".  I do not
231 	 * XXX agree, especially now that I have fixed the dangling
232 	 * XXX ifp-pointers bug.
233 	 */
234 	s = pserialize_read_enter();
235 	IN6_ADDRLIST_READER_FOREACH(ia) {
236 		if (!IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ia->ia_addr.sin6_addr))
237 			continue;
238 		if (ia->ia_ifp != ifa->ifa_ifp)
239 			alt_ifa = &ia->ia_ifa;
240 		if (++ia_count > 1 && alt_ifa != NULL)
241 			break;
242 	}
243 	if (ia_count > 1 && alt_ifa != NULL)
244 		ifa_acquire(alt_ifa, &psref);
245 	pserialize_read_exit(s);
246 
247 	if (ia_count == 0)
248 		return;
249 
250 	rt_ifa_remlocal(ifa, ia_count == 1 ? NULL : alt_ifa);
251 
252 	if (ia_count > 1 && alt_ifa != NULL)
253 		ifa_release(alt_ifa, &psref);
254 }
255 
256 /* Add prefix route for the network. */
257 static int
258 in6_ifaddprefix(struct in6_ifaddr *ia)
259 {
260 	int error, flags = 0;
261 
262 	if (in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) == 128) {
263 		if (ia->ia_dstaddr.sin6_family != AF_INET6)
264 			/* We don't need to install a host route. */
265 			return 0;
266 		flags |= RTF_HOST;
267 	}
268 
269 	/* Is this a connected route for neighbour discovery? */
270 	if (nd6_need_cache(ia->ia_ifp))
271 		flags |= RTF_CONNECTED;
272 
273 	if ((error = rtinit(&ia->ia_ifa, RTM_ADD, RTF_UP | flags)) == 0)
274 		ia->ia_flags |= IFA_ROUTE;
275 	else if (error == EEXIST)
276 		/* Existence of the route is not an error. */
277 		error = 0;
278 
279 	return error;
280 }
281 
282 static int
283 in6_rt_ifa_matcher(struct rtentry *rt, void *v)
284 {
285 	struct ifaddr *ifa = v;
286 
287 	if (rt->rt_ifa == ifa)
288 		return 1;
289 	else
290 		return 0;
291 }
292 
293 /* Delete network prefix route if present.
294  * Re-add it to another address if the prefix matches. */
295 static int
296 in6_ifremprefix(struct in6_ifaddr *target)
297 {
298 	int error, s;
299 	struct in6_ifaddr *ia;
300 
301 	if ((target->ia_flags & IFA_ROUTE) == 0)
302 		return 0;
303 
304 	s = pserialize_read_enter();
305 	IN6_ADDRLIST_READER_FOREACH(ia) {
306 		if (target->ia_dstaddr.sin6_len) {
307 			if (ia->ia_dstaddr.sin6_len == 0 ||
308 			    !IN6_ARE_ADDR_EQUAL(&ia->ia_dstaddr.sin6_addr,
309 			    &target->ia_dstaddr.sin6_addr))
310 				continue;
311 		} else {
312 			if (!IN6_ARE_MASKED_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
313 			    &target->ia_addr.sin6_addr,
314 			    &target->ia_prefixmask.sin6_addr))
315 				continue;
316 		}
317 
318 		/*
319 		 * if we got a matching prefix route, move IFA_ROUTE to him
320 		 */
321 		if ((ia->ia_flags & IFA_ROUTE) == 0) {
322 			struct psref psref;
323 			int bound = curlwp_bind();
324 
325 			ia6_acquire(ia, &psref);
326 			pserialize_read_exit(s);
327 
328 			rtinit(&target->ia_ifa, RTM_DELETE, 0);
329 			target->ia_flags &= ~IFA_ROUTE;
330 
331 			error = in6_ifaddprefix(ia);
332 
333 			if (!ISSET(target->ia_ifa.ifa_flags, IFA_DESTROYING))
334 				goto skip;
335 			/*
336 			 * Replace rt_ifa of routes that have the removing address
337 			 * with the new address.
338 			 */
339 			rt_replace_ifa_matched_entries(AF_INET6,
340 			    in6_rt_ifa_matcher, &target->ia_ifa, &ia->ia_ifa);
341 
342 		skip:
343 			ia6_release(ia, &psref);
344 			curlwp_bindx(bound);
345 
346 			return error;
347 		}
348 	}
349 	pserialize_read_exit(s);
350 
351 	/*
352 	 * noone seem to have prefix route.  remove it.
353 	 */
354 	rtinit(&target->ia_ifa, RTM_DELETE, 0);
355 	target->ia_flags &= ~IFA_ROUTE;
356 
357 	if (ISSET(target->ia_ifa.ifa_flags, IFA_DESTROYING)) {
358 		/* Remove routes that have the removing address as rt_ifa. */
359 		rt_delete_matched_entries(AF_INET6, in6_rt_ifa_matcher,
360 		    &target->ia_ifa, true);
361 	}
362 
363 	return 0;
364 }
365 
366 int
367 in6_mask2len(struct in6_addr *mask, u_char *lim0)
368 {
369 	int x = 0, y;
370 	u_char *lim = lim0, *p;
371 
372 	/* ignore the scope_id part */
373 	if (lim0 == NULL || lim0 - (u_char *)mask > sizeof(*mask))
374 		lim = (u_char *)mask + sizeof(*mask);
375 	for (p = (u_char *)mask; p < lim; x++, p++) {
376 		if (*p != 0xff)
377 			break;
378 	}
379 	y = 0;
380 	if (p < lim) {
381 		for (y = 0; y < NBBY; y++) {
382 			if ((*p & (0x80 >> y)) == 0)
383 				break;
384 		}
385 	}
386 
387 	/*
388 	 * when the limit pointer is given, do a stricter check on the
389 	 * remaining bits.
390 	 */
391 	if (p < lim) {
392 		if (y != 0 && (*p & (0x00ff >> y)) != 0)
393 			return -1;
394 		for (p = p + 1; p < lim; p++)
395 			if (*p != 0)
396 				return -1;
397 	}
398 
399 	return x * NBBY + y;
400 }
401 
402 #define ifa2ia6(ifa)	((struct in6_ifaddr *)(ifa))
403 #define ia62ifa(ia6)	(&((ia6)->ia_ifa))
404 
405 static int
406 in6_control1(struct socket *so, u_long cmd, void *data, struct ifnet *ifp)
407 {
408 	struct	in6_ifreq *ifr = (struct in6_ifreq *)data;
409 	struct	in6_ifaddr *ia = NULL;
410 	struct	in6_aliasreq *ifra = (struct in6_aliasreq *)data;
411 	struct sockaddr_in6 *sa6;
412 	int error, bound;
413 	struct psref psref;
414 
415 	switch (cmd) {
416 	case SIOCAADDRCTL_POLICY:
417 	case SIOCDADDRCTL_POLICY:
418 		/* Privileged. */
419 		return in6_src_ioctl(cmd, data);
420 	/*
421 	 * XXX: Fix me, once we fix SIOCSIFADDR, SIOCIFDSTADDR, etc.
422 	 */
423 	case SIOCSIFADDR:
424 	case SIOCSIFDSTADDR:
425 	case SIOCSIFBRDADDR:
426 	case SIOCSIFNETMASK:
427 		return EOPNOTSUPP;
428 	case SIOCGETSGCNT_IN6:
429 	case SIOCGETMIFCNT_IN6:
430 		return mrt6_ioctl(cmd, data);
431 	case SIOCGIFADDRPREF:
432 	case SIOCSIFADDRPREF:
433 		if (ifp == NULL)
434 			return EINVAL;
435 		return ifaddrpref_ioctl(so, cmd, data, ifp);
436 	}
437 
438 	if (ifp == NULL)
439 		return EOPNOTSUPP;
440 
441 	switch (cmd) {
442 #ifdef OSIOCSIFINFO_IN6_90
443 	case OSIOCSIFINFO_FLAGS_90:
444 	case OSIOCSIFINFO_IN6_90:
445 	case OSIOCSDEFIFACE_IN6:
446 	case OSIOCSNDFLUSH_IN6:
447 	case OSIOCSPFXFLUSH_IN6:
448 	case OSIOCSRTRFLUSH_IN6:
449 #endif
450 	case SIOCSIFINFO_FLAGS:
451 	case SIOCSIFINFO_IN6:
452 		/* Privileged. */
453 		/* FALLTHROUGH */
454 #ifdef OSIOCGIFINFO_IN6
455 	case OSIOCGIFINFO_IN6:
456 #endif
457 #ifdef OSIOCGIFINFO_IN6_90
458 	case OSIOCGDRLST_IN6:
459 	case OSIOCGPRLST_IN6:
460 	case OSIOCGIFINFO_IN6_90:
461 	case OSIOCGDEFIFACE_IN6:
462 #endif
463 	case SIOCGIFINFO_IN6:
464 	case SIOCGNBRINFO_IN6:
465 		return nd6_ioctl(cmd, data, ifp);
466 	}
467 
468 	switch (cmd) {
469 	case SIOCALIFADDR:
470 	case SIOCDLIFADDR:
471 		/* Privileged. */
472 		/* FALLTHROUGH */
473 	case SIOCGLIFADDR:
474 		return in6_lifaddr_ioctl(so, cmd, data, ifp);
475 	}
476 
477 	/*
478 	 * Find address for this interface, if it exists.
479 	 *
480 	 * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
481 	 * only, and used the first interface address as the target of other
482 	 * operations (without checking ifra_addr).  This was because netinet
483 	 * code/API assumed at most 1 interface address per interface.
484 	 * Since IPv6 allows a node to assign multiple addresses
485 	 * on a single interface, we almost always look and check the
486 	 * presence of ifra_addr, and reject invalid ones here.
487 	 * It also decreases duplicated code among SIOC*_IN6 operations.
488 	 */
489 	switch (cmd) {
490 	case SIOCAIFADDR_IN6:
491 #ifdef OSIOCAIFADDR_IN6
492 	case OSIOCAIFADDR_IN6:
493 #endif
494 #ifdef OSIOCSIFPHYADDR_IN6
495 	case OSIOCSIFPHYADDR_IN6:
496 #endif
497 	case SIOCSIFPHYADDR_IN6:
498 		sa6 = &ifra->ifra_addr;
499 		break;
500 	case SIOCSIFADDR_IN6:
501 	case SIOCGIFADDR_IN6:
502 	case SIOCSIFDSTADDR_IN6:
503 	case SIOCSIFNETMASK_IN6:
504 	case SIOCGIFDSTADDR_IN6:
505 	case SIOCGIFNETMASK_IN6:
506 	case SIOCDIFADDR_IN6:
507 	case SIOCGIFPSRCADDR_IN6:
508 	case SIOCGIFPDSTADDR_IN6:
509 	case SIOCGIFAFLAG_IN6:
510 	case SIOCGIFALIFETIME_IN6:
511 #ifdef OSIOCGIFALIFETIME_IN6
512 	case OSIOCGIFALIFETIME_IN6:
513 #endif
514 	case SIOCGIFSTAT_IN6:
515 	case SIOCGIFSTAT_ICMP6:
516 		sa6 = &ifr->ifr_addr;
517 		break;
518 	default:
519 		sa6 = NULL;
520 		break;
521 	}
522 
523 	error = 0;
524 	bound = curlwp_bind();
525 	if (sa6 && sa6->sin6_family == AF_INET6) {
526 		if (sa6->sin6_scope_id != 0)
527 			error = sa6_embedscope(sa6, 0);
528 		else
529 			error = in6_setscope(&sa6->sin6_addr, ifp, NULL);
530 		if (error != 0)
531 			goto out;
532 		ia = in6ifa_ifpwithaddr_psref(ifp, &sa6->sin6_addr, &psref);
533 	} else
534 		ia = NULL;
535 
536 	switch (cmd) {
537 	case SIOCSIFADDR_IN6:
538 	case SIOCSIFDSTADDR_IN6:
539 	case SIOCSIFNETMASK_IN6:
540 		/*
541 		 * Since IPv6 allows a node to assign multiple addresses
542 		 * on a single interface, SIOCSIFxxx ioctls are deprecated.
543 		 */
544 		error = EINVAL;
545 		goto release;
546 
547 	case SIOCDIFADDR_IN6:
548 		/*
549 		 * for IPv4, we look for existing in_ifaddr here to allow
550 		 * "ifconfig if0 delete" to remove the first IPv4 address on
551 		 * the interface.  For IPv6, as the spec allows multiple
552 		 * interface address from the day one, we consider "remove the
553 		 * first one" semantics to be not preferable.
554 		 */
555 		if (ia == NULL) {
556 			error = EADDRNOTAVAIL;
557 			goto out;
558 		}
559 #ifdef OSIOCAIFADDR_IN6
560 		/* FALLTHROUGH */
561 	case OSIOCAIFADDR_IN6:
562 #endif
563 		/* FALLTHROUGH */
564 	case SIOCAIFADDR_IN6:
565 		/*
566 		 * We always require users to specify a valid IPv6 address for
567 		 * the corresponding operation.
568 		 */
569 		if (ifra->ifra_addr.sin6_family != AF_INET6 ||
570 		    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6)) {
571 			error = EAFNOSUPPORT;
572 			goto release;
573 		}
574 		/* Privileged. */
575 
576 		break;
577 
578 	case SIOCGIFADDR_IN6:
579 		/* This interface is basically deprecated. use SIOCGIFCONF. */
580 		/* FALLTHROUGH */
581 	case SIOCGIFAFLAG_IN6:
582 	case SIOCGIFNETMASK_IN6:
583 	case SIOCGIFDSTADDR_IN6:
584 	case SIOCGIFALIFETIME_IN6:
585 #ifdef OSIOCGIFALIFETIME_IN6
586 	case OSIOCGIFALIFETIME_IN6:
587 #endif
588 		/* must think again about its semantics */
589 		if (ia == NULL) {
590 			error = EADDRNOTAVAIL;
591 			goto out;
592 		}
593 		break;
594 	}
595 
596 	switch (cmd) {
597 
598 	case SIOCGIFADDR_IN6:
599 		ifr->ifr_addr = ia->ia_addr;
600 		error = sa6_recoverscope(&ifr->ifr_addr);
601 		break;
602 
603 	case SIOCGIFDSTADDR_IN6:
604 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
605 			error = EINVAL;
606 			break;
607 		}
608 		/*
609 		 * XXX: should we check if ifa_dstaddr is NULL and return
610 		 * an error?
611 		 */
612 		ifr->ifr_dstaddr = ia->ia_dstaddr;
613 		error = sa6_recoverscope(&ifr->ifr_dstaddr);
614 		break;
615 
616 	case SIOCGIFNETMASK_IN6:
617 		ifr->ifr_addr = ia->ia_prefixmask;
618 		break;
619 
620 	case SIOCGIFAFLAG_IN6:
621 		ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
622 		break;
623 
624 	case SIOCGIFSTAT_IN6:
625 		if (ifp == NULL) {
626 			error = EINVAL;
627 			break;
628 		}
629 		memset(&ifr->ifr_ifru.ifru_stat, 0,
630 		    sizeof(ifr->ifr_ifru.ifru_stat));
631 		ifr->ifr_ifru.ifru_stat =
632 		    *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
633 		break;
634 
635 	case SIOCGIFSTAT_ICMP6:
636 		if (ifp == NULL) {
637 			error = EINVAL;
638 			break;
639 		}
640 		memset(&ifr->ifr_ifru.ifru_icmp6stat, 0,
641 		    sizeof(ifr->ifr_ifru.ifru_icmp6stat));
642 		ifr->ifr_ifru.ifru_icmp6stat =
643 		    *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
644 		break;
645 
646 #ifdef OSIOCGIFALIFETIME_IN6
647 	case OSIOCGIFALIFETIME_IN6:
648 #endif
649 	case SIOCGIFALIFETIME_IN6:
650 		ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
651 		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
652 			time_t maxexpire;
653 			struct in6_addrlifetime *retlt =
654 			    &ifr->ifr_ifru.ifru_lifetime;
655 
656 			/*
657 			 * XXX: adjust expiration time assuming time_t is
658 			 * signed.
659 			 */
660 			maxexpire = ((time_t)~0) &
661 			    (time_t)~(1ULL << ((sizeof(maxexpire) * NBBY) - 1));
662 			if (ia->ia6_lifetime.ia6t_vltime <
663 			    maxexpire - ia->ia6_updatetime) {
664 				retlt->ia6t_expire = ia->ia6_updatetime +
665 				    ia->ia6_lifetime.ia6t_vltime;
666 				retlt->ia6t_expire = retlt->ia6t_expire ?
667 				    time_mono_to_wall(retlt->ia6t_expire) :
668 				    0;
669 			} else
670 				retlt->ia6t_expire = maxexpire;
671 		}
672 		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
673 			time_t maxexpire;
674 			struct in6_addrlifetime *retlt =
675 			    &ifr->ifr_ifru.ifru_lifetime;
676 
677 			/*
678 			 * XXX: adjust expiration time assuming time_t is
679 			 * signed.
680 			 */
681 			maxexpire = ((time_t)~0) &
682 			    (time_t)~(1ULL << ((sizeof(maxexpire) * NBBY) - 1));
683 			if (ia->ia6_lifetime.ia6t_pltime <
684 			    maxexpire - ia->ia6_updatetime) {
685 				retlt->ia6t_preferred = ia->ia6_updatetime +
686 				    ia->ia6_lifetime.ia6t_pltime;
687 				retlt->ia6t_preferred = retlt->ia6t_preferred ?
688 				    time_mono_to_wall(retlt->ia6t_preferred) :
689 				    0;
690 			} else
691 				retlt->ia6t_preferred = maxexpire;
692 		}
693 #ifdef OSIOCFIFALIFETIME_IN6
694 		if (cmd == OSIOCFIFALIFETIME_IN6)
695 			in6_addrlifetime_to_in6_addrlifetime50(
696 			    &ifr->ifru.ifru_lifetime);
697 #endif
698 		break;
699 
700 #ifdef OSIOCAIFADDR_IN6
701 	case OSIOCAIFADDR_IN6:
702 		in6_aliasreq50_to_in6_aliasreq(ifra);
703 #endif
704 		/*FALLTHROUGH*/
705 	case SIOCAIFADDR_IN6:
706 	{
707 		struct in6_addrlifetime *lt;
708 
709 		/* reject read-only flags */
710 		if ((ifra->ifra_flags & IN6_IFF_DUPLICATED) != 0 ||
711 		    (ifra->ifra_flags & IN6_IFF_DETACHED) != 0 ||
712 		    (ifra->ifra_flags & IN6_IFF_TENTATIVE) != 0 ||
713 		    (ifra->ifra_flags & IN6_IFF_NODAD) != 0) {
714 			error = EINVAL;
715 			break;
716 		}
717 		/*
718 		 * ia6t_expire and ia6t_preferred won't be used for now,
719 		 * so just in case.
720 		 */
721 		lt = &ifra->ifra_lifetime;
722 		if (lt->ia6t_expire != 0)
723 			lt->ia6t_expire = time_wall_to_mono(lt->ia6t_expire);
724 		if (lt->ia6t_preferred != 0)
725 			lt->ia6t_preferred =
726 			    time_wall_to_mono(lt->ia6t_preferred);
727 		/*
728 		 * make (ia == NULL) or update (ia != NULL) the interface
729 		 * address structure, and link it to the list.
730 		 */
731 		int s = splsoftnet();
732 		error = in6_update_ifa1(ifp, ifra, &ia, &psref, 0);
733 		splx(s);
734 		if (error)
735 			break;
736 		pfil_run_addrhooks(if_pfil, cmd, &ia->ia_ifa);
737 		break;
738 	}
739 
740 	case SIOCDIFADDR_IN6:
741 		ia6_release(ia, &psref);
742 		ifaref(&ia->ia_ifa);
743 		in6_purgeaddr(&ia->ia_ifa);
744 		pfil_run_addrhooks(if_pfil, cmd, &ia->ia_ifa);
745 		ifafree(&ia->ia_ifa);
746 		ia = NULL;
747 		break;
748 
749 	default:
750 		error = ENOTTY;
751 	}
752 release:
753 	ia6_release(ia, &psref);
754 out:
755 	curlwp_bindx(bound);
756 	return error;
757 }
758 
759 int
760 in6_control(struct socket *so, u_long cmd, void *data, struct ifnet *ifp)
761 {
762 	int error, s;
763 
764 	switch (cmd) {
765 #ifdef OSIOCSIFINFO_IN6_90
766 	case OSIOCSIFINFO_FLAGS_90:
767 	case OSIOCSIFINFO_IN6_90:
768 	case OSIOCSDEFIFACE_IN6:
769 	case OSIOCSNDFLUSH_IN6:
770 	case OSIOCSPFXFLUSH_IN6:
771 	case OSIOCSRTRFLUSH_IN6:
772 #endif
773 	case SIOCSIFINFO_FLAGS:
774 	case SIOCSIFINFO_IN6:
775 
776 	case SIOCALIFADDR:
777 	case SIOCDLIFADDR:
778 
779 	case SIOCDIFADDR_IN6:
780 #ifdef OSIOCAIFADDR_IN6
781 	case OSIOCAIFADDR_IN6:
782 #endif
783 	case SIOCAIFADDR_IN6:
784 
785 	case SIOCAADDRCTL_POLICY:
786 	case SIOCDADDRCTL_POLICY:
787 
788 		if (kauth_authorize_network(kauth_cred_get(),
789 		    KAUTH_NETWORK_SOCKET,
790 		    KAUTH_REQ_NETWORK_SOCKET_SETPRIV,
791 		    so, NULL, NULL))
792 			return EPERM;
793 		break;
794 	}
795 
796 	s = splsoftnet();
797 #ifndef NET_MPSAFE
798 	KASSERT(KERNEL_LOCKED_P());
799 #endif
800 	error = in6_control1(so , cmd, data, ifp);
801 	splx(s);
802 	return error;
803 }
804 
805 static int
806 in6_get_llsol_addr(struct in6_addr *llsol, struct ifnet *ifp,
807     struct in6_addr *ip6)
808 {
809 	int error;
810 
811 	memset(llsol, 0, sizeof(struct in6_addr));
812 	llsol->s6_addr16[0] = htons(0xff02);
813 	llsol->s6_addr32[1] = 0;
814 	llsol->s6_addr32[2] = htonl(1);
815 	llsol->s6_addr32[3] = ip6->s6_addr32[3];
816 	llsol->s6_addr8[12] = 0xff;
817 
818 	error = in6_setscope(llsol, ifp, NULL);
819 	if (error != 0) {
820 		/* XXX: should not happen */
821 		log(LOG_ERR, "%s: in6_setscope failed\n", __func__);
822 	}
823 
824 	return error;
825 }
826 
827 static int
828 in6_join_mcastgroups(struct in6_aliasreq *ifra, struct in6_ifaddr *ia,
829     struct ifnet *ifp, int flags)
830 {
831 	int error;
832 	struct sockaddr_in6 mltaddr, mltmask;
833 	struct in6_multi_mship *imm;
834 	struct in6_addr llsol;
835 	struct rtentry *rt;
836 	int dad_delay;
837 	char ip6buf[INET6_ADDRSTRLEN];
838 
839 	/* join solicited multicast addr for new host id */
840 	error = in6_get_llsol_addr(&llsol, ifp, &ifra->ifra_addr.sin6_addr);
841 	if (error != 0)
842 		goto out;
843 	dad_delay = 0;
844 	if ((flags & IN6_IFAUPDATE_DADDELAY)) {
845 		/*
846 		 * We need a random delay for DAD on the address
847 		 * being configured.  It also means delaying
848 		 * transmission of the corresponding MLD report to
849 		 * avoid report collision.
850 		 * [draft-ietf-ipv6-rfc2462bis-02.txt]
851 		 */
852 		dad_delay = cprng_fast32() % (MAX_RTR_SOLICITATION_DELAY * hz);
853 	}
854 
855 #define	MLTMASK_LEN  4	/* mltmask's masklen (=32bit=4octet) */
856 	/* join solicited multicast addr for new host id */
857 	imm = in6_joingroup(ifp, &llsol, &error, dad_delay);
858 	if (!imm) {
859 		nd6log(LOG_ERR,
860 		    "addmulti failed for %s on %s (errno=%d)\n",
861 		    IN6_PRINT(ip6buf, &llsol), if_name(ifp), error);
862 		goto out;
863 	}
864 	mutex_enter(&in6_ifaddr_lock);
865 	LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
866 	mutex_exit(&in6_ifaddr_lock);
867 
868 	sockaddr_in6_init(&mltmask, &in6mask32, 0, 0, 0);
869 
870 	/*
871 	 * join link-local all-nodes address
872 	 */
873 	sockaddr_in6_init(&mltaddr, &in6addr_linklocal_allnodes,
874 	    0, 0, 0);
875 	if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
876 		goto out; /* XXX: should not fail */
877 
878 	/*
879 	 * XXX: do we really need this automatic routes?
880 	 * We should probably reconsider this stuff.  Most applications
881 	 * actually do not need the routes, since they usually specify
882 	 * the outgoing interface.
883 	 */
884 	rt = rtalloc1(sin6tosa(&mltaddr), 0);
885 	if (rt) {
886 		if (memcmp(&mltaddr.sin6_addr,
887 		    &satocsin6(rt_getkey(rt))->sin6_addr,
888 		    MLTMASK_LEN)) {
889 			rt_unref(rt);
890 			rt = NULL;
891 		} else if (rt->rt_ifp != ifp) {
892 			IN6_DPRINTF("%s: rt_ifp %p -> %p (%s) "
893 			    "network %04x:%04x::/32 = %04x:%04x::/32\n",
894 			    __func__, rt->rt_ifp, ifp, ifp->if_xname,
895 			    ntohs(mltaddr.sin6_addr.s6_addr16[0]),
896 			    ntohs(mltaddr.sin6_addr.s6_addr16[1]),
897 			    satocsin6(rt_getkey(rt))->sin6_addr.s6_addr16[0],
898 			    satocsin6(rt_getkey(rt))->sin6_addr.s6_addr16[1]);
899 #ifdef NET_MPSAFE
900 			error = rt_update_prepare(rt);
901 			if (error == 0) {
902 				rt_replace_ifa(rt, &ia->ia_ifa);
903 				rt->rt_ifp = ifp;
904 				rt_update_finish(rt);
905 			} else {
906 				/*
907 				 * If error != 0, the rtentry is being
908 				 * destroyed, so doing nothing doesn't
909 				 * matter.
910 				 */
911 			}
912 #else
913 			rt_replace_ifa(rt, &ia->ia_ifa);
914 			rt->rt_ifp = ifp;
915 #endif
916 		}
917 	}
918 	if (!rt) {
919 		struct rt_addrinfo info;
920 
921 		memset(&info, 0, sizeof(info));
922 		info.rti_info[RTAX_DST] = sin6tosa(&mltaddr);
923 		info.rti_info[RTAX_GATEWAY] = sin6tosa(&ia->ia_addr);
924 		info.rti_info[RTAX_NETMASK] = sin6tosa(&mltmask);
925 		info.rti_info[RTAX_IFA] = sin6tosa(&ia->ia_addr);
926 		/* XXX: we need RTF_CONNECTED to fake nd6_rtrequest */
927 		info.rti_flags = RTF_UP | RTF_CONNECTED;
928 		error = rtrequest1(RTM_ADD, &info, NULL);
929 		if (error)
930 			goto out;
931 	} else {
932 		rt_unref(rt);
933 	}
934 	imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
935 	if (!imm) {
936 		nd6log(LOG_WARNING,
937 		    "addmulti failed for %s on %s (errno=%d)\n",
938 		    IN6_PRINT(ip6buf, &mltaddr.sin6_addr),
939 		    if_name(ifp), error);
940 		goto out;
941 	}
942 	mutex_enter(&in6_ifaddr_lock);
943 	LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
944 	mutex_exit(&in6_ifaddr_lock);
945 
946 	/*
947 	 * join node information group address
948 	 */
949 	dad_delay = 0;
950 	if ((flags & IN6_IFAUPDATE_DADDELAY)) {
951 		/*
952 		 * The spec doesn't say anything about delay for this
953 		 * group, but the same logic should apply.
954 		 */
955 		dad_delay = cprng_fast32() % (MAX_RTR_SOLICITATION_DELAY * hz);
956 	}
957 	if (in6_nigroup(ifp, hostname, hostnamelen, &mltaddr) != 0)
958 		;
959 	else if ((imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error,
960 		  dad_delay)) == NULL) { /* XXX jinmei */
961 		nd6log(LOG_WARNING,
962 		    "addmulti failed for %s on %s (errno=%d)\n",
963 		    IN6_PRINT(ip6buf, &mltaddr.sin6_addr),
964 		    if_name(ifp), error);
965 		/* XXX not very fatal, go on... */
966 	} else {
967 		mutex_enter(&in6_ifaddr_lock);
968 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
969 		mutex_exit(&in6_ifaddr_lock);
970 	}
971 
972 
973 	/*
974 	 * join interface-local all-nodes address.
975 	 * (ff01::1%ifN, and ff01::%ifN/32)
976 	 */
977 	mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
978 	if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
979 		goto out; /* XXX: should not fail */
980 
981 	/* XXX: again, do we really need the route? */
982 	rt = rtalloc1(sin6tosa(&mltaddr), 0);
983 	if (rt) {
984 		/* 32bit came from "mltmask" */
985 		if (memcmp(&mltaddr.sin6_addr,
986 		    &satocsin6(rt_getkey(rt))->sin6_addr,
987 		    32 / NBBY)) {
988 			rt_unref(rt);
989 			rt = NULL;
990 		} else if (rt->rt_ifp != ifp) {
991 			IN6_DPRINTF("%s: rt_ifp %p -> %p (%s) "
992 			    "network %04x:%04x::/32 = %04x:%04x::/32\n",
993 			    __func__, rt->rt_ifp, ifp, ifp->if_xname,
994 			    ntohs(mltaddr.sin6_addr.s6_addr16[0]),
995 			    ntohs(mltaddr.sin6_addr.s6_addr16[1]),
996 			    satocsin6(rt_getkey(rt))->sin6_addr.s6_addr16[0],
997 			    satocsin6(rt_getkey(rt))->sin6_addr.s6_addr16[1]);
998 #ifdef NET_MPSAFE
999 			error = rt_update_prepare(rt);
1000 			if (error == 0) {
1001 				rt_replace_ifa(rt, &ia->ia_ifa);
1002 				rt->rt_ifp = ifp;
1003 				rt_update_finish(rt);
1004 			} else {
1005 				/*
1006 				 * If error != 0, the rtentry is being
1007 				 * destroyed, so doing nothing doesn't
1008 				 * matter.
1009 				 */
1010 			}
1011 #else
1012 			rt_replace_ifa(rt, &ia->ia_ifa);
1013 			rt->rt_ifp = ifp;
1014 #endif
1015 		}
1016 	}
1017 	if (!rt) {
1018 		struct rt_addrinfo info;
1019 
1020 		memset(&info, 0, sizeof(info));
1021 		info.rti_info[RTAX_DST] = sin6tosa(&mltaddr);
1022 		info.rti_info[RTAX_GATEWAY] = sin6tosa(&ia->ia_addr);
1023 		info.rti_info[RTAX_NETMASK] = sin6tosa(&mltmask);
1024 		info.rti_info[RTAX_IFA] = sin6tosa(&ia->ia_addr);
1025 		info.rti_flags = RTF_UP | RTF_CONNECTED;
1026 		error = rtrequest1(RTM_ADD, &info, NULL);
1027 		if (error)
1028 			goto out;
1029 #undef	MLTMASK_LEN
1030 	} else {
1031 		rt_unref(rt);
1032 	}
1033 	imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
1034 	if (!imm) {
1035 		nd6log(LOG_WARNING,
1036 		    "addmulti failed for %s on %s (errno=%d)\n",
1037 		    IN6_PRINT(ip6buf, &mltaddr.sin6_addr),
1038 		    if_name(ifp), error);
1039 		goto out;
1040 	} else {
1041 		mutex_enter(&in6_ifaddr_lock);
1042 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
1043 		mutex_exit(&in6_ifaddr_lock);
1044 	}
1045 	return 0;
1046 
1047 out:
1048 	KASSERT(error != 0);
1049 	return error;
1050 }
1051 
1052 /*
1053  * Update parameters of an IPv6 interface address.
1054  * If necessary, a new entry is created and linked into address chains.
1055  * This function is separated from in6_control().
1056  * XXX: should this be performed under splsoftnet()?
1057  */
1058 static int
1059 in6_update_ifa1(struct ifnet *ifp, struct in6_aliasreq *ifra,
1060     struct in6_ifaddr **iap, struct psref *psref, int flags)
1061 {
1062 	int error = 0, hostIsNew = 0, plen = -1;
1063 	struct sockaddr_in6 dst6;
1064 	struct in6_addrlifetime *lt;
1065 	int dad_delay, was_tentative;
1066 	struct in6_ifaddr *ia = iap ? *iap : NULL;
1067 	char ip6buf[INET6_ADDRSTRLEN];
1068 
1069 	KASSERT((iap == NULL && psref == NULL) ||
1070 	    (iap != NULL && psref != NULL));
1071 
1072 	/* Validate parameters */
1073 	if (ifp == NULL || ifra == NULL) /* this maybe redundant */
1074 		return EINVAL;
1075 
1076 	/*
1077 	 * The destination address for a p2p link must have a family
1078 	 * of AF_UNSPEC or AF_INET6.
1079 	 */
1080 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
1081 	    ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
1082 	    ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
1083 		return EAFNOSUPPORT;
1084 	/*
1085 	 * validate ifra_prefixmask.  don't check sin6_family, netmask
1086 	 * does not carry fields other than sin6_len.
1087 	 */
1088 	if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
1089 		return EINVAL;
1090 	/*
1091 	 * Because the IPv6 address architecture is classless, we require
1092 	 * users to specify a (non 0) prefix length (mask) for a new address.
1093 	 * We also require the prefix (when specified) mask is valid, and thus
1094 	 * reject a non-consecutive mask.
1095 	 */
1096 	if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
1097 		return EINVAL;
1098 	if (ifra->ifra_prefixmask.sin6_len != 0) {
1099 		plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
1100 		    (u_char *)&ifra->ifra_prefixmask +
1101 		    ifra->ifra_prefixmask.sin6_len);
1102 		if (plen <= 0)
1103 			return EINVAL;
1104 	} else {
1105 		/*
1106 		 * In this case, ia must not be NULL.  We just use its prefix
1107 		 * length.
1108 		 */
1109 		plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1110 	}
1111 	/*
1112 	 * If the destination address on a p2p interface is specified,
1113 	 * and the address is a scoped one, validate/set the scope
1114 	 * zone identifier.
1115 	 */
1116 	dst6 = ifra->ifra_dstaddr;
1117 	if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) != 0 &&
1118 	    (dst6.sin6_family == AF_INET6)) {
1119 		struct in6_addr in6_tmp;
1120 		u_int32_t zoneid;
1121 
1122 		in6_tmp = dst6.sin6_addr;
1123 		if (in6_setscope(&in6_tmp, ifp, &zoneid))
1124 			return EINVAL; /* XXX: should be impossible */
1125 
1126 		if (dst6.sin6_scope_id != 0) {
1127 			if (dst6.sin6_scope_id != zoneid)
1128 				return EINVAL;
1129 		} else		/* user omit to specify the ID. */
1130 			dst6.sin6_scope_id = zoneid;
1131 
1132 		/* convert into the internal form */
1133 		if (sa6_embedscope(&dst6, 0))
1134 			return EINVAL; /* XXX: should be impossible */
1135 	}
1136 	/*
1137 	 * The destination address can be specified only for a p2p or a
1138 	 * loopback interface.  If specified, the corresponding prefix length
1139 	 * must be 128.
1140 	 */
1141 	if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
1142 #ifdef FORCE_P2PPLEN
1143 		int i;
1144 #endif
1145 
1146 		if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) == 0) {
1147 			/* XXX: noisy message */
1148 			nd6log(LOG_INFO, "a destination can "
1149 			    "be specified for a p2p or a loopback IF only\n");
1150 			return EINVAL;
1151 		}
1152 		if (plen != 128) {
1153 			nd6log(LOG_INFO, "prefixlen should "
1154 			    "be 128 when dstaddr is specified\n");
1155 #ifdef FORCE_P2PPLEN
1156 			/*
1157 			 * To be compatible with old configurations,
1158 			 * such as ifconfig gif0 inet6 2001::1 2001::2
1159 			 * prefixlen 126, we override the specified
1160 			 * prefixmask as if the prefix length was 128.
1161 			 */
1162 			ifra->ifra_prefixmask.sin6_len =
1163 			    sizeof(struct sockaddr_in6);
1164 			for (i = 0; i < 4; i++)
1165 				ifra->ifra_prefixmask.sin6_addr.s6_addr32[i] =
1166 				    0xffffffff;
1167 			plen = 128;
1168 #else
1169 			return EINVAL;
1170 #endif
1171 		}
1172 	}
1173 	/* lifetime consistency check */
1174 	lt = &ifra->ifra_lifetime;
1175 	if (lt->ia6t_pltime > lt->ia6t_vltime)
1176 		return EINVAL;
1177 	if (lt->ia6t_vltime == 0) {
1178 		/*
1179 		 * the following log might be noisy, but this is a typical
1180 		 * configuration mistake or a tool's bug.
1181 		 */
1182 		nd6log(LOG_INFO, "valid lifetime is 0 for %s\n",
1183 		    IN6_PRINT(ip6buf, &ifra->ifra_addr.sin6_addr));
1184 
1185 		if (ia == NULL)
1186 			return 0; /* there's nothing to do */
1187 	}
1188 
1189 	/*
1190 	 * If this is a new address, allocate a new ifaddr and link it
1191 	 * into chains.
1192 	 */
1193 	if (ia == NULL) {
1194 		hostIsNew = 1;
1195 		/*
1196 		 * When in6_update_ifa() is called in a process of a received
1197 		 * RA, it is called under an interrupt context.  So, we should
1198 		 * call malloc with M_NOWAIT.
1199 		 */
1200 		ia = malloc(sizeof(*ia), M_IFADDR, M_NOWAIT|M_ZERO);
1201 		if (ia == NULL)
1202 			return ENOBUFS;
1203 		LIST_INIT(&ia->ia6_memberships);
1204 		/* Initialize the address and masks, and put time stamp */
1205 		ia->ia_ifa.ifa_addr = sin6tosa(&ia->ia_addr);
1206 		ia->ia_addr.sin6_family = AF_INET6;
1207 		ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
1208 		ia->ia6_createtime = time_uptime;
1209 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
1210 			/*
1211 			 * XXX: some functions expect that ifa_dstaddr is not
1212 			 * NULL for p2p interfaces.
1213 			 */
1214 			ia->ia_ifa.ifa_dstaddr = sin6tosa(&ia->ia_dstaddr);
1215 		} else {
1216 			ia->ia_ifa.ifa_dstaddr = NULL;
1217 		}
1218 		ia->ia_ifa.ifa_netmask = sin6tosa(&ia->ia_prefixmask);
1219 
1220 		ia->ia_ifp = ifp;
1221 		IN6_ADDRLIST_ENTRY_INIT(ia);
1222 		ifa_psref_init(&ia->ia_ifa);
1223 	}
1224 
1225 	/* update timestamp */
1226 	ia->ia6_updatetime = time_uptime;
1227 
1228 	/* set prefix mask */
1229 	if (ifra->ifra_prefixmask.sin6_len) {
1230 		if (ia->ia_prefixmask.sin6_len) {
1231 			if (!IN6_ARE_ADDR_EQUAL(&ia->ia_prefixmask.sin6_addr,
1232 			    &ifra->ifra_prefixmask.sin6_addr))
1233 				in6_ifremprefix(ia);
1234 		}
1235 		ia->ia_prefixmask = ifra->ifra_prefixmask;
1236 	}
1237 
1238 	/* Set destination address. */
1239 	if (dst6.sin6_family == AF_INET6) {
1240 		if (!IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr,
1241 		    &ia->ia_dstaddr.sin6_addr))
1242 			in6_ifremprefix(ia);
1243 		ia->ia_dstaddr = dst6;
1244 	}
1245 
1246 	/*
1247 	 * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
1248 	 * to see if the address is deprecated or invalidated, but initialize
1249 	 * these members for applications.
1250 	 */
1251 	ia->ia6_lifetime = ifra->ifra_lifetime;
1252 	if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1253 		ia->ia6_lifetime.ia6t_expire =
1254 		    time_uptime + ia->ia6_lifetime.ia6t_vltime;
1255 	} else
1256 		ia->ia6_lifetime.ia6t_expire = 0;
1257 	if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1258 		ia->ia6_lifetime.ia6t_preferred =
1259 		    time_uptime + ia->ia6_lifetime.ia6t_pltime;
1260 	} else
1261 		ia->ia6_lifetime.ia6t_preferred = 0;
1262 
1263 	/*
1264 	 * configure address flags.
1265 	 * We need to preserve tentative state so DAD works if
1266 	 * something adds the same address before DAD finishes.
1267 	 */
1268 	was_tentative = ia->ia6_flags & (IN6_IFF_TENTATIVE|IN6_IFF_DUPLICATED);
1269 	ia->ia6_flags = ifra->ifra_flags;
1270 
1271 	/*
1272 	 * Make the address tentative before joining multicast addresses,
1273 	 * so that corresponding MLD responses would not have a tentative
1274 	 * source address.
1275 	 */
1276 	ia->ia6_flags &= ~IN6_IFF_DUPLICATED;	/* safety */
1277 	if (ifp->if_link_state == LINK_STATE_DOWN) {
1278 		ia->ia6_flags |= IN6_IFF_DETACHED;
1279 		ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1280 	} else if ((hostIsNew || was_tentative) && if_do_dad(ifp) &&
1281 	           ip6_dad_enabled()) {
1282 		ia->ia6_flags |= IN6_IFF_TENTATIVE;
1283 	}
1284 
1285 	/*
1286 	 * backward compatibility - if IN6_IFF_DEPRECATED is set from the
1287 	 * userland, make it deprecated.
1288 	 */
1289 	if ((ifra->ifra_flags & IN6_IFF_DEPRECATED) != 0) {
1290 		ia->ia6_lifetime.ia6t_pltime = 0;
1291 		ia->ia6_lifetime.ia6t_preferred = time_uptime;
1292 	}
1293 
1294 	if (hostIsNew) {
1295 		/*
1296 		 * We need a reference to ia before calling in6_ifinit.
1297 		 * Otherwise ia can be freed in in6_ifinit accidentally.
1298 		 */
1299 		ifaref(&ia->ia_ifa);
1300 	}
1301 
1302 	/* Must execute in6_ifinit and ifa_insert atomically */
1303 	mutex_enter(&in6_ifaddr_lock);
1304 
1305 	/* reset the interface and routing table appropriately. */
1306 	error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew);
1307 	if (error != 0) {
1308 		if (hostIsNew)
1309 			free(ia, M_IFADDR);
1310 		mutex_exit(&in6_ifaddr_lock);
1311 		return error;
1312 	}
1313 
1314 	/*
1315 	 * We are done if we have simply modified an existing address.
1316 	 */
1317 	if (!hostIsNew) {
1318 		mutex_exit(&in6_ifaddr_lock);
1319 		return error;
1320 	}
1321 
1322 	/*
1323 	 * Insert ia to the global list and ifa to the interface's list.
1324 	 * A reference to it is already gained above.
1325 	 */
1326 	IN6_ADDRLIST_WRITER_INSERT_TAIL(ia);
1327 	ifa_insert(ifp, &ia->ia_ifa);
1328 
1329 	mutex_exit(&in6_ifaddr_lock);
1330 
1331 	/*
1332 	 * Beyond this point, we should call in6_purgeaddr upon an error,
1333 	 * not just go to unlink.
1334 	 */
1335 
1336 	/* join necessary multicast groups */
1337 	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
1338 		error = in6_join_mcastgroups(ifra, ia, ifp, flags);
1339 		if (error != 0)
1340 			goto cleanup;
1341 	}
1342 
1343 	if (nd6_need_cache(ifp)) {
1344 		/* XXX maybe unnecessary */
1345 		ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1346 		ia->ia_ifa.ifa_flags |= RTF_CONNECTED;
1347 	}
1348 
1349 	/*
1350 	 * Perform DAD, if needed.
1351 	 * XXX It may be of use, if we can administratively
1352 	 * disable DAD.
1353 	 */
1354 	if (hostIsNew && if_do_dad(ifp) &&
1355 	    ((ifra->ifra_flags & IN6_IFF_NODAD) == 0) &&
1356 	    (ia->ia6_flags & IN6_IFF_TENTATIVE))
1357 	{
1358 		int mindelay, maxdelay;
1359 
1360 		dad_delay = 0;
1361 		if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1362 			struct in6_addr llsol;
1363 			struct in6_multi *in6m_sol = NULL;
1364 			/*
1365 			 * We need to impose a delay before sending an NS
1366 			 * for DAD.  Check if we also needed a delay for the
1367 			 * corresponding MLD message.  If we did, the delay
1368 			 * should be larger than the MLD delay (this could be
1369 			 * relaxed a bit, but this simple logic is at least
1370 			 * safe).
1371 			 */
1372 			mindelay = 0;
1373 			error = in6_get_llsol_addr(&llsol, ifp,
1374 			    &ifra->ifra_addr.sin6_addr);
1375 			in6_multi_lock(RW_READER);
1376 			if (error == 0)
1377 				in6m_sol = in6_lookup_multi(&llsol, ifp);
1378 			if (in6m_sol != NULL &&
1379 			    in6m_sol->in6m_state == MLD_REPORTPENDING) {
1380 				mindelay = in6m_sol->in6m_timer;
1381 			}
1382 			in6_multi_unlock();
1383 			maxdelay = MAX_RTR_SOLICITATION_DELAY * hz;
1384 			if (maxdelay - mindelay == 0)
1385 				dad_delay = 0;
1386 			else {
1387 				dad_delay =
1388 				    (cprng_fast32() % (maxdelay - mindelay)) +
1389 				    mindelay;
1390 			}
1391 		}
1392 		/* +1 ensures callout is always used */
1393 		nd6_dad_start(&ia->ia_ifa, dad_delay + 1);
1394 	}
1395 
1396 	if (iap != NULL) {
1397 		*iap = ia;
1398 		if (hostIsNew)
1399 			ia6_acquire(ia, psref);
1400 	}
1401 
1402 	return 0;
1403 
1404   cleanup:
1405 	in6_purgeaddr(&ia->ia_ifa);
1406 	return error;
1407 }
1408 
1409 int
1410 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra, int flags)
1411 {
1412 	int rc, s;
1413 
1414 	s = splsoftnet();
1415 	rc = in6_update_ifa1(ifp, ifra, NULL, NULL, flags);
1416 	splx(s);
1417 	return rc;
1418 }
1419 
1420 void
1421 in6_purgeaddr(struct ifaddr *ifa)
1422 {
1423 	struct ifnet *ifp = ifa->ifa_ifp;
1424 	struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1425 	struct in6_multi_mship *imm;
1426 
1427 	/* KASSERT(!ifa_held(ifa)); XXX need ifa_not_held (psref_not_held) */
1428 	KASSERT(IFNET_LOCKED(ifp));
1429 
1430 	ifa->ifa_flags |= IFA_DESTROYING;
1431 
1432 	/* stop DAD processing */
1433 	nd6_dad_stop(ifa);
1434 
1435 	/* Delete any network route. */
1436 	in6_ifremprefix(ia);
1437 
1438 	/* Remove ownaddr's loopback rtentry, if it exists. */
1439 	in6_ifremlocal(&(ia->ia_ifa));
1440 
1441 	/*
1442 	 * leave from multicast groups we have joined for the interface
1443 	 */
1444     again:
1445 	mutex_enter(&in6_ifaddr_lock);
1446 	while ((imm = LIST_FIRST(&ia->ia6_memberships)) != NULL) {
1447 		struct in6_multi *in6m __diagused = imm->i6mm_maddr;
1448 		KASSERTMSG(in6m == NULL || in6m->in6m_ifp == ifp,
1449 		    "in6m_ifp=%s ifp=%s", in6m ? in6m->in6m_ifp->if_xname : NULL,
1450 		    ifp->if_xname);
1451 		LIST_REMOVE(imm, i6mm_chain);
1452 		mutex_exit(&in6_ifaddr_lock);
1453 
1454 		in6_leavegroup(imm);
1455 		goto again;
1456 	}
1457 	mutex_exit(&in6_ifaddr_lock);
1458 
1459 	in6_unlink_ifa(ia, ifp);
1460 }
1461 
1462 static void
1463 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1464 {
1465 	int	s = splsoftnet();
1466 
1467 	mutex_enter(&in6_ifaddr_lock);
1468 	IN6_ADDRLIST_WRITER_REMOVE(ia);
1469 	ifa_remove(ifp, &ia->ia_ifa);
1470 	/* Assume ifa_remove called pserialize_perform and psref_destroy */
1471 	mutex_exit(&in6_ifaddr_lock);
1472 	IN6_ADDRLIST_ENTRY_DESTROY(ia);
1473 
1474 	/*
1475 	 * release another refcnt for the link from in6_ifaddr.
1476 	 * Note that we should decrement the refcnt at least once for all *BSD.
1477 	 */
1478 	ifafree(&ia->ia_ifa);
1479 
1480 	splx(s);
1481 }
1482 
1483 void
1484 in6_purgeif(struct ifnet *ifp)
1485 {
1486 
1487 	IFNET_LOCK(ifp);
1488 	in6_ifdetach(ifp);
1489 	IFNET_UNLOCK(ifp);
1490 }
1491 
1492 void
1493 in6_purge_mcast_references(struct in6_multi *in6m)
1494 {
1495 	struct	in6_ifaddr *ia;
1496 
1497 	KASSERT(in6_multi_locked(RW_WRITER));
1498 
1499 	mutex_enter(&in6_ifaddr_lock);
1500 	IN6_ADDRLIST_WRITER_FOREACH(ia) {
1501 		struct in6_multi_mship *imm;
1502 		LIST_FOREACH(imm, &ia->ia6_memberships, i6mm_chain) {
1503 			if (imm->i6mm_maddr == in6m)
1504 				imm->i6mm_maddr = NULL;
1505 		}
1506 	}
1507 	mutex_exit(&in6_ifaddr_lock);
1508 }
1509 
1510 /*
1511  * SIOC[GAD]LIFADDR.
1512  *	SIOCGLIFADDR: get first address. (?)
1513  *	SIOCGLIFADDR with IFLR_PREFIX:
1514  *		get first address that matches the specified prefix.
1515  *	SIOCALIFADDR: add the specified address.
1516  *	SIOCALIFADDR with IFLR_PREFIX:
1517  *		add the specified prefix, filling hostid part from
1518  *		the first link-local address.  prefixlen must be <= 64.
1519  *	SIOCDLIFADDR: delete the specified address.
1520  *	SIOCDLIFADDR with IFLR_PREFIX:
1521  *		delete the first address that matches the specified prefix.
1522  * return values:
1523  *	EINVAL on invalid parameters
1524  *	EADDRNOTAVAIL on prefix match failed/specified address not found
1525  *	other values may be returned from in6_ioctl()
1526  *
1527  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1528  * this is to accommodate address naming scheme other than RFC2374,
1529  * in the future.
1530  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1531  * address encoding scheme. (see figure on page 8)
1532  */
1533 static int
1534 in6_lifaddr_ioctl(struct socket *so, u_long cmd, void *data,
1535 	struct ifnet *ifp)
1536 {
1537 	struct in6_ifaddr *ia = NULL; /* XXX gcc 4.8 maybe-uninitialized */
1538 	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1539 	struct ifaddr *ifa;
1540 	struct sockaddr *sa;
1541 
1542 	/* sanity checks */
1543 	if (!data || !ifp) {
1544 		panic("invalid argument to in6_lifaddr_ioctl");
1545 		/* NOTREACHED */
1546 	}
1547 
1548 	switch (cmd) {
1549 	case SIOCGLIFADDR:
1550 		/* address must be specified on GET with IFLR_PREFIX */
1551 		if ((iflr->flags & IFLR_PREFIX) == 0)
1552 			break;
1553 		/* FALLTHROUGH */
1554 	case SIOCALIFADDR:
1555 	case SIOCDLIFADDR:
1556 		/* address must be specified on ADD and DELETE */
1557 		sa = (struct sockaddr *)&iflr->addr;
1558 		if (sa->sa_family != AF_INET6)
1559 			return EINVAL;
1560 		if (sa->sa_len != sizeof(struct sockaddr_in6))
1561 			return EINVAL;
1562 		/* XXX need improvement */
1563 		sa = (struct sockaddr *)&iflr->dstaddr;
1564 		if (sa->sa_family && sa->sa_family != AF_INET6)
1565 			return EINVAL;
1566 		if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1567 			return EINVAL;
1568 		break;
1569 	default: /* shouldn't happen */
1570 #if 0
1571 		panic("invalid cmd to in6_lifaddr_ioctl");
1572 		/* NOTREACHED */
1573 #else
1574 		return EOPNOTSUPP;
1575 #endif
1576 	}
1577 	if (sizeof(struct in6_addr) * NBBY < iflr->prefixlen)
1578 		return EINVAL;
1579 
1580 	switch (cmd) {
1581 	case SIOCALIFADDR:
1582 	    {
1583 		struct in6_aliasreq ifra;
1584 		struct in6_addr *xhostid = NULL;
1585 		int prefixlen;
1586 		int bound = curlwp_bind();
1587 		struct psref psref;
1588 
1589 		if ((iflr->flags & IFLR_PREFIX) != 0) {
1590 			struct sockaddr_in6 *sin6;
1591 
1592 			/*
1593 			 * xhostid is to fill in the hostid part of the
1594 			 * address.  xhostid points to the first link-local
1595 			 * address attached to the interface.
1596 			 */
1597 			ia = in6ifa_ifpforlinklocal_psref(ifp, 0, &psref);
1598 			if (ia == NULL) {
1599 				curlwp_bindx(bound);
1600 				return EADDRNOTAVAIL;
1601 			}
1602 			xhostid = IFA_IN6(&ia->ia_ifa);
1603 
1604 		 	/* prefixlen must be <= 64. */
1605 			if (64 < iflr->prefixlen) {
1606 				ia6_release(ia, &psref);
1607 				curlwp_bindx(bound);
1608 				return EINVAL;
1609 			}
1610 			prefixlen = iflr->prefixlen;
1611 
1612 			/* hostid part must be zero. */
1613 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1614 			if (sin6->sin6_addr.s6_addr32[2] != 0
1615 			 || sin6->sin6_addr.s6_addr32[3] != 0) {
1616 				ia6_release(ia, &psref);
1617 				curlwp_bindx(bound);
1618 				return EINVAL;
1619 			}
1620 		} else
1621 			prefixlen = iflr->prefixlen;
1622 
1623 		/* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1624 		memset(&ifra, 0, sizeof(ifra));
1625 		memcpy(ifra.ifra_name, iflr->iflr_name, sizeof(ifra.ifra_name));
1626 
1627 		memcpy(&ifra.ifra_addr, &iflr->addr,
1628 		    ((struct sockaddr *)&iflr->addr)->sa_len);
1629 		if (xhostid) {
1630 			/* fill in hostid part */
1631 			ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1632 			    xhostid->s6_addr32[2];
1633 			ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1634 			    xhostid->s6_addr32[3];
1635 		}
1636 
1637 		if (((struct sockaddr *)&iflr->dstaddr)->sa_family) { /* XXX */
1638 			memcpy(&ifra.ifra_dstaddr, &iflr->dstaddr,
1639 			    ((struct sockaddr *)&iflr->dstaddr)->sa_len);
1640 			if (xhostid) {
1641 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1642 				    xhostid->s6_addr32[2];
1643 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1644 				    xhostid->s6_addr32[3];
1645 			}
1646 		}
1647 		if (xhostid) {
1648 			ia6_release(ia, &psref);
1649 			ia = NULL;
1650 		}
1651 		curlwp_bindx(bound);
1652 
1653 		ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1654 		in6_prefixlen2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1655 
1656 		ifra.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
1657 		ifra.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
1658 		ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1659 		return in6_control(so, SIOCAIFADDR_IN6, &ifra, ifp);
1660 	    }
1661 	case SIOCGLIFADDR:
1662 	case SIOCDLIFADDR:
1663 	    {
1664 		struct in6_addr mask, candidate, match;
1665 		struct sockaddr_in6 *sin6;
1666 		int cmp;
1667 		int error, s;
1668 
1669 		memset(&mask, 0, sizeof(mask));
1670 		if (iflr->flags & IFLR_PREFIX) {
1671 			/* lookup a prefix rather than address. */
1672 			in6_prefixlen2mask(&mask, iflr->prefixlen);
1673 
1674 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1675 			memcpy(&match, &sin6->sin6_addr, sizeof(match));
1676 			match.s6_addr32[0] &= mask.s6_addr32[0];
1677 			match.s6_addr32[1] &= mask.s6_addr32[1];
1678 			match.s6_addr32[2] &= mask.s6_addr32[2];
1679 			match.s6_addr32[3] &= mask.s6_addr32[3];
1680 
1681 			/* if you set extra bits, that's wrong */
1682 			if (memcmp(&match, &sin6->sin6_addr, sizeof(match)))
1683 				return EINVAL;
1684 
1685 			cmp = 1;
1686 		} else {
1687 			if (cmd == SIOCGLIFADDR) {
1688 				/* on getting an address, take the 1st match */
1689 				cmp = 0;	/* XXX */
1690 			} else {
1691 				/* on deleting an address, do exact match */
1692 				in6_prefixlen2mask(&mask, 128);
1693 				sin6 = (struct sockaddr_in6 *)&iflr->addr;
1694 				memcpy(&match, &sin6->sin6_addr, sizeof(match));
1695 
1696 				cmp = 1;
1697 			}
1698 		}
1699 
1700 		s = pserialize_read_enter();
1701 		IFADDR_READER_FOREACH(ifa, ifp) {
1702 			if (ifa->ifa_addr->sa_family != AF_INET6)
1703 				continue;
1704 			if (!cmp)
1705 				break;
1706 
1707 			/*
1708 			 * XXX: this is adhoc, but is necessary to allow
1709 			 * a user to specify fe80::/64 (not /10) for a
1710 			 * link-local address.
1711 			 */
1712 			memcpy(&candidate, IFA_IN6(ifa), sizeof(candidate));
1713 			in6_clearscope(&candidate);
1714 			candidate.s6_addr32[0] &= mask.s6_addr32[0];
1715 			candidate.s6_addr32[1] &= mask.s6_addr32[1];
1716 			candidate.s6_addr32[2] &= mask.s6_addr32[2];
1717 			candidate.s6_addr32[3] &= mask.s6_addr32[3];
1718 			if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1719 				break;
1720 		}
1721 		if (!ifa) {
1722 			error = EADDRNOTAVAIL;
1723 			goto error;
1724 		}
1725 		ia = ifa2ia6(ifa);
1726 
1727 		if (cmd == SIOCGLIFADDR) {
1728 			/* fill in the if_laddrreq structure */
1729 			memcpy(&iflr->addr, &ia->ia_addr, ia->ia_addr.sin6_len);
1730 			error = sa6_recoverscope(
1731 			    (struct sockaddr_in6 *)&iflr->addr);
1732 			if (error != 0)
1733 				goto error;
1734 
1735 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1736 				memcpy(&iflr->dstaddr, &ia->ia_dstaddr,
1737 				    ia->ia_dstaddr.sin6_len);
1738 				error = sa6_recoverscope(
1739 				    (struct sockaddr_in6 *)&iflr->dstaddr);
1740 				if (error != 0)
1741 					goto error;
1742 			} else
1743 				memset(&iflr->dstaddr, 0, sizeof(iflr->dstaddr));
1744 
1745 			iflr->prefixlen =
1746 			    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1747 
1748 			iflr->flags = ia->ia6_flags;	/* XXX */
1749 
1750 			error = 0;
1751 		} else {
1752 			struct in6_aliasreq ifra;
1753 
1754 			/* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1755 			memset(&ifra, 0, sizeof(ifra));
1756 			memcpy(ifra.ifra_name, iflr->iflr_name,
1757 			    sizeof(ifra.ifra_name));
1758 
1759 			memcpy(&ifra.ifra_addr, &ia->ia_addr,
1760 			    ia->ia_addr.sin6_len);
1761 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1762 				memcpy(&ifra.ifra_dstaddr, &ia->ia_dstaddr,
1763 				    ia->ia_dstaddr.sin6_len);
1764 			} else {
1765 				memset(&ifra.ifra_dstaddr, 0,
1766 				    sizeof(ifra.ifra_dstaddr));
1767 			}
1768 			memcpy(&ifra.ifra_dstaddr, &ia->ia_prefixmask,
1769 			    ia->ia_prefixmask.sin6_len);
1770 
1771 			ifra.ifra_flags = ia->ia6_flags;
1772 			pserialize_read_exit(s);
1773 
1774 			return in6_control(so, SIOCDIFADDR_IN6, &ifra, ifp);
1775 		}
1776 	error:
1777 		pserialize_read_exit(s);
1778 		return error;
1779 	    }
1780 	}
1781 
1782 	return EOPNOTSUPP;	/* just for safety */
1783 }
1784 
1785 /*
1786  * Initialize an interface's internet6 address
1787  * and routing table entry.
1788  */
1789 static int
1790 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia,
1791 	const struct sockaddr_in6 *sin6, int newhost)
1792 {
1793 	int	error = 0, ifacount = 0;
1794 	int s;
1795 	struct ifaddr *ifa;
1796 
1797 	KASSERT(mutex_owned(&in6_ifaddr_lock));
1798 
1799 	/*
1800 	 * Give the interface a chance to initialize
1801 	 * if this is its first address,
1802 	 * and to validate the address if necessary.
1803 	 */
1804 	s = pserialize_read_enter();
1805 	IFADDR_READER_FOREACH(ifa, ifp) {
1806 		if (ifa->ifa_addr->sa_family != AF_INET6)
1807 			continue;
1808 		ifacount++;
1809 	}
1810 	pserialize_read_exit(s);
1811 
1812 	ia->ia_addr = *sin6;
1813 
1814 	if (ifacount == 0 &&
1815 	    (error = if_addr_init(ifp, &ia->ia_ifa, true)) != 0) {
1816 		return error;
1817 	}
1818 
1819 	ia->ia_ifa.ifa_metric = ifp->if_metric;
1820 
1821 	/* we could do in(6)_socktrim here, but just omit it at this moment. */
1822 
1823 	/* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1824 	if (newhost) {
1825 		/* set the rtrequest function to create llinfo */
1826 		if (ifp->if_flags & IFF_POINTOPOINT)
1827 			ia->ia_ifa.ifa_rtrequest = p2p_rtrequest;
1828 		else if ((ifp->if_flags & IFF_LOOPBACK) == 0)
1829 			ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1830 		in6_ifaddlocal(&ia->ia_ifa);
1831 	} else {
1832 		/* Inform the routing socket of new flags/timings */
1833 		rt_addrmsg(RTM_NEWADDR, &ia->ia_ifa);
1834 	}
1835 
1836 	/* Add the network prefix route. */
1837 	if ((error = in6_ifaddprefix(ia)) != 0) {
1838 		if (newhost)
1839 			in6_ifremlocal(&ia->ia_ifa);
1840 		return error;
1841 	}
1842 
1843 	return error;
1844 }
1845 
1846 static struct ifaddr *
1847 bestifa(struct ifaddr *best_ifa, struct ifaddr *ifa)
1848 {
1849 	if (best_ifa == NULL || best_ifa->ifa_preference < ifa->ifa_preference)
1850 		return ifa;
1851 	return best_ifa;
1852 }
1853 
1854 /*
1855  * Find an IPv6 interface link-local address specific to an interface.
1856  */
1857 struct in6_ifaddr *
1858 in6ifa_ifpforlinklocal(const struct ifnet *ifp, const int ignoreflags)
1859 {
1860 	struct ifaddr *best_ifa = NULL, *ifa;
1861 
1862 	IFADDR_READER_FOREACH(ifa, ifp) {
1863 		if (ifa->ifa_addr->sa_family != AF_INET6)
1864 			continue;
1865 		if (!IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa)))
1866 			continue;
1867 		if ((((struct in6_ifaddr *)ifa)->ia6_flags & ignoreflags) != 0)
1868 			continue;
1869 		best_ifa = bestifa(best_ifa, ifa);
1870 	}
1871 
1872 	return (struct in6_ifaddr *)best_ifa;
1873 }
1874 
1875 struct in6_ifaddr *
1876 in6ifa_ifpforlinklocal_psref(const struct ifnet *ifp, const int ignoreflags,
1877     struct psref *psref)
1878 {
1879 	struct in6_ifaddr *ia;
1880 	int s = pserialize_read_enter();
1881 
1882 	ia = in6ifa_ifpforlinklocal(ifp, ignoreflags);
1883 	if (ia != NULL)
1884 		ia6_acquire(ia, psref);
1885 	pserialize_read_exit(s);
1886 
1887 	return ia;
1888 }
1889 
1890 /*
1891  * find the internet address corresponding to a given address.
1892  * ifaddr is returned referenced.
1893  */
1894 struct in6_ifaddr *
1895 in6ifa_ifwithaddr(const struct in6_addr *addr, uint32_t zoneid)
1896 {
1897 	struct in6_ifaddr *ia;
1898 	int s;
1899 
1900 	s = pserialize_read_enter();
1901 	IN6_ADDRLIST_READER_FOREACH(ia) {
1902 		if (IN6_ARE_ADDR_EQUAL(IA6_IN6(ia), addr)) {
1903 			if (zoneid != 0 &&
1904 			    zoneid != ia->ia_addr.sin6_scope_id)
1905 				continue;
1906 			ifaref(&ia->ia_ifa);
1907 			break;
1908 		}
1909 	}
1910 	pserialize_read_exit(s);
1911 
1912 	return ia;
1913 }
1914 
1915 /*
1916  * find the internet address corresponding to a given interface and address.
1917  */
1918 struct in6_ifaddr *
1919 in6ifa_ifpwithaddr(const struct ifnet *ifp, const struct in6_addr *addr)
1920 {
1921 	struct ifaddr *best_ifa = NULL, *ifa;
1922 
1923 	IFADDR_READER_FOREACH(ifa, ifp) {
1924 		if (ifa->ifa_addr->sa_family != AF_INET6)
1925 			continue;
1926 		if (!IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
1927 			continue;
1928 		best_ifa = bestifa(best_ifa, ifa);
1929 	}
1930 
1931 	return (struct in6_ifaddr *)best_ifa;
1932 }
1933 
1934 struct in6_ifaddr *
1935 in6ifa_ifpwithaddr_psref(const struct ifnet *ifp, const struct in6_addr *addr,
1936     struct psref *psref)
1937 {
1938 	struct in6_ifaddr *ia;
1939 	int s = pserialize_read_enter();
1940 
1941 	ia = in6ifa_ifpwithaddr(ifp, addr);
1942 	if (ia != NULL)
1943 		ia6_acquire(ia, psref);
1944 	pserialize_read_exit(s);
1945 
1946 	return ia;
1947 }
1948 
1949 static struct in6_ifaddr *
1950 bestia(struct in6_ifaddr *best_ia, struct in6_ifaddr *ia)
1951 {
1952 	if (best_ia == NULL ||
1953 	    best_ia->ia_ifa.ifa_preference < ia->ia_ifa.ifa_preference)
1954 		return ia;
1955 	return best_ia;
1956 }
1957 
1958 /*
1959  * Determine if an address is on a local network.
1960  */
1961 int
1962 in6_localaddr(const struct in6_addr *in6)
1963 {
1964 	struct in6_ifaddr *ia;
1965 	int s;
1966 
1967 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
1968 		return 1;
1969 
1970 	s = pserialize_read_enter();
1971 	IN6_ADDRLIST_READER_FOREACH(ia) {
1972 		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
1973 					      &ia->ia_prefixmask.sin6_addr)) {
1974 			pserialize_read_exit(s);
1975 			return 1;
1976 		}
1977 	}
1978 	pserialize_read_exit(s);
1979 
1980 	return 0;
1981 }
1982 
1983 int
1984 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
1985 {
1986 	struct in6_ifaddr *ia;
1987 	int s;
1988 
1989 	s = pserialize_read_enter();
1990 	IN6_ADDRLIST_READER_FOREACH(ia) {
1991 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
1992 		    &sa6->sin6_addr) &&
1993 #ifdef SCOPEDROUTING
1994 		    ia->ia_addr.sin6_scope_id == sa6->sin6_scope_id &&
1995 #endif
1996 		    (ia->ia6_flags & IN6_IFF_DEPRECATED) != 0) {
1997 			pserialize_read_exit(s);
1998 			return 1; /* true */
1999 		}
2000 
2001 		/* XXX: do we still have to go thru the rest of the list? */
2002 	}
2003 	pserialize_read_exit(s);
2004 
2005 	return 0;		/* false */
2006 }
2007 
2008 /*
2009  * return length of part which dst and src are equal
2010  * hard coding...
2011  */
2012 int
2013 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
2014 {
2015 	int match = 0;
2016 	u_char *s = (u_char *)src, *d = (u_char *)dst;
2017 	u_char *lim = s + 16, r;
2018 
2019 	while (s < lim)
2020 		if ((r = (*d++ ^ *s++)) != 0) {
2021 			while (r < 128) {
2022 				match++;
2023 				r <<= 1;
2024 			}
2025 			break;
2026 		} else
2027 			match += NBBY;
2028 	return match;
2029 }
2030 
2031 void
2032 in6_prefixlen2mask(struct in6_addr *maskp, int len)
2033 {
2034 	static const u_char maskarray[NBBY] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
2035 	int bytelen, bitlen, i;
2036 
2037 	/* sanity check */
2038 	if (len < 0 || len > 128) {
2039 		log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
2040 		    len);
2041 		return;
2042 	}
2043 
2044 	memset(maskp, 0, sizeof(*maskp));
2045 	bytelen = len / NBBY;
2046 	bitlen = len % NBBY;
2047 	for (i = 0; i < bytelen; i++)
2048 		maskp->s6_addr[i] = 0xff;
2049 	if (bitlen)
2050 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
2051 }
2052 
2053 /*
2054  * return the best address out of the same scope. if no address was
2055  * found, return the first valid address from designated IF.
2056  */
2057 struct in6_ifaddr *
2058 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
2059 {
2060 	int dst_scope =	in6_addrscope(dst), blen = -1, tlen;
2061 	struct ifaddr *ifa;
2062 	struct in6_ifaddr *best_ia = NULL, *ia;
2063 	struct in6_ifaddr *dep[2];	/* last-resort: deprecated */
2064 
2065 	dep[0] = dep[1] = NULL;
2066 
2067 	/*
2068 	 * We first look for addresses in the same scope.
2069 	 * If there is one, return it.
2070 	 * If two or more, return one which matches the dst longest.
2071 	 * If none, return one of global addresses assigned other ifs.
2072 	 */
2073 	IFADDR_READER_FOREACH(ifa, ifp) {
2074 		if (ifa->ifa_addr->sa_family != AF_INET6)
2075 			continue;
2076 		ia = (struct in6_ifaddr *)ifa;
2077 		if (ia->ia6_flags & IN6_IFF_ANYCAST)
2078 			continue; /* XXX: is there any case to allow anycast? */
2079 		if (ia->ia6_flags & IN6_IFF_NOTREADY)
2080 			continue; /* don't use this interface */
2081 		if (ia->ia6_flags & IN6_IFF_DETACHED)
2082 			continue;
2083 		if (ia->ia6_flags & IN6_IFF_DEPRECATED) {
2084 			if (ip6_use_deprecated)
2085 				dep[0] = ia;
2086 			continue;
2087 		}
2088 
2089 		if (dst_scope != in6_addrscope(IFA_IN6(ifa)))
2090 			continue;
2091 		/*
2092 		 * call in6_matchlen() as few as possible
2093 		 */
2094 		if (best_ia == NULL) {
2095 			best_ia = ia;
2096 			continue;
2097 		}
2098 		if (blen == -1)
2099 			blen = in6_matchlen(&best_ia->ia_addr.sin6_addr, dst);
2100 		tlen = in6_matchlen(IFA_IN6(ifa), dst);
2101 		if (tlen > blen) {
2102 			blen = tlen;
2103 			best_ia = ia;
2104 		} else if (tlen == blen)
2105 			best_ia = bestia(best_ia, ia);
2106 	}
2107 	if (best_ia != NULL)
2108 		return best_ia;
2109 
2110 	IFADDR_READER_FOREACH(ifa, ifp) {
2111 		if (ifa->ifa_addr->sa_family != AF_INET6)
2112 			continue;
2113 		ia = (struct in6_ifaddr *)ifa;
2114 		if (ia->ia6_flags & IN6_IFF_ANYCAST)
2115 			continue; /* XXX: is there any case to allow anycast? */
2116 		if (ia->ia6_flags & IN6_IFF_NOTREADY)
2117 			continue; /* don't use this interface */
2118 		if (ia->ia6_flags & IN6_IFF_DETACHED)
2119 			continue;
2120 		if (ia->ia6_flags & IN6_IFF_DEPRECATED) {
2121 			if (ip6_use_deprecated)
2122 				dep[1] = (struct in6_ifaddr *)ifa;
2123 			continue;
2124 		}
2125 
2126 		best_ia = bestia(best_ia, ia);
2127 	}
2128 	if (best_ia != NULL)
2129 		return best_ia;
2130 
2131 	/* use the last-resort values, that are, deprecated addresses */
2132 	if (dep[0])
2133 		return dep[0];
2134 	if (dep[1])
2135 		return dep[1];
2136 
2137 	return NULL;
2138 }
2139 
2140 /*
2141  * perform DAD when interface becomes IFF_UP.
2142  */
2143 void
2144 in6_if_link_up(struct ifnet *ifp)
2145 {
2146 	struct ifaddr *ifa;
2147 	struct in6_ifaddr *ia;
2148 	int s, bound;
2149 	char ip6buf[INET6_ADDRSTRLEN];
2150 
2151 	/* Ensure it's sane to run DAD */
2152 	if (ifp->if_link_state == LINK_STATE_DOWN)
2153 		return;
2154 	if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
2155 		return;
2156 
2157 	bound = curlwp_bind();
2158 	s = pserialize_read_enter();
2159 	IFADDR_READER_FOREACH(ifa, ifp) {
2160 		struct psref psref;
2161 
2162 		if (ifa->ifa_addr->sa_family != AF_INET6)
2163 			continue;
2164 
2165 		ifa_acquire(ifa, &psref);
2166 		pserialize_read_exit(s);
2167 		ia = (struct in6_ifaddr *)ifa;
2168 
2169 		/* If detached then mark as tentative */
2170 		if (ia->ia6_flags & IN6_IFF_DETACHED) {
2171 			ia->ia6_flags &= ~IN6_IFF_DETACHED;
2172 			if (ip6_dad_enabled() && if_do_dad(ifp)) {
2173 				ia->ia6_flags |= IN6_IFF_TENTATIVE;
2174 				nd6log(LOG_ERR, "%s marked tentative\n",
2175 				    IN6_PRINT(ip6buf,
2176 				    &ia->ia_addr.sin6_addr));
2177 			} else if ((ia->ia6_flags & IN6_IFF_TENTATIVE) == 0)
2178 				rt_addrmsg(RTM_NEWADDR, ifa);
2179 		}
2180 
2181 		if (ia->ia6_flags & IN6_IFF_TENTATIVE) {
2182 			int rand_delay;
2183 
2184 			/* Clear the duplicated flag as we're starting DAD. */
2185 			ia->ia6_flags &= ~IN6_IFF_DUPLICATED;
2186 
2187 			/*
2188 			 * The TENTATIVE flag was likely set by hand
2189 			 * beforehand, implicitly indicating the need for DAD.
2190 			 * We may be able to skip the random delay in this
2191 			 * case, but we impose delays just in case.
2192 			 */
2193 			rand_delay = cprng_fast32() %
2194 			    (MAX_RTR_SOLICITATION_DELAY * hz);
2195 			/* +1 ensures callout is always used */
2196 			nd6_dad_start(ifa, rand_delay + 1);
2197 		}
2198 
2199 		s = pserialize_read_enter();
2200 		ifa_release(ifa, &psref);
2201 	}
2202 	pserialize_read_exit(s);
2203 	curlwp_bindx(bound);
2204 }
2205 
2206 void
2207 in6_if_up(struct ifnet *ifp)
2208 {
2209 
2210 	/*
2211 	 * special cases, like 6to4, are handled in in6_ifattach
2212 	 */
2213 	in6_ifattach(ifp, NULL);
2214 
2215 	/* interface may not support link state, so bring it up also */
2216 	in6_if_link_up(ifp);
2217 }
2218 
2219 /*
2220  * Mark all addresses as detached.
2221  */
2222 void
2223 in6_if_link_down(struct ifnet *ifp)
2224 {
2225 	struct ifaddr *ifa;
2226 	struct in6_ifaddr *ia;
2227 	int s, bound;
2228 	char ip6buf[INET6_ADDRSTRLEN];
2229 
2230 	bound = curlwp_bind();
2231 	s = pserialize_read_enter();
2232 	IFADDR_READER_FOREACH(ifa, ifp) {
2233 		struct psref psref;
2234 
2235 		if (ifa->ifa_addr->sa_family != AF_INET6)
2236 			continue;
2237 
2238 		ifa_acquire(ifa, &psref);
2239 		pserialize_read_exit(s);
2240 		ia = (struct in6_ifaddr *)ifa;
2241 
2242 		/* Stop DAD processing */
2243 		nd6_dad_stop(ifa);
2244 
2245 		/*
2246 		 * Mark the address as detached.
2247 		 * This satisfies RFC4862 Section 5.3, but we should apply
2248 		 * this logic to all addresses to be a good citizen and
2249 		 * avoid potential duplicated addresses.
2250 		 * When the interface comes up again, detached addresses
2251 		 * are marked tentative and DAD commences.
2252 		 */
2253 		if (!(ia->ia6_flags & IN6_IFF_DETACHED)) {
2254 			nd6log(LOG_DEBUG, "%s marked detached\n",
2255 			    IN6_PRINT(ip6buf, &ia->ia_addr.sin6_addr));
2256 			ia->ia6_flags |= IN6_IFF_DETACHED;
2257 			ia->ia6_flags &=
2258 			    ~(IN6_IFF_TENTATIVE | IN6_IFF_DUPLICATED);
2259 			rt_addrmsg(RTM_NEWADDR, ifa);
2260 		}
2261 
2262 		s = pserialize_read_enter();
2263 		ifa_release(ifa, &psref);
2264 	}
2265 	pserialize_read_exit(s);
2266 	curlwp_bindx(bound);
2267 }
2268 
2269 void
2270 in6_if_down(struct ifnet *ifp)
2271 {
2272 
2273 	in6_if_link_down(ifp);
2274 	lltable_purge_entries(LLTABLE6(ifp));
2275 }
2276 
2277 void
2278 in6_if_link_state_change(struct ifnet *ifp, int link_state)
2279 {
2280 
2281 	/*
2282 	 * Treat LINK_STATE_UNKNOWN as UP.
2283 	 * LINK_STATE_UNKNOWN transitions to LINK_STATE_DOWN when
2284 	 * if_link_state_change() transitions to LINK_STATE_UP.
2285 	 */
2286 	if (link_state == LINK_STATE_DOWN)
2287 		in6_if_link_down(ifp);
2288 	else
2289 		in6_if_link_up(ifp);
2290 }
2291 
2292 int
2293 in6_tunnel_validate(const struct ip6_hdr *ip6, const struct in6_addr *src,
2294     const struct in6_addr *dst)
2295 {
2296 
2297 	/* check for address match */
2298 	if (!IN6_ARE_ADDR_EQUAL(src, &ip6->ip6_dst) ||
2299 	    !IN6_ARE_ADDR_EQUAL(dst, &ip6->ip6_src))
2300 		return 0;
2301 
2302 	/* martian filters on outer source - done in ip6_input */
2303 
2304 	/* NOTE: the packet may be dropped by uRPF. */
2305 
2306 	/* return valid bytes length */
2307 	return sizeof(*src) + sizeof(*dst);
2308 }
2309 
2310 #define	IN6_LLTBL_DEFAULT_HSIZE	32
2311 #define	IN6_LLTBL_HASH(k, h) \
2312 	(((((((k >> 8) ^ k) >> 8) ^ k) >> 8) ^ k) & ((h) - 1))
2313 
2314 /*
2315  * Do actual deallocation of @lle.
2316  * Called by LLE_FREE_LOCKED when number of references
2317  * drops to zero.
2318  */
2319 static void
2320 in6_lltable_destroy_lle(struct llentry *lle)
2321 {
2322 
2323 	KASSERTMSG(lle->la_numheld == 0, "la_numheld=%d", lle->la_numheld);
2324 
2325 	LLE_WUNLOCK(lle);
2326 	LLE_LOCK_DESTROY(lle);
2327 	llentry_pool_put(lle);
2328 }
2329 
2330 static struct llentry *
2331 in6_lltable_new(const struct in6_addr *addr6, u_int flags)
2332 {
2333 	struct llentry *lle;
2334 
2335 	lle = llentry_pool_get(PR_NOWAIT);
2336 	if (lle == NULL)		/* NB: caller generates msg */
2337 		return NULL;
2338 
2339 	lle->r_l3addr.addr6 = *addr6;
2340 	lle->lle_refcnt = 1;
2341 	lle->lle_free = in6_lltable_destroy_lle;
2342 	LLE_LOCK_INIT(lle);
2343 	callout_init(&lle->lle_timer, CALLOUT_MPSAFE);
2344 
2345 	return lle;
2346 }
2347 
2348 static int
2349 in6_lltable_match_prefix(const struct sockaddr *prefix,
2350     const struct sockaddr *mask, u_int flags, struct llentry *lle)
2351 {
2352 	const struct sockaddr_in6 *pfx = (const struct sockaddr_in6 *)prefix;
2353 	const struct sockaddr_in6 *msk = (const struct sockaddr_in6 *)mask;
2354 
2355 	if (IN6_ARE_MASKED_ADDR_EQUAL(&lle->r_l3addr.addr6,
2356 	    &pfx->sin6_addr, &msk->sin6_addr) &&
2357 	    ((flags & LLE_STATIC) || !(lle->la_flags & LLE_STATIC)))
2358 		return 1;
2359 
2360 	return 0;
2361 }
2362 
2363 static void
2364 in6_lltable_free_entry(struct lltable *llt, struct llentry *lle)
2365 {
2366 
2367 	LLE_WLOCK_ASSERT(lle);
2368 	(void) llentry_free(lle);
2369 }
2370 
2371 static int
2372 in6_lltable_rtcheck(struct ifnet *ifp, u_int flags,
2373     const struct sockaddr *l3addr, const struct rtentry *rt)
2374 {
2375 	char ip6buf[INET6_ADDRSTRLEN];
2376 
2377 	if (rt == NULL || (rt->rt_flags & RTF_GATEWAY) || rt->rt_ifp != ifp) {
2378 		int s;
2379 		struct ifaddr *ifa;
2380 		/*
2381 		 * Create an ND6 cache for an IPv6 neighbor
2382 		 * that is not covered by our own prefix.
2383 		 */
2384 		/* XXX ifaof_ifpforaddr should take a const param */
2385 		s = pserialize_read_enter();
2386 		ifa = ifaof_ifpforaddr(l3addr, ifp);
2387 		if (ifa != NULL) {
2388 			pserialize_read_exit(s);
2389 			return 0;
2390 		}
2391 		pserialize_read_exit(s);
2392 		log(LOG_INFO, "IPv6 address: \"%s\" is not on the network\n",
2393 		    IN6_PRINT(ip6buf,
2394 		    &((const struct sockaddr_in6 *)l3addr)->sin6_addr));
2395 		return EINVAL;
2396 	}
2397 	return 0;
2398 }
2399 
2400 static inline uint32_t
2401 in6_lltable_hash_dst(const struct in6_addr *dst, uint32_t hsize)
2402 {
2403 
2404 	return IN6_LLTBL_HASH(dst->s6_addr32[3], hsize);
2405 }
2406 
2407 static uint32_t
2408 in6_lltable_hash(const struct llentry *lle, uint32_t hsize)
2409 {
2410 
2411 	return in6_lltable_hash_dst(&lle->r_l3addr.addr6, hsize);
2412 }
2413 
2414 static void
2415 in6_lltable_fill_sa_entry(const struct llentry *lle, struct sockaddr *sa)
2416 {
2417 	struct sockaddr_in6 *sin6;
2418 
2419 	sin6 = (struct sockaddr_in6 *)sa;
2420 	bzero(sin6, sizeof(*sin6));
2421 	sin6->sin6_family = AF_INET6;
2422 	sin6->sin6_len = sizeof(*sin6);
2423 	sin6->sin6_addr = lle->r_l3addr.addr6;
2424 }
2425 
2426 static inline struct llentry *
2427 in6_lltable_find_dst(struct lltable *llt, const struct in6_addr *dst)
2428 {
2429 	struct llentry *lle;
2430 	struct llentries *lleh;
2431 	u_int hashidx;
2432 
2433 	hashidx = in6_lltable_hash_dst(dst, llt->llt_hsize);
2434 	lleh = &llt->lle_head[hashidx];
2435 	LIST_FOREACH(lle, lleh, lle_next) {
2436 		if (lle->la_flags & LLE_DELETED)
2437 			continue;
2438 		if (IN6_ARE_ADDR_EQUAL(&lle->r_l3addr.addr6, dst))
2439 			break;
2440 	}
2441 
2442 	return lle;
2443 }
2444 
2445 static int
2446 in6_lltable_delete(struct lltable *llt, u_int flags,
2447 	const struct sockaddr *l3addr)
2448 {
2449 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)l3addr;
2450 	struct llentry *lle;
2451 
2452 	IF_AFDATA_WLOCK_ASSERT(llt->llt_ifp);
2453 	KASSERTMSG(l3addr->sa_family == AF_INET6,
2454 	    "sin_family %d", l3addr->sa_family);
2455 
2456 	lle = in6_lltable_find_dst(llt, &sin6->sin6_addr);
2457 
2458 	if (lle == NULL) {
2459 #ifdef LLTABLE_DEBUG
2460 		char buf[64];
2461 		sockaddr_format(l3addr, buf, sizeof(buf));
2462 		log(LOG_INFO, "%s: cache for %s is not found\n",
2463 		    __func__, buf);
2464 #endif
2465 		return ENOENT;
2466 	}
2467 
2468 	LLE_WLOCK(lle);
2469 #ifdef LLTABLE_DEBUG
2470 	{
2471 		char buf[64];
2472 		sockaddr_format(l3addr, buf, sizeof(buf));
2473 		log(LOG_INFO, "%s: cache for %s (%p) is deleted\n",
2474 		    __func__, buf, lle);
2475 	}
2476 #endif
2477 	llentry_free(lle);
2478 
2479 	return 0;
2480 }
2481 
2482 static struct llentry *
2483 in6_lltable_create(struct lltable *llt, u_int flags,
2484     const struct sockaddr *l3addr, const struct rtentry *rt)
2485 {
2486 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)l3addr;
2487 	struct ifnet *ifp = llt->llt_ifp;
2488 	struct llentry *lle;
2489 
2490 	IF_AFDATA_WLOCK_ASSERT(ifp);
2491 	KASSERTMSG(l3addr->sa_family == AF_INET6,
2492 	    "sin_family %d", l3addr->sa_family);
2493 
2494 	lle = in6_lltable_find_dst(llt, &sin6->sin6_addr);
2495 
2496 	if (lle != NULL) {
2497 		LLE_WLOCK(lle);
2498 		return lle;
2499 	}
2500 
2501 	/*
2502 	 * A route that covers the given address must have
2503 	 * been installed 1st because we are doing a resolution,
2504 	 * verify this.
2505 	 */
2506 	if (!(flags & LLE_IFADDR) &&
2507 	    in6_lltable_rtcheck(ifp, flags, l3addr, rt) != 0)
2508 		return NULL;
2509 
2510 	lle = in6_lltable_new(&sin6->sin6_addr, flags);
2511 	if (lle == NULL) {
2512 		log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
2513 		return NULL;
2514 	}
2515 	lle->la_flags = flags;
2516 	if ((flags & LLE_IFADDR) == LLE_IFADDR) {
2517 		memcpy(&lle->ll_addr, CLLADDR(ifp->if_sadl), ifp->if_addrlen);
2518 		lle->la_flags |= LLE_VALID;
2519 	}
2520 
2521 	lltable_link_entry(llt, lle);
2522 	LLE_WLOCK(lle);
2523 
2524 	return lle;
2525 }
2526 
2527 static struct llentry *
2528 in6_lltable_lookup(struct lltable *llt, u_int flags,
2529 	const struct sockaddr *l3addr)
2530 {
2531 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)l3addr;
2532 	struct llentry *lle;
2533 
2534 	IF_AFDATA_LOCK_ASSERT(llt->llt_ifp);
2535 	KASSERTMSG(l3addr->sa_family == AF_INET6,
2536 	    "sin_family %d", l3addr->sa_family);
2537 
2538 	lle = in6_lltable_find_dst(llt, &sin6->sin6_addr);
2539 
2540 	if (lle == NULL)
2541 		return NULL;
2542 
2543 	if (flags & LLE_EXCLUSIVE)
2544 		LLE_WLOCK(lle);
2545 	else
2546 		LLE_RLOCK(lle);
2547 	return lle;
2548 }
2549 
2550 static int
2551 in6_lltable_dump_entry(struct lltable *llt, struct llentry *lle,
2552     struct rt_walkarg *w)
2553 {
2554 	struct sockaddr_in6 sin6;
2555 
2556 	LLTABLE_LOCK_ASSERT();
2557 
2558 	/* skip deleted entries */
2559 	if (lle->la_flags & LLE_DELETED)
2560 		return 0;
2561 
2562 	sockaddr_in6_init(&sin6, &lle->r_l3addr.addr6, 0, 0, 0);
2563 
2564 	return lltable_dump_entry(llt, lle, w, sin6tosa(&sin6));
2565 }
2566 
2567 static struct lltable *
2568 in6_lltattach(struct ifnet *ifp)
2569 {
2570 	struct lltable *llt;
2571 
2572 	llt = lltable_allocate_htbl(IN6_LLTBL_DEFAULT_HSIZE);
2573 	llt->llt_af = AF_INET6;
2574 	llt->llt_ifp = ifp;
2575 
2576 	llt->llt_lookup = in6_lltable_lookup;
2577 	llt->llt_create = in6_lltable_create;
2578 	llt->llt_delete = in6_lltable_delete;
2579 	llt->llt_dump_entry = in6_lltable_dump_entry;
2580 	llt->llt_hash = in6_lltable_hash;
2581 	llt->llt_fill_sa_entry = in6_lltable_fill_sa_entry;
2582 	llt->llt_free_entry = in6_lltable_free_entry;
2583 	llt->llt_match_prefix = in6_lltable_match_prefix;
2584 	lltable_link(llt);
2585 
2586 	return llt;
2587 }
2588 
2589 void *
2590 in6_domifattach(struct ifnet *ifp)
2591 {
2592 	struct in6_ifextra *ext;
2593 
2594 	ext = malloc(sizeof(*ext), M_IFADDR, M_WAITOK|M_ZERO);
2595 
2596 	ext->in6_ifstat = malloc(sizeof(struct in6_ifstat),
2597 	    M_IFADDR, M_WAITOK|M_ZERO);
2598 
2599 	ext->icmp6_ifstat = malloc(sizeof(struct icmp6_ifstat),
2600 	    M_IFADDR, M_WAITOK|M_ZERO);
2601 
2602 	ext->nd_ifinfo = nd6_ifattach(ifp);
2603 	ext->scope6_id = scope6_ifattach(ifp);
2604 	ext->lltable = in6_lltattach(ifp);
2605 
2606 	return ext;
2607 }
2608 
2609 void
2610 in6_domifdetach(struct ifnet *ifp, void *aux)
2611 {
2612 	struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2613 
2614 	lltable_free(ext->lltable);
2615 	ext->lltable = NULL;
2616 	SOFTNET_LOCK_UNLESS_NET_MPSAFE();
2617 	nd6_ifdetach(ifp, ext);
2618 	SOFTNET_UNLOCK_UNLESS_NET_MPSAFE();
2619 	free(ext->in6_ifstat, M_IFADDR);
2620 	free(ext->icmp6_ifstat, M_IFADDR);
2621 	scope6_ifdetach(ext->scope6_id);
2622 	free(ext, M_IFADDR);
2623 }
2624 
2625 /*
2626  * Convert IPv4 address stored in struct in_addr to IPv4-Mapped IPv6 address
2627  * stored in struct in6_addr as defined in RFC 4921 section 2.5.5.2.
2628  */
2629 void
2630 in6_in_2_v4mapin6(const struct in_addr *in, struct in6_addr *in6)
2631 {
2632 	in6->s6_addr32[0] = 0;
2633 	in6->s6_addr32[1] = 0;
2634 	in6->s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2635 	in6->s6_addr32[3] = in->s_addr;
2636 }
2637 
2638 /*
2639  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2640  * v4 mapped addr or v4 compat addr
2641  */
2642 void
2643 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2644 {
2645 	memset(sin, 0, 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(const struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2655 {
2656 	memset(sin6, 0, sizeof(*sin6));
2657 	sin6->sin6_len = sizeof(struct sockaddr_in6);
2658 	sin6->sin6_family = AF_INET6;
2659 	sin6->sin6_port = sin->sin_port;
2660 	in6_in_2_v4mapin6(&sin->sin_addr, &sin6->sin6_addr);
2661 }
2662 
2663 /* Convert sockaddr_in6 into sockaddr_in. */
2664 void
2665 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2666 {
2667 	struct sockaddr_in *sin_p;
2668 	struct sockaddr_in6 sin6;
2669 
2670 	/*
2671 	 * Save original sockaddr_in6 addr and convert it
2672 	 * to sockaddr_in.
2673 	 */
2674 	sin6 = *(struct sockaddr_in6 *)nam;
2675 	sin_p = (struct sockaddr_in *)nam;
2676 	in6_sin6_2_sin(sin_p, &sin6);
2677 }
2678 
2679 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2680 void
2681 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2682 {
2683 	struct sockaddr_in *sin_p;
2684 	struct sockaddr_in6 *sin6_p;
2685 
2686 	sin6_p = malloc(sizeof(*sin6_p), M_SONAME, M_WAITOK);
2687 	sin_p = (struct sockaddr_in *)*nam;
2688 	in6_sin_2_v4mapsin6(sin_p, sin6_p);
2689 	free(*nam, M_SONAME);
2690 	*nam = sin6tosa(sin6_p);
2691 }
2692