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