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