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