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