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