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