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