xref: /dflybsd-src/sys/netinet6/in6.c (revision 450f08dbfd98cded95c51be4079ef10f5adb3241)
1 /*	$FreeBSD: src/sys/netinet6/in6.c,v 1.7.2.9 2002/04/28 05:40:26 suz Exp $	*/
2 /*	$KAME: in6.c,v 1.259 2002/01/21 11:37:50 keiichi 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 "opt_inet.h"
65 #include "opt_inet6.h"
66 
67 #include <sys/param.h>
68 #include <sys/errno.h>
69 #include <sys/malloc.h>
70 #include <sys/socket.h>
71 #include <sys/socketvar.h>
72 #include <sys/sockio.h>
73 #include <sys/systm.h>
74 #include <sys/proc.h>
75 #include <sys/priv.h>
76 #include <sys/time.h>
77 #include <sys/kernel.h>
78 #include <sys/syslog.h>
79 
80 #include <sys/thread2.h>
81 #include <sys/msgport2.h>
82 
83 #include <net/if.h>
84 #include <net/if_types.h>
85 #include <net/route.h>
86 #include <net/if_dl.h>
87 
88 #include <netinet/in.h>
89 #include <netinet/in_var.h>
90 #include <netinet/if_ether.h>
91 #include <netinet/in_systm.h>
92 #include <netinet/ip.h>
93 #include <netinet/in_pcb.h>
94 
95 #include <netinet/ip6.h>
96 #include <netinet6/ip6_var.h>
97 #include <netinet6/nd6.h>
98 #include <netinet6/mld6_var.h>
99 #include <netinet6/ip6_mroute.h>
100 #include <netinet6/in6_ifattach.h>
101 #include <netinet6/scope6_var.h>
102 #include <netinet6/in6_pcb.h>
103 #include <netinet6/in6_var.h>
104 
105 #include <net/net_osdep.h>
106 
107 /*
108  * Definitions of some costant IP6 addresses.
109  */
110 const struct in6_addr kin6addr_any = IN6ADDR_ANY_INIT;
111 const struct in6_addr kin6addr_loopback = IN6ADDR_LOOPBACK_INIT;
112 const struct in6_addr kin6addr_nodelocal_allnodes =
113 	IN6ADDR_NODELOCAL_ALLNODES_INIT;
114 const struct in6_addr kin6addr_linklocal_allnodes =
115 	IN6ADDR_LINKLOCAL_ALLNODES_INIT;
116 const struct in6_addr kin6addr_linklocal_allrouters =
117 	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
118 
119 const struct in6_addr in6mask0 = IN6MASK0;
120 const struct in6_addr in6mask32 = IN6MASK32;
121 const struct in6_addr in6mask64 = IN6MASK64;
122 const struct in6_addr in6mask96 = IN6MASK96;
123 const struct in6_addr in6mask128 = IN6MASK128;
124 
125 const struct sockaddr_in6 sa6_any = {sizeof(sa6_any), AF_INET6,
126 				     0, 0, IN6ADDR_ANY_INIT, 0};
127 
128 static int in6_lifaddr_ioctl (struct socket *, u_long, caddr_t,
129 	struct ifnet *, struct thread *);
130 static int in6_ifinit (struct ifnet *, struct in6_ifaddr *,
131 			   struct sockaddr_in6 *, int);
132 static void in6_unlink_ifa (struct in6_ifaddr *, struct ifnet *);
133 static void in6_ifloop_request_callback(int, int, struct rt_addrinfo *, struct rtentry *, void *);
134 
135 struct in6_multihead in6_multihead;	/* XXX BSS initialization */
136 
137 int	(*faithprefix_p)(struct in6_addr *);
138 
139 /*
140  * Subroutine for in6_ifaddloop() and in6_ifremloop().
141  * This routine does actual work.
142  */
143 static void
144 in6_ifloop_request(int cmd, struct ifaddr *ifa)
145 {
146 	struct sockaddr_in6 all1_sa;
147         struct rt_addrinfo rtinfo;
148 	int error;
149 
150 	bzero(&all1_sa, sizeof(all1_sa));
151 	all1_sa.sin6_family = AF_INET6;
152 	all1_sa.sin6_len = sizeof(struct sockaddr_in6);
153 	all1_sa.sin6_addr = in6mask128;
154 
155 	/*
156 	 * We specify the address itself as the gateway, and set the
157 	 * RTF_LLINFO flag, so that the corresponding host route would have
158 	 * the flag, and thus applications that assume traditional behavior
159 	 * would be happy.  Note that we assume the caller of the function
160 	 * (probably implicitly) set nd6_rtrequest() to ifa->ifa_rtrequest,
161 	 * which changes the outgoing interface to the loopback interface.
162 	 */
163 	bzero(&rtinfo, sizeof(struct rt_addrinfo));
164 	rtinfo.rti_info[RTAX_DST] = ifa->ifa_addr;
165 	rtinfo.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
166 	rtinfo.rti_info[RTAX_NETMASK] = (struct sockaddr *)&all1_sa;
167 	rtinfo.rti_flags = RTF_UP|RTF_HOST|RTF_LLINFO;
168 
169 	error = rtrequest1_global(cmd, &rtinfo,
170 	    in6_ifloop_request_callback, ifa, RTREQ_PRIO_NORM);
171 	if (error != 0) {
172 		log(LOG_ERR, "in6_ifloop_request: "
173 		    "%s operation failed for %s (errno=%d)\n",
174 		    cmd == RTM_ADD ? "ADD" : "DELETE",
175 		    ip6_sprintf(&((struct in6_ifaddr *)ifa)->ia_addr.sin6_addr),
176 		    error);
177 	}
178 }
179 
180 static void
181 in6_ifloop_request_callback(int cmd, int error, struct rt_addrinfo *rtinfo,
182 			    struct rtentry *rt, void *arg)
183 {
184 	struct ifaddr *ifa = arg;
185 
186 	if (error)
187 		goto done;
188 
189 	/*
190 	 * Make sure rt_ifa be equal to IFA, the second argument of the
191 	 * function.
192 	 * We need this because when we refer to rt_ifa->ia6_flags in
193 	 * ip6_input, we assume that the rt_ifa points to the address instead
194 	 * of the loopback address.
195 	 */
196 	if (cmd == RTM_ADD && rt && ifa != rt->rt_ifa) {
197 		++rt->rt_refcnt;
198 		IFAFREE(rt->rt_ifa);
199 		IFAREF(ifa);
200 		rt->rt_ifa = ifa;
201 		--rt->rt_refcnt;
202 	}
203 
204 	/*
205 	 * Report the addition/removal of the address to the routing socket.
206 	 * XXX: since we called rtinit for a p2p interface with a destination,
207 	 *      we end up reporting twice in such a case.  Should we rather
208 	 *      omit the second report?
209 	 */
210 	if (rt) {
211 		if (mycpuid == 0)
212 			rt_newaddrmsg(cmd, ifa, error, rt);
213 		if (cmd == RTM_DELETE) {
214 			if (rt->rt_refcnt == 0) {
215 				++rt->rt_refcnt;
216 				rtfree(rt);
217 			}
218 		}
219 	}
220 done:
221 	/* no way to return any new error */
222 	;
223 }
224 
225 /*
226  * Add ownaddr as loopback rtentry.  We previously add the route only if
227  * necessary (ex. on a p2p link).  However, since we now manage addresses
228  * separately from prefixes, we should always add the route.  We can't
229  * rely on the cloning mechanism from the corresponding interface route
230  * any more.
231  */
232 void
233 in6_ifaddloop(struct ifaddr *ifa)
234 {
235 	struct rtentry *rt;
236 
237 	/* If there is no loopback entry, allocate one. */
238 	rt = rtpurelookup(ifa->ifa_addr);
239 	if (rt == NULL || !(rt->rt_flags & RTF_HOST) ||
240 	    !(rt->rt_ifp->if_flags & IFF_LOOPBACK))
241 		in6_ifloop_request(RTM_ADD, ifa);
242 	if (rt != NULL)
243 		rt->rt_refcnt--;
244 }
245 
246 /*
247  * Remove loopback rtentry of ownaddr generated by in6_ifaddloop(),
248  * if it exists.
249  */
250 void
251 in6_ifremloop(struct ifaddr *ifa)
252 {
253 	struct in6_ifaddr *ia;
254 	struct rtentry *rt;
255 	int ia_count = 0;
256 
257 	/*
258 	 * Some of BSD variants do not remove cloned routes
259 	 * from an interface direct route, when removing the direct route
260 	 * (see comments in net/net_osdep.h).  Even for variants that do remove
261 	 * cloned routes, they could fail to remove the cloned routes when
262 	 * we handle multple addresses that share a common prefix.
263 	 * So, we should remove the route corresponding to the deleted address
264 	 * regardless of the result of in6_is_ifloop_auto().
265 	 */
266 
267 	/*
268 	 * Delete the entry only if exact one ifa exists.  More than one ifa
269 	 * can exist if we assign a same single address to multiple
270 	 * (probably p2p) interfaces.
271 	 * XXX: we should avoid such a configuration in IPv6...
272 	 */
273 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
274 		if (IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ia->ia_addr.sin6_addr)) {
275 			ia_count++;
276 			if (ia_count > 1)
277 				break;
278 		}
279 	}
280 
281 	if (ia_count == 1) {
282 		/*
283 		 * Before deleting, check if a corresponding loopbacked host
284 		 * route surely exists.  With this check, we can avoid to
285 		 * delete an interface direct route whose destination is same
286 		 * as the address being removed.  This can happen when remofing
287 		 * a subnet-router anycast address on an interface attahced
288 		 * to a shared medium.
289 		 */
290 		rt = rtpurelookup(ifa->ifa_addr);
291 		if (rt != NULL && (rt->rt_flags & RTF_HOST) &&
292 		    (rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
293 			rt->rt_refcnt--;
294 			in6_ifloop_request(RTM_DELETE, ifa);
295 		}
296 	}
297 }
298 
299 int
300 in6_ifindex2scopeid(int idx)
301 {
302 	struct ifnet *ifp;
303 	struct sockaddr_in6 *sin6;
304 	struct ifaddr_container *ifac;
305 
306 	if (idx < 0 || if_index < idx)
307 		return -1;
308 	ifp = ifindex2ifnet[idx];
309 
310 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link)
311 	{
312 		struct ifaddr *ifa = ifac->ifa;
313 
314 		if (ifa->ifa_addr->sa_family != AF_INET6)
315 			continue;
316 		sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
317 		if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))
318 			return sin6->sin6_scope_id & 0xffff;
319 	}
320 
321 	return -1;
322 }
323 
324 int
325 in6_mask2len(struct in6_addr *mask, u_char *lim0)
326 {
327 	int x = 0, y;
328 	u_char *lim = lim0, *p;
329 
330 	if (lim0 == NULL ||
331 	    lim0 - (u_char *)mask > sizeof(*mask)) /* ignore the scope_id part */
332 		lim = (u_char *)mask + sizeof(*mask);
333 	for (p = (u_char *)mask; p < lim; x++, p++) {
334 		if (*p != 0xff)
335 			break;
336 	}
337 	y = 0;
338 	if (p < lim) {
339 		for (y = 0; y < 8; y++) {
340 			if ((*p & (0x80 >> y)) == 0)
341 				break;
342 		}
343 	}
344 
345 	/*
346 	 * when the limit pointer is given, do a stricter check on the
347 	 * remaining bits.
348 	 */
349 	if (p < lim) {
350 		if (y != 0 && (*p & (0x00ff >> y)) != 0)
351 			return (-1);
352 		for (p = p + 1; p < lim; p++)
353 			if (*p != 0)
354 				return (-1);
355 	}
356 
357 	return x * 8 + y;
358 }
359 
360 void
361 in6_len2mask(struct in6_addr *mask, int len)
362 {
363 	int i;
364 
365 	bzero(mask, sizeof(*mask));
366 	for (i = 0; i < len / 8; i++)
367 		mask->s6_addr8[i] = 0xff;
368 	if (len % 8)
369 		mask->s6_addr8[i] = (0xff00 >> (len % 8)) & 0xff;
370 }
371 
372 #define ifa2ia6(ifa)	((struct in6_ifaddr *)(ifa))
373 #define ia62ifa(ia6)	(&((ia6)->ia_ifa))
374 
375 void
376 in6_control_dispatch(netmsg_t msg)
377 {
378 	int error;
379 
380 	error = in6_control(msg->control.base.nm_so,
381 			    msg->control.nm_cmd,
382 			    msg->control.nm_data,
383 			    msg->control.nm_ifp,
384 			    msg->control.nm_td);
385 	lwkt_replymsg(&msg->control.base.lmsg, error);
386 }
387 
388 int
389 in6_control(struct socket *so, u_long cmd, caddr_t data,
390 	    struct ifnet *ifp, struct thread *td)
391 {
392 	struct	in6_ifreq *ifr = (struct in6_ifreq *)data;
393 	struct	in6_ifaddr *ia = NULL;
394 	struct	in6_aliasreq *ifra = (struct in6_aliasreq *)data;
395 	int privileged;
396 	int error;
397 
398 	privileged = 0;
399 	if (priv_check(td, PRIV_ROOT) == 0)
400 		privileged++;
401 
402 	switch (cmd) {
403 	case SIOCGETSGCNT_IN6:
404 	case SIOCGETMIFCNT_IN6:
405 		return (mrt6_ioctl(cmd, data));
406 	}
407 
408 	switch(cmd) {
409 	case SIOCAADDRCTL_POLICY:
410 	case SIOCDADDRCTL_POLICY:
411 		if (!privileged)
412 			return (EPERM);
413 		return (in6_src_ioctl(cmd, data));
414 	}
415 
416 	if (ifp == NULL)
417 		return (EOPNOTSUPP);
418 
419 	switch (cmd) {
420 	case SIOCSNDFLUSH_IN6:
421 	case SIOCSPFXFLUSH_IN6:
422 	case SIOCSRTRFLUSH_IN6:
423 	case SIOCSDEFIFACE_IN6:
424 	case SIOCSIFINFO_FLAGS:
425 		if (!privileged)
426 			return (EPERM);
427 		/* fall through */
428 	case OSIOCGIFINFO_IN6:
429 	case SIOCGIFINFO_IN6:
430 	case SIOCGDRLST_IN6:
431 	case SIOCGPRLST_IN6:
432 	case SIOCGNBRINFO_IN6:
433 	case SIOCGDEFIFACE_IN6:
434 		return (nd6_ioctl(cmd, data, ifp));
435 	}
436 
437 	switch (cmd) {
438 	case SIOCSIFPREFIX_IN6:
439 	case SIOCDIFPREFIX_IN6:
440 	case SIOCAIFPREFIX_IN6:
441 	case SIOCCIFPREFIX_IN6:
442 	case SIOCSGIFPREFIX_IN6:
443 	case SIOCGIFPREFIX_IN6:
444 		log(LOG_NOTICE,
445 		    "prefix ioctls are now invalidated. "
446 		    "please use ifconfig.\n");
447 		return (EOPNOTSUPP);
448 	}
449 
450 	switch (cmd) {
451 	case SIOCSSCOPE6:
452 		if (!privileged)
453 			return (EPERM);
454 		return (scope6_set(ifp,
455 			(struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
456 		break;
457 	case SIOCGSCOPE6:
458 		return (scope6_get(ifp,
459 			(struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
460 		break;
461 	case SIOCGSCOPE6DEF:
462 		return (scope6_get_default((struct scope6_id *)
463 			ifr->ifr_ifru.ifru_scope_id));
464 		break;
465 	}
466 
467 	switch (cmd) {
468 	case SIOCALIFADDR:
469 	case SIOCDLIFADDR:
470 		if (!privileged)
471 			return (EPERM);
472 		/* fall through */
473 	case SIOCGLIFADDR:
474 		return in6_lifaddr_ioctl(so, cmd, data, ifp, td);
475 	}
476 
477 	/*
478 	 * Find address for this interface, if it exists.
479 	 */
480 	if (ifra->ifra_addr.sin6_family == AF_INET6) { /* XXX */
481 		struct sockaddr_in6 *sa6 =
482 			(struct sockaddr_in6 *)&ifra->ifra_addr;
483 
484 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
485 			if (sa6->sin6_addr.s6_addr16[1] == 0) {
486 				/* link ID is not embedded by the user */
487 				sa6->sin6_addr.s6_addr16[1] =
488 					htons(ifp->if_index);
489 			} else if (sa6->sin6_addr.s6_addr16[1] !=
490 				    htons(ifp->if_index)) {
491 				return (EINVAL);	/* link ID contradicts */
492 			}
493 			if (sa6->sin6_scope_id) {
494 				if (sa6->sin6_scope_id !=
495 				    (u_int32_t)ifp->if_index)
496 					return (EINVAL);
497 				sa6->sin6_scope_id = 0; /* XXX: good way? */
498 			}
499 		}
500 		ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr);
501 	}
502 
503 	switch (cmd) {
504 	case SIOCSIFADDR_IN6:
505 	case SIOCSIFDSTADDR_IN6:
506 	case SIOCSIFNETMASK_IN6:
507 		/*
508 		 * Since IPv6 allows a node to assign multiple addresses
509 		 * on a single interface, SIOCSIFxxx ioctls are not suitable
510 		 * and should be unused.
511 		 */
512 		/* we decided to obsolete this command (20000704) */
513 		return (EINVAL);
514 
515 	case SIOCDIFADDR_IN6:
516 		/*
517 		 * for IPv4, we look for existing in_ifaddr here to allow
518 		 * "ifconfig if0 delete" to remove first IPv4 address on the
519 		 * interface.  For IPv6, as the spec allow multiple interface
520 		 * address from the day one, we consider "remove the first one"
521 		 * semantics to be not preferable.
522 		 */
523 		if (ia == NULL)
524 			return (EADDRNOTAVAIL);
525 		/* FALLTHROUGH */
526 	case SIOCAIFADDR_IN6:
527 		/*
528 		 * We always require users to specify a valid IPv6 address for
529 		 * the corresponding operation.
530 		 */
531 		if (ifra->ifra_addr.sin6_family != AF_INET6 ||
532 		    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6))
533 			return (EAFNOSUPPORT);
534 		if (!privileged)
535 			return (EPERM);
536 
537 		break;
538 
539 	case SIOCGIFADDR_IN6:
540 		/* This interface is basically deprecated. use SIOCGIFCONF. */
541 		/* fall through */
542 	case SIOCGIFAFLAG_IN6:
543 	case SIOCGIFNETMASK_IN6:
544 	case SIOCGIFDSTADDR_IN6:
545 	case SIOCGIFALIFETIME_IN6:
546 		/* must think again about its semantics */
547 		if (ia == NULL)
548 			return (EADDRNOTAVAIL);
549 		break;
550 	case SIOCSIFALIFETIME_IN6:
551 	    {
552 		struct in6_addrlifetime *lt;
553 
554 		if (!privileged)
555 			return (EPERM);
556 		if (ia == NULL)
557 			return (EADDRNOTAVAIL);
558 		/* sanity for overflow - beware unsigned */
559 		lt = &ifr->ifr_ifru.ifru_lifetime;
560 		if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
561 		    && lt->ia6t_vltime + time_uptime < time_uptime) {
562 			return EINVAL;
563 		}
564 		if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
565 		    && lt->ia6t_pltime + time_uptime < time_uptime) {
566 			return EINVAL;
567 		}
568 		break;
569 	    }
570 	}
571 
572 	switch (cmd) {
573 
574 	case SIOCGIFADDR_IN6:
575 		ifr->ifr_addr = ia->ia_addr;
576 		break;
577 
578 	case SIOCGIFDSTADDR_IN6:
579 		if (!(ifp->if_flags & IFF_POINTOPOINT))
580 			return (EINVAL);
581 		/*
582 		 * XXX: should we check if ifa_dstaddr is NULL and return
583 		 * an error?
584 		 */
585 		ifr->ifr_dstaddr = ia->ia_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 			return EINVAL;
599 		bzero(&ifr->ifr_ifru.ifru_stat,
600 			sizeof(ifr->ifr_ifru.ifru_stat));
601 		ifr->ifr_ifru.ifru_stat =
602 			*((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
603 		break;
604 
605 	case SIOCGIFSTAT_ICMP6:
606 		bzero(&ifr->ifr_ifru.ifru_stat,
607 			sizeof(ifr->ifr_ifru.ifru_icmp6stat));
608 		ifr->ifr_ifru.ifru_icmp6stat =
609 			*((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
610 		break;
611 
612 	case SIOCSIFADDR:
613 	case SIOCSIFDSTADDR:
614 	case SIOCSIFBRDADDR:
615 	case SIOCSIFNETMASK:
616 		/*
617 		 * Do not pass those ioctl to driver handler since they are not
618 		 * properly setup.  Instead just error out.
619 		 */
620 		return (EOPNOTSUPP);
621 
622 	case SIOCGIFALIFETIME_IN6:
623 		ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
624 		break;
625 
626 	case SIOCSIFALIFETIME_IN6:
627 		ia->ia6_lifetime = ifr->ifr_ifru.ifru_lifetime;
628 		/* for sanity */
629 		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
630 			ia->ia6_lifetime.ia6t_expire =
631 				time_uptime + ia->ia6_lifetime.ia6t_vltime;
632 		} else
633 			ia->ia6_lifetime.ia6t_expire = 0;
634 		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
635 			ia->ia6_lifetime.ia6t_preferred =
636 				time_uptime + ia->ia6_lifetime.ia6t_pltime;
637 		} else
638 			ia->ia6_lifetime.ia6t_preferred = 0;
639 		break;
640 
641 	case SIOCAIFADDR_IN6:
642 	{
643 		int i, error = 0, iaIsNew;
644 		struct nd_prefix pr0, *pr;
645 
646 		if (ia != NULL)
647 			iaIsNew = 0;
648 		else
649 			iaIsNew = 1;
650 
651 		/*
652 		 * first, make or update the interface address structure,
653 		 * and link it to the list.
654 		 */
655 		if ((error = in6_update_ifa(ifp, ifra, ia)) != 0)
656 			return (error);
657 
658 		/*
659 		 * then, make the prefix on-link on the interface.
660 		 * XXX: we'd rather create the prefix before the address, but
661 		 * we need at least one address to install the corresponding
662 		 * interface route, so we configure the address first.
663 		 */
664 
665 		/*
666 		 * convert mask to prefix length (prefixmask has already
667 		 * been validated in in6_update_ifa().
668 		 */
669 		bzero(&pr0, sizeof(pr0));
670 		pr0.ndpr_ifp = ifp;
671 		pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
672 					     NULL);
673 		if (pr0.ndpr_plen == 128)
674 			break;	/* we don't need to install a host route. */
675 		pr0.ndpr_prefix = ifra->ifra_addr;
676 		pr0.ndpr_mask = ifra->ifra_prefixmask.sin6_addr;
677 		/* apply the mask for safety. */
678 		for (i = 0; i < 4; i++) {
679 			pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
680 				ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
681 		}
682 		/*
683 		 * XXX: since we don't have an API to set prefix (not address)
684 		 * lifetimes, we just use the same lifetimes as addresses.
685 		 * The (temporarily) installed lifetimes can be overridden by
686 		 * later advertised RAs (when accept_rtadv is non 0), which is
687 		 * an intended behavior.
688 		 */
689 		pr0.ndpr_raf_onlink = 1; /* should be configurable? */
690 		pr0.ndpr_raf_auto =
691 			((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
692 		pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
693 		pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
694 
695 		/* add the prefix if there's one. */
696 		if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
697 			/*
698 			 * nd6_prelist_add will install the corresponding
699 			 * interface route.
700 			 */
701 			if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
702 				return (error);
703 			if (pr == NULL) {
704 				log(LOG_ERR, "nd6_prelist_add succeeded but "
705 				    "no prefix\n");
706 				return (EINVAL); /* XXX panic here? */
707 			}
708 		}
709 		if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
710 		    == NULL) {
711 		    	/* XXX: this should not happen! */
712 			log(LOG_ERR, "in6_control: addition succeeded, but"
713 			    " no ifaddr\n");
714 		} else {
715 			if ((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
716 			    ia->ia6_ndpr == NULL) { /* new autoconfed addr */
717 				ia->ia6_ndpr = pr;
718 				pr->ndpr_refcnt++;
719 
720 				/*
721 				 * If this is the first autoconf address from
722 				 * the prefix, create a temporary address
723 				 * as well (when specified).
724 				 */
725 				if (ip6_use_tempaddr &&
726 				    pr->ndpr_refcnt == 1) {
727 					int e;
728 					if ((e = in6_tmpifadd(ia, 1)) != 0) {
729 						log(LOG_NOTICE, "in6_control: "
730 						    "failed to create a "
731 						    "temporary address, "
732 						    "errno=%d\n",
733 						    e);
734 					}
735 				}
736 			}
737 
738 			/*
739 			 * this might affect the status of autoconfigured
740 			 * addresses, that is, this address might make
741 			 * other addresses detached.
742 			 */
743 			pfxlist_onlink_check();
744 		}
745 		if (error == 0 && ia) {
746 			EVENTHANDLER_INVOKE(ifaddr_event, ifp,
747 			iaIsNew ? IFADDR_EVENT_ADD : IFADDR_EVENT_CHANGE,
748 			&ia->ia_ifa);
749 		}
750 		break;
751 	}
752 
753 	case SIOCDIFADDR_IN6:
754 	{
755 		int i = 0;
756 		struct nd_prefix pr0, *pr;
757 
758 		/*
759 		 * If the address being deleted is the only one that owns
760 		 * the corresponding prefix, expire the prefix as well.
761 		 * XXX: theoretically, we don't have to warry about such
762 		 * relationship, since we separate the address management
763 		 * and the prefix management.  We do this, however, to provide
764 		 * as much backward compatibility as possible in terms of
765 		 * the ioctl operation.
766 		 */
767 		bzero(&pr0, sizeof(pr0));
768 		pr0.ndpr_ifp = ifp;
769 		pr0.ndpr_plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr,
770 					     NULL);
771 		if (pr0.ndpr_plen == 128)
772 			goto purgeaddr;
773 		pr0.ndpr_prefix = ia->ia_addr;
774 		pr0.ndpr_mask = ia->ia_prefixmask.sin6_addr;
775 		for (i = 0; i < 4; i++) {
776 			pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
777 				ia->ia_prefixmask.sin6_addr.s6_addr32[i];
778 		}
779 		/*
780 		 * The logic of the following condition is a bit complicated.
781 		 * We expire the prefix when
782 		 * 1. the address obeys autoconfiguration and it is the
783 		 *    only owner of the associated prefix, or
784 		 * 2. the address does not obey autoconf and there is no
785 		 *    other owner of the prefix.
786 		 */
787 		if ((pr = nd6_prefix_lookup(&pr0)) != NULL &&
788 		    (((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
789 		       pr->ndpr_refcnt == 1) ||
790 		     (!(ia->ia6_flags & IN6_IFF_AUTOCONF) &&
791 		      pr->ndpr_refcnt == 0))) {
792 			pr->ndpr_expire = 1; /* XXX: just for expiration */
793 		}
794 
795 purgeaddr:
796 		EVENTHANDLER_INVOKE(ifaddr_event, ifp, IFADDR_EVENT_DELETE,
797 				    &ia->ia_ifa);
798 		in6_purgeaddr(&ia->ia_ifa);
799 		break;
800 	}
801 
802 	default:
803 		if (ifp == NULL || ifp->if_ioctl == NULL)
804 			return (EOPNOTSUPP);
805 		ifnet_serialize_all(ifp);
806 		error = ifp->if_ioctl(ifp, cmd, data, td->td_proc->p_ucred);
807 		ifnet_deserialize_all(ifp);
808 		return (error);
809 	}
810 
811 	return (0);
812 }
813 
814 /*
815  * Update parameters of an IPv6 interface address.
816  * If necessary, a new entry is created and linked into address chains.
817  * This function is separated from in6_control().
818  * XXX: should this be performed under splnet()?
819  */
820 int
821 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
822 	       struct in6_ifaddr *ia)
823 {
824 	int error = 0, hostIsNew = 0, plen = -1;
825 	struct in6_ifaddr *oia;
826 	struct sockaddr_in6 dst6;
827 	struct in6_addrlifetime *lt;
828 
829 	/* Validate parameters */
830 	if (ifp == NULL || ifra == NULL) /* this maybe redundant */
831 		return (EINVAL);
832 
833 	/*
834 	 * The destination address for a p2p link must have a family
835 	 * of AF_UNSPEC or AF_INET6.
836 	 */
837 	if ((ifp->if_flags & IFF_POINTOPOINT) &&
838 	    ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
839 	    ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
840 		return (EAFNOSUPPORT);
841 	/*
842 	 * validate ifra_prefixmask.  don't check sin6_family, netmask
843 	 * does not carry fields other than sin6_len.
844 	 */
845 	if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
846 		return (EINVAL);
847 	/*
848 	 * Because the IPv6 address architecture is classless, we require
849 	 * users to specify a (non 0) prefix length (mask) for a new address.
850 	 * We also require the prefix (when specified) mask is valid, and thus
851 	 * reject a non-consecutive mask.
852 	 */
853 	if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
854 		return (EINVAL);
855 	if (ifra->ifra_prefixmask.sin6_len != 0) {
856 		plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
857 				    (u_char *)&ifra->ifra_prefixmask +
858 				    ifra->ifra_prefixmask.sin6_len);
859 		if (plen <= 0)
860 			return (EINVAL);
861 	}
862 	else {
863 		/*
864 		 * In this case, ia must not be NULL.  We just use its prefix
865 		 * length.
866 		 */
867 		plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
868 	}
869 	/*
870 	 * If the destination address on a p2p interface is specified,
871 	 * and the address is a scoped one, validate/set the scope
872 	 * zone identifier.
873 	 */
874 	dst6 = ifra->ifra_dstaddr;
875 	if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) &&
876 	    (dst6.sin6_family == AF_INET6)) {
877 		int scopeid;
878 
879 		if ((error = in6_recoverscope(&dst6,
880 					      &ifra->ifra_dstaddr.sin6_addr,
881 					      ifp)) != 0)
882 			return (error);
883 		scopeid = in6_addr2scopeid(ifp, &dst6.sin6_addr);
884 		if (dst6.sin6_scope_id == 0) /* user omit to specify the ID. */
885 			dst6.sin6_scope_id = scopeid;
886 		else if (dst6.sin6_scope_id != scopeid)
887 			return (EINVAL); /* scope ID mismatch. */
888 		if ((error = in6_embedscope(&dst6.sin6_addr, &dst6, NULL, NULL))
889 		    != 0)
890 			return (error);
891 		dst6.sin6_scope_id = 0; /* XXX */
892 	}
893 	/*
894 	 * The destination address can be specified only for a p2p or a
895 	 * loopback interface.  If specified, the corresponding prefix length
896 	 * must be 128.
897 	 */
898 	if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
899 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
900 			/* XXX: noisy message */
901 			log(LOG_INFO, "in6_update_ifa: a destination can be "
902 			    "specified for a p2p or a loopback IF only\n");
903 			return (EINVAL);
904 		}
905 		if (plen != 128) {
906 			/*
907 			 * The following message seems noisy, but we dare to
908 			 * add it for diagnosis.
909 			 */
910 			log(LOG_INFO, "in6_update_ifa: prefixlen must be 128 "
911 			    "when dstaddr is specified\n");
912 			return (EINVAL);
913 		}
914 	}
915 	/* lifetime consistency check */
916 	lt = &ifra->ifra_lifetime;
917 	if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
918 	    && lt->ia6t_vltime + time_uptime < time_uptime) {
919 		return EINVAL;
920 	}
921 	if (lt->ia6t_vltime == 0) {
922 		/*
923 		 * the following log might be noisy, but this is a typical
924 		 * configuration mistake or a tool's bug.
925 		 */
926 		log(LOG_INFO,
927 		    "in6_update_ifa: valid lifetime is 0 for %s\n",
928 		    ip6_sprintf(&ifra->ifra_addr.sin6_addr));
929 	}
930 	if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
931 	    && lt->ia6t_pltime + time_uptime < time_uptime) {
932 		return EINVAL;
933 	}
934 
935 	/*
936 	 * If this is a new address, allocate a new ifaddr and link it
937 	 * into chains.
938 	 */
939 	if (ia == NULL) {
940 		hostIsNew = 1;
941 		/*
942 		 * When in6_update_ifa() is called in a process of a received
943 		 * RA, it is called under splnet().  So, we should call malloc
944 		 * with M_NOWAIT.
945 		 */
946 		ia = ifa_create(sizeof(*ia), M_NOWAIT);
947 		if (ia == NULL)
948 			return (ENOBUFS);
949 		/* Initialize the address and masks */
950 		ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
951 		ia->ia_addr.sin6_family = AF_INET6;
952 		ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
953 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
954 			/*
955 			 * XXX: some functions expect that ifa_dstaddr is not
956 			 * NULL for p2p interfaces.
957 			 */
958 			ia->ia_ifa.ifa_dstaddr
959 				= (struct sockaddr *)&ia->ia_dstaddr;
960 		} else {
961 			ia->ia_ifa.ifa_dstaddr = NULL;
962 		}
963 		ia->ia_ifa.ifa_netmask
964 			= (struct sockaddr *)&ia->ia_prefixmask;
965 
966 		ia->ia_ifp = ifp;
967 		if ((oia = in6_ifaddr) != NULL) {
968 			for ( ; oia->ia_next; oia = oia->ia_next)
969 				continue;
970 			oia->ia_next = ia;
971 		} else
972 			in6_ifaddr = ia;
973 
974 		ifa_iflink(&ia->ia_ifa, ifp, 1);
975 	}
976 
977 	/* set prefix mask */
978 	if (ifra->ifra_prefixmask.sin6_len) {
979 		/*
980 		 * We prohibit changing the prefix length of an existing
981 		 * address, because
982 		 * + such an operation should be rare in IPv6, and
983 		 * + the operation would confuse prefix management.
984 		 */
985 		if (ia->ia_prefixmask.sin6_len &&
986 		    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
987 			log(LOG_INFO, "in6_update_ifa: the prefix length of an"
988 			    " existing (%s) address should not be changed\n",
989 			    ip6_sprintf(&ia->ia_addr.sin6_addr));
990 			error = EINVAL;
991 			goto unlink;
992 		}
993 		ia->ia_prefixmask = ifra->ifra_prefixmask;
994 	}
995 
996 	/*
997 	 * If a new destination address is specified, scrub the old one and
998 	 * install the new destination.  Note that the interface must be
999 	 * p2p or loopback (see the check above.)
1000 	 */
1001 	if (dst6.sin6_family == AF_INET6 &&
1002 	    !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr,
1003 				&ia->ia_dstaddr.sin6_addr)) {
1004 		int e;
1005 
1006 		if ((ia->ia_flags & IFA_ROUTE) &&
1007 		    (e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1008 		    != 0) {
1009 			log(LOG_ERR, "in6_update_ifa: failed to remove "
1010 			    "a route to the old destination: %s\n",
1011 			    ip6_sprintf(&ia->ia_addr.sin6_addr));
1012 			/* proceed anyway... */
1013 		}
1014 		else
1015 			ia->ia_flags &= ~IFA_ROUTE;
1016 		ia->ia_dstaddr = dst6;
1017 	}
1018 
1019 	/* reset the interface and routing table appropriately. */
1020 	if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
1021 		goto unlink;
1022 
1023 	/*
1024 	 * Beyond this point, we should call in6_purgeaddr upon an error,
1025 	 * not just go to unlink.
1026 	 */
1027 
1028 #if 0				/* disable this mechanism for now */
1029 	/* update prefix list */
1030 	if (hostIsNew &&
1031 	    (ifra->ifra_flags & IN6_IFF_NOPFX) == 0) { /* XXX */
1032 		int iilen;
1033 
1034 		iilen = (sizeof(ia->ia_prefixmask.sin6_addr) << 3) - plen;
1035 		if ((error = in6_prefix_add_ifid(iilen, ia)) != 0) {
1036 			in6_purgeaddr((struct ifaddr *)ia);
1037 			return (error);
1038 		}
1039 	}
1040 #endif
1041 
1042 	if (ifp->if_flags & IFF_MULTICAST) {
1043 		struct sockaddr_in6 mltaddr, mltmask;
1044 		struct in6_multi *in6m;
1045 
1046 		if (hostIsNew) {
1047 			/*
1048 			 * join solicited multicast addr for new host id
1049 			 */
1050 			struct in6_addr llsol;
1051 			bzero(&llsol, sizeof(struct in6_addr));
1052 			llsol.s6_addr16[0] = htons(0xff02);
1053 			llsol.s6_addr16[1] = htons(ifp->if_index);
1054 			llsol.s6_addr32[1] = 0;
1055 			llsol.s6_addr32[2] = htonl(1);
1056 			llsol.s6_addr32[3] =
1057 				ifra->ifra_addr.sin6_addr.s6_addr32[3];
1058 			llsol.s6_addr8[12] = 0xff;
1059 			in6_addmulti(&llsol, ifp, &error);
1060 			if (error != 0) {
1061 				log(LOG_WARNING,
1062 				    "in6_update_ifa: addmulti failed for "
1063 				    "%s on %s (errno=%d)\n",
1064 				    ip6_sprintf(&llsol), if_name(ifp),
1065 				    error);
1066 				in6_purgeaddr((struct ifaddr *)ia);
1067 				return (error);
1068 			}
1069 		}
1070 
1071 		bzero(&mltmask, sizeof(mltmask));
1072 		mltmask.sin6_len = sizeof(struct sockaddr_in6);
1073 		mltmask.sin6_family = AF_INET6;
1074 		mltmask.sin6_addr = in6mask32;
1075 
1076 		/*
1077 		 * join link-local all-nodes address
1078 		 */
1079 		bzero(&mltaddr, sizeof(mltaddr));
1080 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1081 		mltaddr.sin6_family = AF_INET6;
1082 		mltaddr.sin6_addr = kin6addr_linklocal_allnodes;
1083 		mltaddr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1084 
1085 		IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1086 		if (in6m == NULL) {
1087 			rtrequest_global(RTM_ADD,
1088 				  (struct sockaddr *)&mltaddr,
1089 				  (struct sockaddr *)&ia->ia_addr,
1090 				  (struct sockaddr *)&mltmask,
1091 				  RTF_UP|RTF_CLONING);  /* xxx */
1092 			in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1093 			if (error != 0) {
1094 				log(LOG_WARNING,
1095 				    "in6_update_ifa: addmulti failed for "
1096 				    "%s on %s (errno=%d)\n",
1097 				    ip6_sprintf(&mltaddr.sin6_addr),
1098 				    if_name(ifp), error);
1099 			}
1100 		}
1101 
1102 		/*
1103 		 * join node information group address
1104 		 */
1105 #define hostnamelen	strlen(hostname)
1106 		if (in6_nigroup(ifp, hostname, hostnamelen, &mltaddr.sin6_addr)
1107 		    == 0) {
1108 			IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1109 			if (in6m == NULL && ia != NULL) {
1110 				in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1111 				if (error != 0) {
1112 					log(LOG_WARNING, "in6_update_ifa: "
1113 					    "addmulti failed for "
1114 					    "%s on %s (errno=%d)\n",
1115 					    ip6_sprintf(&mltaddr.sin6_addr),
1116 					    if_name(ifp), error);
1117 				}
1118 			}
1119 		}
1120 #undef hostnamelen
1121 
1122 		/*
1123 		 * join node-local all-nodes address, on loopback.
1124 		 * XXX: since "node-local" is obsoleted by interface-local,
1125 		 *      we have to join the group on every interface with
1126 		 *      some interface-boundary restriction.
1127 		 */
1128 		if (ifp->if_flags & IFF_LOOPBACK) {
1129 			struct in6_ifaddr *ia_loop;
1130 
1131 			struct in6_addr loop6 = kin6addr_loopback;
1132 			ia_loop = in6ifa_ifpwithaddr(ifp, &loop6);
1133 
1134 			mltaddr.sin6_addr = kin6addr_nodelocal_allnodes;
1135 
1136 			IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1137 			if (in6m == NULL && ia_loop != NULL) {
1138 				rtrequest_global(RTM_ADD,
1139 					  (struct sockaddr *)&mltaddr,
1140 					  (struct sockaddr *)&ia_loop->ia_addr,
1141 					  (struct sockaddr *)&mltmask,
1142 					  RTF_UP);
1143 				in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1144 				if (error != 0) {
1145 					log(LOG_WARNING, "in6_update_ifa: "
1146 					    "addmulti failed for %s on %s "
1147 					    "(errno=%d)\n",
1148 					    ip6_sprintf(&mltaddr.sin6_addr),
1149 					    if_name(ifp), error);
1150 				}
1151 			}
1152 		}
1153 	}
1154 
1155 	ia->ia6_flags = ifra->ifra_flags;
1156 	ia->ia6_flags &= ~IN6_IFF_DUPLICATED;	/*safety*/
1157 	ia->ia6_flags &= ~IN6_IFF_NODAD;	/* Mobile IPv6 */
1158 
1159 	ia->ia6_lifetime = ifra->ifra_lifetime;
1160 	/* for sanity */
1161 	if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1162 		ia->ia6_lifetime.ia6t_expire =
1163 			time_uptime + ia->ia6_lifetime.ia6t_vltime;
1164 	} else
1165 		ia->ia6_lifetime.ia6t_expire = 0;
1166 	if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1167 		ia->ia6_lifetime.ia6t_preferred =
1168 			time_uptime + ia->ia6_lifetime.ia6t_pltime;
1169 	} else
1170 		ia->ia6_lifetime.ia6t_preferred = 0;
1171 
1172 	/*
1173 	 * Perform DAD, if needed.
1174 	 * XXX It may be of use, if we can administratively
1175 	 * disable DAD.
1176 	 */
1177 	if (in6if_do_dad(ifp) && !(ifra->ifra_flags & IN6_IFF_NODAD)) {
1178 		ia->ia6_flags |= IN6_IFF_TENTATIVE;
1179 		nd6_dad_start((struct ifaddr *)ia, NULL);
1180 	}
1181 
1182 	return (error);
1183 
1184 unlink:
1185 	/*
1186 	 * XXX: if a change of an existing address failed, keep the entry
1187 	 * anyway.
1188 	 */
1189 	if (hostIsNew)
1190 		in6_unlink_ifa(ia, ifp);
1191 	return (error);
1192 }
1193 
1194 void
1195 in6_purgeaddr(struct ifaddr *ifa)
1196 {
1197 	struct ifnet *ifp = ifa->ifa_ifp;
1198 	struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1199 
1200 	/* stop DAD processing */
1201 	nd6_dad_stop(ifa);
1202 
1203 	/*
1204 	 * delete route to the destination of the address being purged.
1205 	 * The interface must be p2p or loopback in this case.
1206 	 */
1207 	if ((ia->ia_flags & IFA_ROUTE) && ia->ia_dstaddr.sin6_len != 0) {
1208 		int e;
1209 
1210 		if ((e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1211 		    != 0) {
1212 			log(LOG_ERR, "in6_purgeaddr: failed to remove "
1213 			    "a route to the p2p destination: %s on %s, "
1214 			    "errno=%d\n",
1215 			    ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
1216 			    e);
1217 			/* proceed anyway... */
1218 		}
1219 		else
1220 			ia->ia_flags &= ~IFA_ROUTE;
1221 	}
1222 
1223 	/* Remove ownaddr's loopback rtentry, if it exists. */
1224 	in6_ifremloop(&(ia->ia_ifa));
1225 
1226 	if (ifp->if_flags & IFF_MULTICAST) {
1227 		/*
1228 		 * delete solicited multicast addr for deleting host id
1229 		 */
1230 		struct in6_multi *in6m;
1231 		struct in6_addr llsol;
1232 		bzero(&llsol, sizeof(struct in6_addr));
1233 		llsol.s6_addr16[0] = htons(0xff02);
1234 		llsol.s6_addr16[1] = htons(ifp->if_index);
1235 		llsol.s6_addr32[1] = 0;
1236 		llsol.s6_addr32[2] = htonl(1);
1237 		llsol.s6_addr32[3] =
1238 			ia->ia_addr.sin6_addr.s6_addr32[3];
1239 		llsol.s6_addr8[12] = 0xff;
1240 
1241 		IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1242 		if (in6m)
1243 			in6_delmulti(in6m);
1244 	}
1245 
1246 	in6_unlink_ifa(ia, ifp);
1247 }
1248 
1249 static void
1250 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1251 {
1252 	int plen, iilen;
1253 	struct in6_ifaddr *oia;
1254 
1255 	crit_enter();
1256 
1257 	ifa_ifunlink(&ia->ia_ifa, ifp);
1258 
1259 	oia = ia;
1260 	if (oia == (ia = in6_ifaddr))
1261 		in6_ifaddr = ia->ia_next;
1262 	else {
1263 		while (ia->ia_next && (ia->ia_next != oia))
1264 			ia = ia->ia_next;
1265 		if (ia->ia_next)
1266 			ia->ia_next = oia->ia_next;
1267 		else {
1268 			/* search failed */
1269 			kprintf("Couldn't unlink in6_ifaddr from in6_ifaddr\n");
1270 		}
1271 	}
1272 
1273 	if (oia->ia6_ifpr) {	/* check for safety */
1274 		plen = in6_mask2len(&oia->ia_prefixmask.sin6_addr, NULL);
1275 		iilen = (sizeof(oia->ia_prefixmask.sin6_addr) << 3) - plen;
1276 		in6_prefix_remove_ifid(iilen, oia);
1277 	}
1278 
1279 	/*
1280 	 * When an autoconfigured address is being removed, release the
1281 	 * reference to the base prefix.  Also, since the release might
1282 	 * affect the status of other (detached) addresses, call
1283 	 * pfxlist_onlink_check().
1284 	 */
1285 	if (oia->ia6_flags & IN6_IFF_AUTOCONF) {
1286 		if (oia->ia6_ndpr == NULL) {
1287 			log(LOG_NOTICE, "in6_unlink_ifa: autoconf'ed address "
1288 			    "%p has no prefix\n", oia);
1289 		} else {
1290 			oia->ia6_ndpr->ndpr_refcnt--;
1291 			oia->ia6_flags &= ~IN6_IFF_AUTOCONF;
1292 			oia->ia6_ndpr = NULL;
1293 		}
1294 
1295 		pfxlist_onlink_check();
1296 	}
1297 
1298 	/*
1299 	 * release another refcnt for the link from in6_ifaddr.
1300 	 * Note that we should decrement the refcnt at least once for all *BSD.
1301 	 */
1302 	ifa_destroy(&oia->ia_ifa);
1303 
1304 	crit_exit();
1305 }
1306 
1307 void
1308 in6_purgeif(struct ifnet *ifp)
1309 {
1310 	struct ifaddr_container *ifac, *next;
1311 
1312 	TAILQ_FOREACH_MUTABLE(ifac, &ifp->if_addrheads[mycpuid],
1313 			      ifa_link, next) {
1314 		if (ifac->ifa->ifa_addr->sa_family != AF_INET6)
1315 			continue;
1316 		in6_purgeaddr(ifac->ifa);
1317 	}
1318 
1319 	in6_ifdetach(ifp);
1320 }
1321 
1322 /*
1323  * SIOC[GAD]LIFADDR.
1324  *	SIOCGLIFADDR: get first address. (?)
1325  *	SIOCGLIFADDR with IFLR_PREFIX:
1326  *		get first address that matches the specified prefix.
1327  *	SIOCALIFADDR: add the specified address.
1328  *	SIOCALIFADDR with IFLR_PREFIX:
1329  *		add the specified prefix, filling hostid part from
1330  *		the first link-local address.  prefixlen must be <= 64.
1331  *	SIOCDLIFADDR: delete the specified address.
1332  *	SIOCDLIFADDR with IFLR_PREFIX:
1333  *		delete the first address that matches the specified prefix.
1334  * return values:
1335  *	EINVAL on invalid parameters
1336  *	EADDRNOTAVAIL on prefix match failed/specified address not found
1337  *	other values may be returned from in6_ioctl()
1338  *
1339  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1340  * this is to accomodate address naming scheme other than RFC2374,
1341  * in the future.
1342  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1343  * address encoding scheme. (see figure on page 8)
1344  */
1345 static int
1346 in6_lifaddr_ioctl(struct socket *so, u_long cmd, caddr_t data,
1347 		  struct ifnet *ifp, struct thread *td)
1348 {
1349 	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1350 	struct sockaddr *sa;
1351 
1352 	/* sanity checks */
1353 	if (!data || !ifp) {
1354 		panic("invalid argument to in6_lifaddr_ioctl");
1355 		/*NOTRECHED*/
1356 	}
1357 
1358 	switch (cmd) {
1359 	case SIOCGLIFADDR:
1360 		/* address must be specified on GET with IFLR_PREFIX */
1361 		if (!(iflr->flags & IFLR_PREFIX))
1362 			break;
1363 		/* FALLTHROUGH */
1364 	case SIOCALIFADDR:
1365 	case SIOCDLIFADDR:
1366 		/* address must be specified on ADD and DELETE */
1367 		sa = (struct sockaddr *)&iflr->addr;
1368 		if (sa->sa_family != AF_INET6)
1369 			return EINVAL;
1370 		if (sa->sa_len != sizeof(struct sockaddr_in6))
1371 			return EINVAL;
1372 		/* XXX need improvement */
1373 		sa = (struct sockaddr *)&iflr->dstaddr;
1374 		if (sa->sa_family && sa->sa_family != AF_INET6)
1375 			return EINVAL;
1376 		if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1377 			return EINVAL;
1378 		break;
1379 	default: /* shouldn't happen */
1380 #if 0
1381 		panic("invalid cmd to in6_lifaddr_ioctl");
1382 		/* NOTREACHED */
1383 #else
1384 		return EOPNOTSUPP;
1385 #endif
1386 	}
1387 	if (sizeof(struct in6_addr) * 8 < iflr->prefixlen)
1388 		return EINVAL;
1389 
1390 	switch (cmd) {
1391 	case SIOCALIFADDR:
1392 	    {
1393 		struct in6_aliasreq ifra;
1394 		struct in6_addr *hostid = NULL;
1395 		int prefixlen;
1396 
1397 		if (iflr->flags & IFLR_PREFIX) {
1398 			struct ifaddr *ifa;
1399 			struct sockaddr_in6 *sin6;
1400 
1401 			/*
1402 			 * hostid is to fill in the hostid part of the
1403 			 * address.  hostid points to the first link-local
1404 			 * address attached to the interface.
1405 			 */
1406 			ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);
1407 			if (!ifa)
1408 				return EADDRNOTAVAIL;
1409 			hostid = IFA_IN6(ifa);
1410 
1411 		 	/* prefixlen must be <= 64. */
1412 			if (64 < iflr->prefixlen)
1413 				return EINVAL;
1414 			prefixlen = iflr->prefixlen;
1415 
1416 			/* hostid part must be zero. */
1417 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1418 			if (sin6->sin6_addr.s6_addr32[2] != 0
1419 			 || sin6->sin6_addr.s6_addr32[3] != 0) {
1420 				return EINVAL;
1421 			}
1422 		} else
1423 			prefixlen = iflr->prefixlen;
1424 
1425 		/* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1426 		bzero(&ifra, sizeof(ifra));
1427 		bcopy(iflr->iflr_name, ifra.ifra_name,
1428 			sizeof(ifra.ifra_name));
1429 
1430 		bcopy(&iflr->addr, &ifra.ifra_addr,
1431 			((struct sockaddr *)&iflr->addr)->sa_len);
1432 		if (hostid) {
1433 			/* fill in hostid part */
1434 			ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1435 				hostid->s6_addr32[2];
1436 			ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1437 				hostid->s6_addr32[3];
1438 		}
1439 
1440 		if (((struct sockaddr *)&iflr->dstaddr)->sa_family) {	/*XXX*/
1441 			bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
1442 				((struct sockaddr *)&iflr->dstaddr)->sa_len);
1443 			if (hostid) {
1444 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1445 					hostid->s6_addr32[2];
1446 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1447 					hostid->s6_addr32[3];
1448 			}
1449 		}
1450 
1451 		ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1452 		in6_len2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1453 
1454 		ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1455 		return in6_control(so, SIOCAIFADDR_IN6, (caddr_t)&ifra, ifp, td);
1456 	    }
1457 	case SIOCGLIFADDR:
1458 	case SIOCDLIFADDR:
1459 	    {
1460 		struct ifaddr_container *ifac;
1461 		struct in6_ifaddr *ia;
1462 		struct in6_addr mask, candidate, match;
1463 		struct sockaddr_in6 *sin6;
1464 		int cmp;
1465 
1466 		bzero(&mask, sizeof(mask));
1467 		if (iflr->flags & IFLR_PREFIX) {
1468 			/* lookup a prefix rather than address. */
1469 			in6_len2mask(&mask, iflr->prefixlen);
1470 
1471 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1472 			bcopy(&sin6->sin6_addr, &match, sizeof(match));
1473 			match.s6_addr32[0] &= mask.s6_addr32[0];
1474 			match.s6_addr32[1] &= mask.s6_addr32[1];
1475 			match.s6_addr32[2] &= mask.s6_addr32[2];
1476 			match.s6_addr32[3] &= mask.s6_addr32[3];
1477 
1478 			/* if you set extra bits, that's wrong */
1479 			if (bcmp(&match, &sin6->sin6_addr, sizeof(match)))
1480 				return EINVAL;
1481 
1482 			cmp = 1;
1483 		} else {
1484 			if (cmd == SIOCGLIFADDR) {
1485 				/* on getting an address, take the 1st match */
1486 				cmp = 0;	/* XXX */
1487 			} else {
1488 				/* on deleting an address, do exact match */
1489 				in6_len2mask(&mask, 128);
1490 				sin6 = (struct sockaddr_in6 *)&iflr->addr;
1491 				bcopy(&sin6->sin6_addr, &match, sizeof(match));
1492 
1493 				cmp = 1;
1494 			}
1495 		}
1496 
1497 		TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1498 			struct ifaddr *ifa = ifac->ifa;
1499 
1500 			if (ifa->ifa_addr->sa_family != AF_INET6)
1501 				continue;
1502 			if (!cmp)
1503 				break;
1504 
1505 			bcopy(IFA_IN6(ifa), &candidate, sizeof(candidate));
1506 			/*
1507 			 * XXX: this is adhoc, but is necessary to allow
1508 			 * a user to specify fe80::/64 (not /10) for a
1509 			 * link-local address.
1510 			 */
1511 			if (IN6_IS_ADDR_LINKLOCAL(&candidate))
1512 				candidate.s6_addr16[1] = 0;
1513 			candidate.s6_addr32[0] &= mask.s6_addr32[0];
1514 			candidate.s6_addr32[1] &= mask.s6_addr32[1];
1515 			candidate.s6_addr32[2] &= mask.s6_addr32[2];
1516 			candidate.s6_addr32[3] &= mask.s6_addr32[3];
1517 			if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1518 				break;
1519 		}
1520 		if (ifac == NULL)
1521 			return EADDRNOTAVAIL;
1522 		ia = ifa2ia6(ifac->ifa);
1523 
1524 		if (cmd == SIOCGLIFADDR) {
1525 			struct sockaddr_in6 *s6;
1526 
1527 			/* fill in the if_laddrreq structure */
1528 			bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin6_len);
1529 			s6 = (struct sockaddr_in6 *)&iflr->addr;
1530 			if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1531 				s6->sin6_addr.s6_addr16[1] = 0;
1532 				s6->sin6_scope_id =
1533 					in6_addr2scopeid(ifp, &s6->sin6_addr);
1534 			}
1535 			if (ifp->if_flags & IFF_POINTOPOINT) {
1536 				bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
1537 					ia->ia_dstaddr.sin6_len);
1538 				s6 = (struct sockaddr_in6 *)&iflr->dstaddr;
1539 				if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1540 					s6->sin6_addr.s6_addr16[1] = 0;
1541 					s6->sin6_scope_id =
1542 						in6_addr2scopeid(ifp,
1543 								 &s6->sin6_addr);
1544 				}
1545 			} else
1546 				bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
1547 
1548 			iflr->prefixlen =
1549 				in6_mask2len(&ia->ia_prefixmask.sin6_addr,
1550 					     NULL);
1551 
1552 			iflr->flags = ia->ia6_flags;	/* XXX */
1553 
1554 			return 0;
1555 		} else {
1556 			struct in6_aliasreq ifra;
1557 
1558 			/* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1559 			bzero(&ifra, sizeof(ifra));
1560 			bcopy(iflr->iflr_name, ifra.ifra_name,
1561 			      sizeof(ifra.ifra_name));
1562 
1563 			bcopy(&ia->ia_addr, &ifra.ifra_addr,
1564 			      ia->ia_addr.sin6_len);
1565 			if (ifp->if_flags & IFF_POINTOPOINT)
1566 				bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
1567 				      ia->ia_dstaddr.sin6_len);
1568 			else
1569 				bzero(&ifra.ifra_dstaddr,
1570 				      sizeof(ifra.ifra_dstaddr));
1571 			bcopy(&ia->ia_prefixmask, &ifra.ifra_dstaddr,
1572 			      ia->ia_prefixmask.sin6_len);
1573 
1574 			ifra.ifra_flags = ia->ia6_flags;
1575 			return in6_control(so, SIOCDIFADDR_IN6, (caddr_t)&ifra,
1576 				ifp, td);
1577 		}
1578 	    }
1579 	}
1580 
1581 	return EOPNOTSUPP;	/* just for safety */
1582 }
1583 
1584 /*
1585  * Initialize an interface's intetnet6 address
1586  * and routing table entry.
1587  */
1588 static int
1589 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia, struct sockaddr_in6 *sin6,
1590 	   int newhost)
1591 {
1592 	int	error = 0, plen, ifacount = 0;
1593 	struct ifaddr_container *ifac;
1594 
1595 	/*
1596 	 * Give the interface a chance to initialize
1597 	 * if this is its first address,
1598 	 * and to validate the address if necessary.
1599 	 */
1600 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1601 		if (ifac->ifa->ifa_addr == NULL)
1602 			continue;	/* just for safety */
1603 		if (ifac->ifa->ifa_addr->sa_family != AF_INET6)
1604 			continue;
1605 		ifacount++;
1606 	}
1607 
1608 	ifnet_serialize_all(ifp);
1609 
1610 	ia->ia_addr = *sin6;
1611 
1612 	if (ifacount <= 1 && ifp->if_ioctl &&
1613 	    (error = ifp->if_ioctl(ifp, SIOCSIFADDR, (caddr_t)ia, NULL))) {
1614 		ifnet_deserialize_all(ifp);
1615 		return (error);
1616 	}
1617 
1618 	ifnet_deserialize_all(ifp);
1619 
1620 	ia->ia_ifa.ifa_metric = ifp->if_metric;
1621 
1622 	/* we could do in(6)_socktrim here, but just omit it at this moment. */
1623 
1624 	/*
1625 	 * Special case:
1626 	 * If the destination address is specified for a point-to-point
1627 	 * interface, install a route to the destination as an interface
1628 	 * direct route.
1629 	 */
1630 	plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1631 	if (plen == 128 && ia->ia_dstaddr.sin6_family == AF_INET6) {
1632 		if ((error = rtinit(&(ia->ia_ifa), (int)RTM_ADD,
1633 				    RTF_UP | RTF_HOST)) != 0)
1634 			return (error);
1635 		ia->ia_flags |= IFA_ROUTE;
1636 	}
1637 	if (plen < 128) {
1638 		/*
1639 		 * The RTF_CLONING flag is necessary for in6_is_ifloop_auto().
1640 		 */
1641 		ia->ia_ifa.ifa_flags |= RTF_CLONING;
1642 	}
1643 
1644 	/* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1645 	if (newhost) {
1646 		/* set the rtrequest function to create llinfo */
1647 		ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1648 		in6_ifaddloop(&(ia->ia_ifa));
1649 	}
1650 
1651 	return (error);
1652 }
1653 
1654 struct in6_multi_mship *
1655 in6_joingroup(struct ifnet *ifp, struct in6_addr *addr, int *errorp)
1656 {
1657        struct in6_multi_mship *imm;
1658 
1659        imm = kmalloc(sizeof(*imm), M_IPMADDR, M_NOWAIT);
1660        if (!imm) {
1661                *errorp = ENOBUFS;
1662                return NULL;
1663        }
1664        imm->i6mm_maddr = in6_addmulti(addr, ifp, errorp);
1665        if (!imm->i6mm_maddr) {
1666                /* *errorp is alrady set */
1667                kfree(imm, M_IPMADDR);
1668                return NULL;
1669        }
1670        return imm;
1671 }
1672 
1673 int
1674 in6_leavegroup(struct in6_multi_mship *imm)
1675 {
1676 
1677        if (imm->i6mm_maddr)
1678                in6_delmulti(imm->i6mm_maddr);
1679        kfree(imm,  M_IPMADDR);
1680        return 0;
1681 }
1682 
1683 /*
1684  * Add an address to the list of IP6 multicast addresses for a
1685  * given interface.
1686  */
1687 struct	in6_multi *
1688 in6_addmulti(struct in6_addr *maddr6, struct ifnet *ifp, int *errorp)
1689 {
1690 	struct	in6_multi *in6m;
1691 	struct sockaddr_in6 sin6;
1692 	struct ifmultiaddr *ifma;
1693 
1694 	*errorp = 0;
1695 
1696 	crit_enter();
1697 
1698 	/*
1699 	 * Call generic routine to add membership or increment
1700 	 * refcount.  It wants addresses in the form of a sockaddr,
1701 	 * so we build one here (being careful to zero the unused bytes).
1702 	 */
1703 	bzero(&sin6, sizeof sin6);
1704 	sin6.sin6_family = AF_INET6;
1705 	sin6.sin6_len = sizeof sin6;
1706 	sin6.sin6_addr = *maddr6;
1707 	*errorp = if_addmulti(ifp, (struct sockaddr *)&sin6, &ifma);
1708 	if (*errorp) {
1709 		crit_exit();
1710 		return 0;
1711 	}
1712 
1713 	/*
1714 	 * If ifma->ifma_protospec is null, then if_addmulti() created
1715 	 * a new record.  Otherwise, we are done.
1716 	 */
1717 	if (ifma->ifma_protospec != NULL) {
1718 		crit_exit();
1719 		return ifma->ifma_protospec;
1720 	}
1721 
1722 	/* XXX - if_addmulti uses M_WAITOK.  Can this really be called
1723 	   at interrupt time?  If so, need to fix if_addmulti. XXX */
1724 	in6m = (struct in6_multi *)kmalloc(sizeof(*in6m), M_IPMADDR, M_NOWAIT);
1725 	if (in6m == NULL) {
1726 		crit_exit();
1727 		return (NULL);
1728 	}
1729 
1730 	bzero(in6m, sizeof *in6m);
1731 	in6m->in6m_addr = *maddr6;
1732 	in6m->in6m_ifp = ifp;
1733 	in6m->in6m_ifma = ifma;
1734 	ifma->ifma_protospec = in6m;
1735 	LIST_INSERT_HEAD(&in6_multihead, in6m, in6m_entry);
1736 
1737 	/*
1738 	 * Let MLD6 know that we have joined a new IP6 multicast
1739 	 * group.
1740 	 */
1741 	mld6_start_listening(in6m);
1742 	crit_exit();
1743 	return (in6m);
1744 }
1745 
1746 /*
1747  * Delete a multicast address record.
1748  */
1749 void
1750 in6_delmulti(struct in6_multi *in6m)
1751 {
1752 	struct ifmultiaddr *ifma = in6m->in6m_ifma;
1753 
1754 	crit_enter();
1755 
1756 	if (ifma->ifma_refcount == 1) {
1757 		/*
1758 		 * No remaining claims to this record; let MLD6 know
1759 		 * that we are leaving the multicast group.
1760 		 */
1761 		mld6_stop_listening(in6m);
1762 		ifma->ifma_protospec = NULL;
1763 		LIST_REMOVE(in6m, in6m_entry);
1764 		kfree(in6m, M_IPMADDR);
1765 	}
1766 	/* XXX - should be separate API for when we have an ifma? */
1767 	if_delmulti(ifma->ifma_ifp, ifma->ifma_addr);
1768 	crit_exit();
1769 }
1770 
1771 /*
1772  * Find an IPv6 interface link-local address specific to an interface.
1773  */
1774 struct in6_ifaddr *
1775 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
1776 {
1777 	struct ifaddr_container *ifac;
1778 
1779 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1780 		struct ifaddr *ifa = ifac->ifa;
1781 
1782 		if (ifa->ifa_addr == NULL)
1783 			continue;	/* just for safety */
1784 		if (ifa->ifa_addr->sa_family != AF_INET6)
1785 			continue;
1786 		if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1787 			if ((((struct in6_ifaddr *)ifa)->ia6_flags &
1788 			     ignoreflags) != 0)
1789 				continue;
1790 			break;
1791 		}
1792 	}
1793 	if (ifac != NULL)
1794 		return ((struct in6_ifaddr *)(ifac->ifa));
1795 	else
1796 		return (NULL);
1797 }
1798 
1799 
1800 /*
1801  * find the internet address corresponding to a given interface and address.
1802  */
1803 struct in6_ifaddr *
1804 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
1805 {
1806 	struct ifaddr_container *ifac;
1807 
1808 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1809 		struct ifaddr *ifa = ifac->ifa;
1810 
1811 		if (ifa->ifa_addr == NULL)
1812 			continue;	/* just for safety */
1813 		if (ifa->ifa_addr->sa_family != AF_INET6)
1814 			continue;
1815 		if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
1816 			break;
1817 	}
1818 	if (ifac != NULL)
1819 		return ((struct in6_ifaddr *)(ifac->ifa));
1820 	else
1821 		return (NULL);
1822 }
1823 
1824 /*
1825  * find the internet address on a given interface corresponding to a neighbor's
1826  * address.
1827  */
1828 struct in6_ifaddr *
1829 in6ifa_ifplocaladdr(const struct ifnet *ifp, const struct in6_addr *addr)
1830 {
1831 	struct ifaddr *ifa;
1832 	struct in6_ifaddr *ia;
1833 	struct ifaddr_container *ifac;
1834 
1835 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1836 		ifa = ifac->ifa;
1837 
1838 		if (ifa->ifa_addr == NULL)
1839 			continue;	/* just for safety */
1840 		if (ifa->ifa_addr->sa_family != AF_INET6)
1841 			continue;
1842 		ia = (struct in6_ifaddr *)ifa;
1843 		if (IN6_ARE_MASKED_ADDR_EQUAL(addr,
1844 				&ia->ia_addr.sin6_addr,
1845 				&ia->ia_prefixmask.sin6_addr))
1846 			return ia;
1847 	}
1848 
1849 	return NULL;
1850 }
1851 
1852 /*
1853  * Convert IP6 address to printable (loggable) representation.
1854  */
1855 static char digits[] = "0123456789abcdef";
1856 static int ip6round = 0;
1857 char *
1858 ip6_sprintf(const struct in6_addr *addr)
1859 {
1860 	static char ip6buf[8][48];
1861 	int i;
1862 	char *cp;
1863 	const u_short *a = (const u_short *)addr;
1864 	const u_char *d;
1865 	int dcolon = 0;
1866 
1867 	ip6round = (ip6round + 1) & 7;
1868 	cp = ip6buf[ip6round];
1869 
1870 	for (i = 0; i < 8; i++) {
1871 		if (dcolon == 1) {
1872 			if (*a == 0) {
1873 				if (i == 7)
1874 					*cp++ = ':';
1875 				a++;
1876 				continue;
1877 			} else
1878 				dcolon = 2;
1879 		}
1880 		if (*a == 0) {
1881 			if (dcolon == 0 && *(a + 1) == 0) {
1882 				if (i == 0)
1883 					*cp++ = ':';
1884 				*cp++ = ':';
1885 				dcolon = 1;
1886 			} else {
1887 				*cp++ = '0';
1888 				*cp++ = ':';
1889 			}
1890 			a++;
1891 			continue;
1892 		}
1893 		d = (const u_char *)a;
1894 		*cp++ = digits[*d >> 4];
1895 		*cp++ = digits[*d++ & 0xf];
1896 		*cp++ = digits[*d >> 4];
1897 		*cp++ = digits[*d & 0xf];
1898 		*cp++ = ':';
1899 		a++;
1900 	}
1901 	*--cp = 0;
1902 	return (ip6buf[ip6round]);
1903 }
1904 
1905 int
1906 in6_localaddr(struct in6_addr *in6)
1907 {
1908 	struct in6_ifaddr *ia;
1909 
1910 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
1911 		return 1;
1912 
1913 	for (ia = in6_ifaddr; ia; ia = ia->ia_next)
1914 		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
1915 					      &ia->ia_prefixmask.sin6_addr))
1916 			return 1;
1917 
1918 	return (0);
1919 }
1920 
1921 int
1922 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
1923 {
1924 	struct in6_ifaddr *ia;
1925 
1926 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1927 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
1928 				       &sa6->sin6_addr) &&
1929 		    (ia->ia6_flags & IN6_IFF_DEPRECATED))
1930 			return (1); /* true */
1931 
1932 		/* XXX: do we still have to go thru the rest of the list? */
1933 	}
1934 
1935 	return (0);		/* false */
1936 }
1937 
1938 /*
1939  * return length of part which dst and src are equal
1940  * hard coding...
1941  */
1942 int
1943 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
1944 {
1945 	int match = 0;
1946 	u_char *s = (u_char *)src, *d = (u_char *)dst;
1947 	u_char *lim = s + 16, r;
1948 
1949 	while (s < lim)
1950 		if ((r = (*d++ ^ *s++)) != 0) {
1951 			while (r < 128) {
1952 				match++;
1953 				r <<= 1;
1954 			}
1955 			break;
1956 		} else
1957 			match += 8;
1958 	return match;
1959 }
1960 
1961 /* XXX: to be scope conscious */
1962 int
1963 in6_are_prefix_equal(struct in6_addr *p1, struct in6_addr *p2, int len)
1964 {
1965 	int bytelen, bitlen;
1966 
1967 	/* sanity check */
1968 	if (0 > len || len > 128) {
1969 		log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
1970 		    len);
1971 		return (0);
1972 	}
1973 
1974 	bytelen = len / 8;
1975 	bitlen = len % 8;
1976 
1977 	if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
1978 		return (0);
1979 	if (p1->s6_addr[bytelen] >> (8 - bitlen) !=
1980 	    p2->s6_addr[bytelen] >> (8 - bitlen))
1981 		return (0);
1982 
1983 	return (1);
1984 }
1985 
1986 void
1987 in6_prefixlen2mask(struct in6_addr *maskp, int len)
1988 {
1989 	u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
1990 	int bytelen, bitlen, i;
1991 
1992 	/* sanity check */
1993 	if (0 > len || len > 128) {
1994 		log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
1995 		    len);
1996 		return;
1997 	}
1998 
1999 	bzero(maskp, sizeof(*maskp));
2000 	bytelen = len / 8;
2001 	bitlen = len % 8;
2002 	for (i = 0; i < bytelen; i++)
2003 		maskp->s6_addr[i] = 0xff;
2004 	if (bitlen)
2005 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
2006 }
2007 
2008 /*
2009  * return the best address out of the same scope
2010  */
2011 struct in6_ifaddr *
2012 in6_ifawithscope(struct ifnet *oifp, struct in6_addr *dst)
2013 {
2014 	int dst_scope =	in6_addrscope(dst), src_scope, best_scope = 0;
2015 	int blen = -1;
2016 	struct ifnet *ifp;
2017 	struct in6_ifaddr *ifa_best = NULL;
2018 
2019 	if (oifp == NULL) {
2020 #if 0
2021 		kprintf("in6_ifawithscope: output interface is not specified\n");
2022 #endif
2023 		return (NULL);
2024 	}
2025 
2026 	/*
2027 	 * We search for all addresses on all interfaces from the beginning.
2028 	 * Comparing an interface with the outgoing interface will be done
2029 	 * only at the final stage of tiebreaking.
2030 	 */
2031 	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2032 	{
2033 		struct ifaddr_container *ifac;
2034 
2035 		/*
2036 		 * We can never take an address that breaks the scope zone
2037 		 * of the destination.
2038 		 */
2039 		if (in6_addr2scopeid(ifp, dst) != in6_addr2scopeid(oifp, dst))
2040 			continue;
2041 
2042 		TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2043 			int tlen = -1, dscopecmp, bscopecmp, matchcmp;
2044 			struct ifaddr *ifa = ifac->ifa;
2045 
2046 			if (ifa->ifa_addr->sa_family != AF_INET6)
2047 				continue;
2048 
2049 			src_scope = in6_addrscope(IFA_IN6(ifa));
2050 
2051 			/*
2052 			 * Don't use an address before completing DAD
2053 			 * nor a duplicated address.
2054 			 */
2055 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2056 			    IN6_IFF_NOTREADY)
2057 				continue;
2058 
2059 			/* XXX: is there any case to allow anycasts? */
2060 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2061 			    IN6_IFF_ANYCAST)
2062 				continue;
2063 
2064 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2065 			    IN6_IFF_DETACHED)
2066 				continue;
2067 
2068 			/*
2069 			 * If this is the first address we find,
2070 			 * keep it anyway.
2071 			 */
2072 			if (ifa_best == NULL)
2073 				goto replace;
2074 
2075 			/*
2076 			 * ifa_best is never NULL beyond this line except
2077 			 * within the block labeled "replace".
2078 			 */
2079 
2080 			/*
2081 			 * If ifa_best has a smaller scope than dst and
2082 			 * the current address has a larger one than
2083 			 * (or equal to) dst, always replace ifa_best.
2084 			 * Also, if the current address has a smaller scope
2085 			 * than dst, ignore it unless ifa_best also has a
2086 			 * smaller scope.
2087 			 * Consequently, after the two if-clause below,
2088 			 * the followings must be satisfied:
2089 			 * (scope(src) < scope(dst) &&
2090 			 *  scope(best) < scope(dst))
2091 			 *  OR
2092 			 * (scope(best) >= scope(dst) &&
2093 			 *  scope(src) >= scope(dst))
2094 			 */
2095 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0 &&
2096 			    IN6_ARE_SCOPE_CMP(src_scope, dst_scope) >= 0)
2097 				goto replace; /* (A) */
2098 			if (IN6_ARE_SCOPE_CMP(src_scope, dst_scope) < 0 &&
2099 			    IN6_ARE_SCOPE_CMP(best_scope, dst_scope) >= 0)
2100 				continue; /* (B) */
2101 
2102 			/*
2103 			 * A deprecated address SHOULD NOT be used in new
2104 			 * communications if an alternate (non-deprecated)
2105 			 * address is available and has sufficient scope.
2106 			 * RFC 2462, Section 5.5.4.
2107 			 */
2108 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2109 			    IN6_IFF_DEPRECATED) {
2110 				/*
2111 				 * Ignore any deprecated addresses if
2112 				 * specified by configuration.
2113 				 */
2114 				if (!ip6_use_deprecated)
2115 					continue;
2116 
2117 				/*
2118 				 * If we have already found a non-deprecated
2119 				 * candidate, just ignore deprecated addresses.
2120 				 */
2121 				if (!(ifa_best->ia6_flags & IN6_IFF_DEPRECATED))
2122 					continue;
2123 			}
2124 
2125 			/*
2126 			 * A non-deprecated address is always preferred
2127 			 * to a deprecated one regardless of scopes and
2128 			 * address matching (Note invariants ensured by the
2129 			 * conditions (A) and (B) above.)
2130 			 */
2131 			if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) &&
2132 			    !(((struct in6_ifaddr *)ifa)->ia6_flags &
2133 			     IN6_IFF_DEPRECATED))
2134 				goto replace;
2135 
2136 			/*
2137 			 * When we use temporary addresses described in
2138 			 * RFC 3041, we prefer temporary addresses to
2139 			 * public autoconf addresses.  Again, note the
2140 			 * invariants from (A) and (B).  Also note that we
2141 			 * don't have any preference between static addresses
2142 			 * and autoconf addresses (despite of whether or not
2143 			 * the latter is temporary or public.)
2144 			 */
2145 			if (ip6_use_tempaddr) {
2146 				struct in6_ifaddr *ifat;
2147 
2148 				ifat = (struct in6_ifaddr *)ifa;
2149 				if ((ifa_best->ia6_flags &
2150 				     (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2151 				     == IN6_IFF_AUTOCONF &&
2152 				    (ifat->ia6_flags &
2153 				     (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2154 				     == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY)) {
2155 					goto replace;
2156 				}
2157 				if ((ifa_best->ia6_flags &
2158 				     (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2159 				    == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY) &&
2160 				    (ifat->ia6_flags &
2161 				     (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2162 				     == IN6_IFF_AUTOCONF) {
2163 					continue;
2164 				}
2165 			}
2166 
2167 			/*
2168 			 * At this point, we have two cases:
2169 			 * 1. we are looking at a non-deprecated address,
2170 			 *    and ifa_best is also non-deprecated.
2171 			 * 2. we are looking at a deprecated address,
2172 			 *    and ifa_best is also deprecated.
2173 			 * Also, we do not have to consider a case where
2174 			 * the scope of if_best is larger(smaller) than dst and
2175 			 * the scope of the current address is smaller(larger)
2176 			 * than dst. Such a case has already been covered.
2177 			 * Tiebreaking is done according to the following
2178 			 * items:
2179 			 * - the scope comparison between the address and
2180 			 *   dst (dscopecmp)
2181 			 * - the scope comparison between the address and
2182 			 *   ifa_best (bscopecmp)
2183 			 * - if the address match dst longer than ifa_best
2184 			 *   (matchcmp)
2185 			 * - if the address is on the outgoing I/F (outI/F)
2186 			 *
2187 			 * Roughly speaking, the selection policy is
2188 			 * - the most important item is scope. The same scope
2189 			 *   is best. Then search for a larger scope.
2190 			 *   Smaller scopes are the last resort.
2191 			 * - A deprecated address is chosen only when we have
2192 			 *   no address that has an enough scope, but is
2193 			 *   prefered to any addresses of smaller scopes
2194 			 *   (this must be already done above.)
2195 			 * - addresses on the outgoing I/F are preferred to
2196 			 *   ones on other interfaces if none of above
2197 			 *   tiebreaks.  In the table below, the column "bI"
2198 			 *   means if the best_ifa is on the outgoing
2199 			 *   interface, and the column "sI" means if the ifa
2200 			 *   is on the outgoing interface.
2201 			 * - If there is no other reasons to choose one,
2202 			 *   longest address match against dst is considered.
2203 			 *
2204 			 * The precise decision table is as follows:
2205 			 * dscopecmp bscopecmp    match  bI oI | replace?
2206 			 *       N/A     equal      N/A   Y  N |   No (1)
2207 			 *       N/A     equal      N/A   N  Y |  Yes (2)
2208 			 *       N/A     equal   larger    N/A |  Yes (3)
2209 			 *       N/A     equal  !larger    N/A |   No (4)
2210 			 *    larger    larger      N/A    N/A |   No (5)
2211 			 *    larger   smaller      N/A    N/A |  Yes (6)
2212 			 *   smaller    larger      N/A    N/A |  Yes (7)
2213 			 *   smaller   smaller      N/A    N/A |   No (8)
2214 			 *     equal   smaller      N/A    N/A |  Yes (9)
2215 			 *     equal    larger       (already done at A above)
2216 			 */
2217 			dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
2218 			bscopecmp = IN6_ARE_SCOPE_CMP(src_scope, best_scope);
2219 
2220 			if (bscopecmp == 0) {
2221 				struct ifnet *bifp = ifa_best->ia_ifp;
2222 
2223 				if (bifp == oifp && ifp != oifp) /* (1) */
2224 					continue;
2225 				if (bifp != oifp && ifp == oifp) /* (2) */
2226 					goto replace;
2227 
2228 				/*
2229 				 * Both bifp and ifp are on the outgoing
2230 				 * interface, or both two are on a different
2231 				 * interface from the outgoing I/F.
2232 				 * now we need address matching against dst
2233 				 * for tiebreaking.
2234 				 */
2235 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
2236 				matchcmp = tlen - blen;
2237 				if (matchcmp > 0) /* (3) */
2238 					goto replace;
2239 				continue; /* (4) */
2240 			}
2241 			if (dscopecmp > 0) {
2242 				if (bscopecmp > 0) /* (5) */
2243 					continue;
2244 				goto replace; /* (6) */
2245 			}
2246 			if (dscopecmp < 0) {
2247 				if (bscopecmp > 0) /* (7) */
2248 					goto replace;
2249 				continue; /* (8) */
2250 			}
2251 
2252 			/* now dscopecmp must be 0 */
2253 			if (bscopecmp < 0)
2254 				goto replace; /* (9) */
2255 
2256 replace:
2257 			ifa_best = (struct in6_ifaddr *)ifa;
2258 			blen = tlen >= 0 ? tlen :
2259 				in6_matchlen(IFA_IN6(ifa), dst);
2260 			best_scope = in6_addrscope(&ifa_best->ia_addr.sin6_addr);
2261 		}
2262 	}
2263 
2264 	/* count statistics for future improvements */
2265 	if (ifa_best == NULL)
2266 		ip6stat.ip6s_sources_none++;
2267 	else {
2268 		if (oifp == ifa_best->ia_ifp)
2269 			ip6stat.ip6s_sources_sameif[best_scope]++;
2270 		else
2271 			ip6stat.ip6s_sources_otherif[best_scope]++;
2272 
2273 		if (best_scope == dst_scope)
2274 			ip6stat.ip6s_sources_samescope[best_scope]++;
2275 		else
2276 			ip6stat.ip6s_sources_otherscope[best_scope]++;
2277 
2278 		if (ifa_best->ia6_flags & IN6_IFF_DEPRECATED)
2279 			ip6stat.ip6s_sources_deprecated[best_scope]++;
2280 	}
2281 
2282 	return (ifa_best);
2283 }
2284 
2285 /*
2286  * return the best address out of the same scope. if no address was
2287  * found, return the first valid address from designated IF.
2288  */
2289 struct in6_ifaddr *
2290 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
2291 {
2292 	int dst_scope =	in6_addrscope(dst), blen = -1, tlen;
2293 	struct ifaddr_container *ifac;
2294 	struct in6_ifaddr *besta = NULL;
2295 	struct in6_ifaddr *dep[2];	/* last-resort: deprecated */
2296 
2297 	dep[0] = dep[1] = NULL;
2298 
2299 	/*
2300 	 * We first look for addresses in the same scope.
2301 	 * If there is one, return it.
2302 	 * If two or more, return one which matches the dst longest.
2303 	 * If none, return one of global addresses assigned other ifs.
2304 	 */
2305 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2306 		struct ifaddr *ifa = ifac->ifa;
2307 
2308 		if (ifa->ifa_addr->sa_family != AF_INET6)
2309 			continue;
2310 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2311 			continue; /* XXX: is there any case to allow anycast? */
2312 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2313 			continue; /* don't use this interface */
2314 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2315 			continue;
2316 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2317 			if (ip6_use_deprecated)
2318 				dep[0] = (struct in6_ifaddr *)ifa;
2319 			continue;
2320 		}
2321 
2322 		if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
2323 			/*
2324 			 * call in6_matchlen() as few as possible
2325 			 */
2326 			if (besta) {
2327 				if (blen == -1)
2328 					blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
2329 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
2330 				if (tlen > blen) {
2331 					blen = tlen;
2332 					besta = (struct in6_ifaddr *)ifa;
2333 				}
2334 			} else
2335 				besta = (struct in6_ifaddr *)ifa;
2336 		}
2337 	}
2338 	if (besta)
2339 		return (besta);
2340 
2341 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2342 		struct ifaddr *ifa = ifac->ifa;
2343 
2344 		if (ifa->ifa_addr->sa_family != AF_INET6)
2345 			continue;
2346 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2347 			continue; /* XXX: is there any case to allow anycast? */
2348 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2349 			continue; /* don't use this interface */
2350 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2351 			continue;
2352 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2353 			if (ip6_use_deprecated)
2354 				dep[1] = (struct in6_ifaddr *)ifa;
2355 			continue;
2356 		}
2357 
2358 		return (struct in6_ifaddr *)ifa;
2359 	}
2360 
2361 	/* use the last-resort values, that are, deprecated addresses */
2362 	if (dep[0])
2363 		return dep[0];
2364 	if (dep[1])
2365 		return dep[1];
2366 
2367 	return NULL;
2368 }
2369 
2370 /*
2371  * perform DAD when interface becomes IFF_UP.
2372  */
2373 void
2374 in6_if_up(struct ifnet *ifp)
2375 {
2376 	struct ifaddr_container *ifac;
2377 	struct in6_ifaddr *ia;
2378 	int dad_delay;		/* delay ticks before DAD output */
2379 
2380 	/*
2381 	 * special cases, like 6to4, are handled in in6_ifattach
2382 	 */
2383 	in6_ifattach(ifp, NULL);
2384 
2385 	dad_delay = 0;
2386 	TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2387 		struct ifaddr *ifa = ifac->ifa;
2388 
2389 		if (ifa->ifa_addr->sa_family != AF_INET6)
2390 			continue;
2391 		ia = (struct in6_ifaddr *)ifa;
2392 		if (ia->ia6_flags & IN6_IFF_TENTATIVE)
2393 			nd6_dad_start(ifa, &dad_delay);
2394 	}
2395 }
2396 
2397 int
2398 in6if_do_dad(struct ifnet *ifp)
2399 {
2400 	if (ifp->if_flags & IFF_LOOPBACK)
2401 		return (0);
2402 
2403 	switch (ifp->if_type) {
2404 #ifdef IFT_DUMMY
2405 	case IFT_DUMMY:
2406 #endif
2407 	case IFT_FAITH:
2408 		/*
2409 		 * These interfaces do not have the IFF_LOOPBACK flag,
2410 		 * but loop packets back.  We do not have to do DAD on such
2411 		 * interfaces.  We should even omit it, because loop-backed
2412 		 * NS would confuse the DAD procedure.
2413 		 */
2414 		return (0);
2415 	default:
2416 		/*
2417 		 * Our DAD routine requires the interface up and running.
2418 		 * However, some interfaces can be up before the RUNNING
2419 		 * status.  Additionaly, users may try to assign addresses
2420 		 * before the interface becomes up (or running).
2421 		 * We simply skip DAD in such a case as a work around.
2422 		 * XXX: we should rather mark "tentative" on such addresses,
2423 		 * and do DAD after the interface becomes ready.
2424 		 */
2425 		if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) !=
2426 		    (IFF_UP|IFF_RUNNING))
2427 			return (0);
2428 
2429 		return (1);
2430 	}
2431 }
2432 
2433 /*
2434  * Calculate max IPv6 MTU through all the interfaces and store it
2435  * to in6_maxmtu.
2436  */
2437 void
2438 in6_setmaxmtu(void)
2439 {
2440 	unsigned long maxmtu = 0;
2441 	struct ifnet *ifp;
2442 
2443 	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2444 	{
2445 		/* this function can be called during ifnet initialization */
2446 		if (!ifp->if_afdata[AF_INET6])
2447 			continue;
2448 		if (!(ifp->if_flags & IFF_LOOPBACK) &&
2449 		    ND_IFINFO(ifp)->linkmtu > maxmtu)
2450 			maxmtu =  ND_IFINFO(ifp)->linkmtu;
2451 	}
2452 	if (maxmtu)	/* update only when maxmtu is positive */
2453 		in6_maxmtu = maxmtu;
2454 }
2455 
2456 void *
2457 in6_domifattach(struct ifnet *ifp)
2458 {
2459 	struct in6_ifextra *ext;
2460 
2461 	ext = (struct in6_ifextra *)kmalloc(sizeof(*ext), M_IFADDR, M_WAITOK);
2462 	bzero(ext, sizeof(*ext));
2463 
2464 	ext->in6_ifstat = (struct in6_ifstat *)kmalloc(sizeof(struct in6_ifstat),
2465 		M_IFADDR, M_WAITOK);
2466 	bzero(ext->in6_ifstat, sizeof(*ext->in6_ifstat));
2467 
2468 	ext->icmp6_ifstat =
2469 		(struct icmp6_ifstat *)kmalloc(sizeof(struct icmp6_ifstat),
2470 			M_IFADDR, M_WAITOK);
2471 	bzero(ext->icmp6_ifstat, sizeof(*ext->icmp6_ifstat));
2472 
2473 	ext->nd_ifinfo = nd6_ifattach(ifp);
2474 	ext->scope6_id = scope6_ifattach(ifp);
2475 	return ext;
2476 }
2477 
2478 void
2479 in6_domifdetach(struct ifnet *ifp, void *aux)
2480 {
2481 	struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2482 	scope6_ifdetach(ext->scope6_id);
2483 	nd6_ifdetach(ext->nd_ifinfo);
2484 	kfree(ext->in6_ifstat, M_IFADDR);
2485 	kfree(ext->icmp6_ifstat, M_IFADDR);
2486 	kfree(ext, M_IFADDR);
2487 }
2488 
2489 /*
2490  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2491  * v4 mapped addr or v4 compat addr
2492  */
2493 void
2494 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2495 {
2496 	bzero(sin, sizeof(*sin));
2497 	sin->sin_len = sizeof(struct sockaddr_in);
2498 	sin->sin_family = AF_INET;
2499 	sin->sin_port = sin6->sin6_port;
2500 	sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
2501 }
2502 
2503 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2504 void
2505 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2506 {
2507 	bzero(sin6, sizeof(*sin6));
2508 	sin6->sin6_len = sizeof(struct sockaddr_in6);
2509 	sin6->sin6_family = AF_INET6;
2510 	sin6->sin6_port = sin->sin_port;
2511 	sin6->sin6_addr.s6_addr32[0] = 0;
2512 	sin6->sin6_addr.s6_addr32[1] = 0;
2513 	sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2514 	sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2515 }
2516 
2517 /* Convert sockaddr_in6 into sockaddr_in. */
2518 void
2519 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2520 {
2521 	struct sockaddr_in *sin_p;
2522 	struct sockaddr_in6 sin6;
2523 
2524 	/*
2525 	 * Save original sockaddr_in6 addr and convert it
2526 	 * to sockaddr_in.
2527 	 */
2528 	sin6 = *(struct sockaddr_in6 *)nam;
2529 	sin_p = (struct sockaddr_in *)nam;
2530 	in6_sin6_2_sin(sin_p, &sin6);
2531 }
2532 
2533 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2534 void
2535 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2536 {
2537 	struct sockaddr_in *sin_p;
2538 	struct sockaddr_in6 *sin6_p;
2539 
2540 	sin6_p = kmalloc(sizeof *sin6_p, M_SONAME, M_WAITOK);
2541 	sin_p = (struct sockaddr_in *)*nam;
2542 	in6_sin_2_v4mapsin6(sin_p, sin6_p);
2543 	kfree(*nam, M_SONAME);
2544 	*nam = (struct sockaddr *)sin6_p;
2545 }
2546