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