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