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