xref: /freebsd/sys/netinet6/in6.c (revision f11c7f63056671247335df83a3fe80b94c6616ac)
1 /*-
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the project nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	$KAME: in6.c,v 1.259 2002/01/21 11:37:50 keiichi Exp $
30  */
31 
32 /*-
33  * Copyright (c) 1982, 1986, 1991, 1993
34  *	The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)in.c	8.2 (Berkeley) 11/15/93
61  */
62 
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
65 
66 #include "opt_compat.h"
67 #include "opt_inet.h"
68 #include "opt_inet6.h"
69 
70 #include <sys/param.h>
71 #include <sys/errno.h>
72 #include <sys/jail.h>
73 #include <sys/malloc.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/sockio.h>
77 #include <sys/systm.h>
78 #include <sys/priv.h>
79 #include <sys/proc.h>
80 #include <sys/time.h>
81 #include <sys/kernel.h>
82 #include <sys/syslog.h>
83 
84 #include <net/if.h>
85 #include <net/if_var.h>
86 #include <net/if_types.h>
87 #include <net/route.h>
88 #include <net/if_dl.h>
89 #include <net/vnet.h>
90 
91 #include <netinet/in.h>
92 #include <netinet/in_var.h>
93 #include <net/if_llatbl.h>
94 #include <netinet/if_ether.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/in_pcb.h>
98 #include <netinet/ip_carp.h>
99 
100 #include <netinet/ip6.h>
101 #include <netinet6/ip6_var.h>
102 #include <netinet6/nd6.h>
103 #include <netinet6/mld6_var.h>
104 #include <netinet6/ip6_mroute.h>
105 #include <netinet6/in6_ifattach.h>
106 #include <netinet6/scope6_var.h>
107 #include <netinet6/in6_pcb.h>
108 
109 /*
110  * Definitions of some costant IP6 addresses.
111  */
112 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
113 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
114 const struct in6_addr in6addr_nodelocal_allnodes =
115 	IN6ADDR_NODELOCAL_ALLNODES_INIT;
116 const struct in6_addr in6addr_linklocal_allnodes =
117 	IN6ADDR_LINKLOCAL_ALLNODES_INIT;
118 const struct in6_addr in6addr_linklocal_allrouters =
119 	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
120 const struct in6_addr in6addr_linklocal_allv2routers =
121 	IN6ADDR_LINKLOCAL_ALLV2ROUTERS_INIT;
122 
123 const struct in6_addr in6mask0 = IN6MASK0;
124 const struct in6_addr in6mask32 = IN6MASK32;
125 const struct in6_addr in6mask64 = IN6MASK64;
126 const struct in6_addr in6mask96 = IN6MASK96;
127 const struct in6_addr in6mask128 = IN6MASK128;
128 
129 const struct sockaddr_in6 sa6_any =
130 	{ sizeof(sa6_any), AF_INET6, 0, 0, IN6ADDR_ANY_INIT, 0 };
131 
132 static int in6_lifaddr_ioctl __P((struct socket *, u_long, caddr_t,
133 	struct ifnet *, struct thread *));
134 static int in6_ifinit __P((struct ifnet *, struct in6_ifaddr *,
135 	struct sockaddr_in6 *, int));
136 static void in6_unlink_ifa(struct in6_ifaddr *, struct ifnet *);
137 
138 int	(*faithprefix_p)(struct in6_addr *);
139 
140 #define ifa2ia6(ifa)	((struct in6_ifaddr *)(ifa))
141 #define ia62ifa(ia6)	(&((ia6)->ia_ifa))
142 
143 void
144 in6_ifaddloop(struct ifaddr *ifa)
145 {
146 	struct sockaddr_dl gateway;
147 	struct sockaddr_in6 mask, addr;
148 	struct rtentry rt;
149 	struct in6_ifaddr *ia;
150 	struct ifnet *ifp;
151 	struct llentry *ln;
152 
153 	ia = ifa2ia6(ifa);
154 	ifp = ifa->ifa_ifp;
155 	IF_AFDATA_LOCK(ifp);
156 	ifa->ifa_rtrequest = nd6_rtrequest;
157 	ln = lla_lookup(LLTABLE6(ifp), (LLE_CREATE | LLE_IFADDR |
158 	    LLE_EXCLUSIVE), (struct sockaddr *)&ia->ia_addr);
159 	IF_AFDATA_UNLOCK(ifp);
160 	if (ln != NULL) {
161 		ln->la_expire = 0;  /* for IPv6 this means permanent */
162 		ln->ln_state = ND6_LLINFO_REACHABLE;
163 		/*
164 		 * initialize for rtmsg generation
165 		 */
166 		bzero(&gateway, sizeof(gateway));
167 		gateway.sdl_len = sizeof(gateway);
168 		gateway.sdl_family = AF_LINK;
169 		gateway.sdl_nlen = 0;
170 		gateway.sdl_alen = 6;
171 		memcpy(gateway.sdl_data, &ln->ll_addr.mac_aligned,
172 		    sizeof(ln->ll_addr));
173 		LLE_WUNLOCK(ln);
174 	}
175 
176 	bzero(&rt, sizeof(rt));
177 	rt.rt_gateway = (struct sockaddr *)&gateway;
178 	memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
179 	memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
180 	rt_mask(&rt) = (struct sockaddr *)&mask;
181 	rt_key(&rt) = (struct sockaddr *)&addr;
182 	rt.rt_flags = RTF_UP | RTF_HOST | RTF_STATIC;
183 	rt_newaddrmsg(RTM_ADD, ifa, 0, &rt);
184 }
185 
186 void
187 in6_ifremloop(struct ifaddr *ifa)
188 {
189 	struct sockaddr_dl gateway;
190 	struct sockaddr_in6 mask, addr;
191 	struct rtentry rt0;
192 	struct in6_ifaddr *ia;
193 	struct ifnet *ifp;
194 
195 	ia = ifa2ia6(ifa);
196 	ifp = ifa->ifa_ifp;
197 	IF_AFDATA_LOCK(ifp);
198 	lla_lookup(LLTABLE6(ifp), (LLE_DELETE | LLE_IFADDR),
199 	    (struct sockaddr *)&ia->ia_addr);
200 	IF_AFDATA_UNLOCK(ifp);
201 
202 	/*
203 	 * initialize for rtmsg generation
204 	 */
205 	bzero(&gateway, sizeof(gateway));
206 	gateway.sdl_len = sizeof(gateway);
207 	gateway.sdl_family = AF_LINK;
208 	gateway.sdl_nlen = 0;
209 	gateway.sdl_alen = ifp->if_addrlen;
210 	bzero(&rt0, sizeof(rt0));
211 	rt0.rt_gateway = (struct sockaddr *)&gateway;
212 	memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
213 	memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
214 	rt_mask(&rt0) = (struct sockaddr *)&mask;
215 	rt_key(&rt0) = (struct sockaddr *)&addr;
216 	rt0.rt_flags = RTF_HOST | RTF_STATIC;
217 	rt_newaddrmsg(RTM_DELETE, ifa, 0, &rt0);
218 }
219 
220 int
221 in6_mask2len(struct in6_addr *mask, u_char *lim0)
222 {
223 	int x = 0, y;
224 	u_char *lim = lim0, *p;
225 
226 	/* ignore the scope_id part */
227 	if (lim0 == NULL || lim0 - (u_char *)mask > sizeof(*mask))
228 		lim = (u_char *)mask + sizeof(*mask);
229 	for (p = (u_char *)mask; p < lim; x++, p++) {
230 		if (*p != 0xff)
231 			break;
232 	}
233 	y = 0;
234 	if (p < lim) {
235 		for (y = 0; y < 8; y++) {
236 			if ((*p & (0x80 >> y)) == 0)
237 				break;
238 		}
239 	}
240 
241 	/*
242 	 * when the limit pointer is given, do a stricter check on the
243 	 * remaining bits.
244 	 */
245 	if (p < lim) {
246 		if (y != 0 && (*p & (0x00ff >> y)) != 0)
247 			return (-1);
248 		for (p = p + 1; p < lim; p++)
249 			if (*p != 0)
250 				return (-1);
251 	}
252 
253 	return x * 8 + y;
254 }
255 
256 #ifdef COMPAT_FREEBSD32
257 struct in6_ndifreq32 {
258         char ifname[IFNAMSIZ];
259         uint32_t ifindex;
260 };
261 #define	SIOCGDEFIFACE32_IN6     _IOWR('i', 86, struct in6_ndifreq32)
262 #endif
263 
264 int
265 in6_control(struct socket *so, u_long cmd, caddr_t data,
266     struct ifnet *ifp, struct thread *td)
267 {
268 	struct	in6_ifreq *ifr = (struct in6_ifreq *)data;
269 	struct	in6_ifaddr *ia = NULL;
270 	struct	in6_aliasreq *ifra = (struct in6_aliasreq *)data;
271 	struct sockaddr_in6 *sa6;
272 	int carp_attached = 0;
273 	int error;
274 	u_long ocmd = cmd;
275 
276 	/*
277 	 * Compat to make pre-10.x ifconfig(8) operable.
278 	 */
279 	if (cmd == OSIOCAIFADDR_IN6)
280 		cmd = SIOCAIFADDR_IN6;
281 
282 	switch (cmd) {
283 	case SIOCGETSGCNT_IN6:
284 	case SIOCGETMIFCNT_IN6:
285 		return (mrt6_ioctl ? mrt6_ioctl(cmd, data) : EOPNOTSUPP);
286 	}
287 
288 	switch(cmd) {
289 	case SIOCAADDRCTL_POLICY:
290 	case SIOCDADDRCTL_POLICY:
291 		if (td != NULL) {
292 			error = priv_check(td, PRIV_NETINET_ADDRCTRL6);
293 			if (error)
294 				return (error);
295 		}
296 		return (in6_src_ioctl(cmd, data));
297 	}
298 
299 	if (ifp == NULL)
300 		return (EOPNOTSUPP);
301 
302 	switch (cmd) {
303 	case SIOCSNDFLUSH_IN6:
304 	case SIOCSPFXFLUSH_IN6:
305 	case SIOCSRTRFLUSH_IN6:
306 	case SIOCSDEFIFACE_IN6:
307 	case SIOCSIFINFO_FLAGS:
308 	case SIOCSIFINFO_IN6:
309 		if (td != NULL) {
310 			error = priv_check(td, PRIV_NETINET_ND6);
311 			if (error)
312 				return (error);
313 		}
314 		/* FALLTHROUGH */
315 	case OSIOCGIFINFO_IN6:
316 	case SIOCGIFINFO_IN6:
317 	case SIOCGDRLST_IN6:
318 	case SIOCGPRLST_IN6:
319 	case SIOCGNBRINFO_IN6:
320 	case SIOCGDEFIFACE_IN6:
321 		return (nd6_ioctl(cmd, data, ifp));
322 
323 #ifdef COMPAT_FREEBSD32
324 	case SIOCGDEFIFACE32_IN6:
325 		{
326 			struct in6_ndifreq ndif;
327 			struct in6_ndifreq32 *ndif32;
328 
329 			error = nd6_ioctl(SIOCGDEFIFACE_IN6, (caddr_t)&ndif,
330 			    ifp);
331 			if (error)
332 				return (error);
333 			ndif32 = (struct in6_ndifreq32 *)data;
334 			ndif32->ifindex = ndif.ifindex;
335 			return (0);
336 		}
337 #endif
338 	}
339 
340 	switch (cmd) {
341 	case SIOCSIFPREFIX_IN6:
342 	case SIOCDIFPREFIX_IN6:
343 	case SIOCAIFPREFIX_IN6:
344 	case SIOCCIFPREFIX_IN6:
345 	case SIOCSGIFPREFIX_IN6:
346 	case SIOCGIFPREFIX_IN6:
347 		log(LOG_NOTICE,
348 		    "prefix ioctls are now invalidated. "
349 		    "please use ifconfig.\n");
350 		return (EOPNOTSUPP);
351 	}
352 
353 	switch (cmd) {
354 	case SIOCSSCOPE6:
355 		if (td != NULL) {
356 			error = priv_check(td, PRIV_NETINET_SCOPE6);
357 			if (error)
358 				return (error);
359 		}
360 		return (scope6_set(ifp,
361 		    (struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
362 	case SIOCGSCOPE6:
363 		return (scope6_get(ifp,
364 		    (struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
365 	case SIOCGSCOPE6DEF:
366 		return (scope6_get_default((struct scope6_id *)
367 		    ifr->ifr_ifru.ifru_scope_id));
368 	}
369 
370 	switch (cmd) {
371 	case SIOCALIFADDR:
372 		if (td != NULL) {
373 			error = priv_check(td, PRIV_NET_ADDIFADDR);
374 			if (error)
375 				return (error);
376 		}
377 		return in6_lifaddr_ioctl(so, cmd, data, ifp, td);
378 
379 	case SIOCDLIFADDR:
380 		if (td != NULL) {
381 			error = priv_check(td, PRIV_NET_DELIFADDR);
382 			if (error)
383 				return (error);
384 		}
385 		/* FALLTHROUGH */
386 	case SIOCGLIFADDR:
387 		return in6_lifaddr_ioctl(so, cmd, data, ifp, td);
388 	}
389 
390 	/*
391 	 * Find address for this interface, if it exists.
392 	 *
393 	 * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
394 	 * only, and used the first interface address as the target of other
395 	 * operations (without checking ifra_addr).  This was because netinet
396 	 * code/API assumed at most 1 interface address per interface.
397 	 * Since IPv6 allows a node to assign multiple addresses
398 	 * on a single interface, we almost always look and check the
399 	 * presence of ifra_addr, and reject invalid ones here.
400 	 * It also decreases duplicated code among SIOC*_IN6 operations.
401 	 */
402 	switch (cmd) {
403 	case SIOCAIFADDR_IN6:
404 	case SIOCSIFPHYADDR_IN6:
405 		sa6 = &ifra->ifra_addr;
406 		break;
407 	case SIOCSIFADDR_IN6:
408 	case SIOCGIFADDR_IN6:
409 	case SIOCSIFDSTADDR_IN6:
410 	case SIOCSIFNETMASK_IN6:
411 	case SIOCGIFDSTADDR_IN6:
412 	case SIOCGIFNETMASK_IN6:
413 	case SIOCDIFADDR_IN6:
414 	case SIOCGIFPSRCADDR_IN6:
415 	case SIOCGIFPDSTADDR_IN6:
416 	case SIOCGIFAFLAG_IN6:
417 	case SIOCSNDFLUSH_IN6:
418 	case SIOCSPFXFLUSH_IN6:
419 	case SIOCSRTRFLUSH_IN6:
420 	case SIOCGIFALIFETIME_IN6:
421 	case SIOCSIFALIFETIME_IN6:
422 	case SIOCGIFSTAT_IN6:
423 	case SIOCGIFSTAT_ICMP6:
424 		sa6 = &ifr->ifr_addr;
425 		break;
426 	default:
427 		sa6 = NULL;
428 		break;
429 	}
430 	if (sa6 && sa6->sin6_family == AF_INET6) {
431 		if (sa6->sin6_scope_id != 0)
432 			error = sa6_embedscope(sa6, 0);
433 		else
434 			error = in6_setscope(&sa6->sin6_addr, ifp, NULL);
435 		if (error != 0)
436 			return (error);
437 		if (td != NULL && (error = prison_check_ip6(td->td_ucred,
438 		    &sa6->sin6_addr)) != 0)
439 			return (error);
440 		ia = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
441 	} else
442 		ia = NULL;
443 
444 	switch (cmd) {
445 	case SIOCSIFADDR_IN6:
446 	case SIOCSIFDSTADDR_IN6:
447 	case SIOCSIFNETMASK_IN6:
448 		/*
449 		 * Since IPv6 allows a node to assign multiple addresses
450 		 * on a single interface, SIOCSIFxxx ioctls are deprecated.
451 		 */
452 		/* we decided to obsolete this command (20000704) */
453 		error = EINVAL;
454 		goto out;
455 
456 	case SIOCDIFADDR_IN6:
457 		/*
458 		 * for IPv4, we look for existing in_ifaddr here to allow
459 		 * "ifconfig if0 delete" to remove the first IPv4 address on
460 		 * the interface.  For IPv6, as the spec allows multiple
461 		 * interface address from the day one, we consider "remove the
462 		 * first one" semantics to be not preferable.
463 		 */
464 		if (ia == NULL) {
465 			error = EADDRNOTAVAIL;
466 			goto out;
467 		}
468 		/* FALLTHROUGH */
469 	case SIOCAIFADDR_IN6:
470 		/*
471 		 * We always require users to specify a valid IPv6 address for
472 		 * the corresponding operation.
473 		 */
474 		if (ifra->ifra_addr.sin6_family != AF_INET6 ||
475 		    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6)) {
476 			error = EAFNOSUPPORT;
477 			goto out;
478 		}
479 
480 		if (td != NULL) {
481 			error = priv_check(td, (cmd == SIOCDIFADDR_IN6) ?
482 			    PRIV_NET_DELIFADDR : PRIV_NET_ADDIFADDR);
483 			if (error)
484 				goto out;
485 		}
486 		break;
487 
488 	case SIOCGIFADDR_IN6:
489 		/* This interface is basically deprecated. use SIOCGIFCONF. */
490 		/* FALLTHROUGH */
491 	case SIOCGIFAFLAG_IN6:
492 	case SIOCGIFNETMASK_IN6:
493 	case SIOCGIFDSTADDR_IN6:
494 	case SIOCGIFALIFETIME_IN6:
495 		/* must think again about its semantics */
496 		if (ia == NULL) {
497 			error = EADDRNOTAVAIL;
498 			goto out;
499 		}
500 		break;
501 
502 	case SIOCSIFALIFETIME_IN6:
503 	    {
504 		struct in6_addrlifetime *lt;
505 
506 		if (td != NULL) {
507 			error = priv_check(td, PRIV_NETINET_ALIFETIME6);
508 			if (error)
509 				goto out;
510 		}
511 		if (ia == NULL) {
512 			error = EADDRNOTAVAIL;
513 			goto out;
514 		}
515 		/* sanity for overflow - beware unsigned */
516 		lt = &ifr->ifr_ifru.ifru_lifetime;
517 		if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME &&
518 		    lt->ia6t_vltime + time_second < time_second) {
519 			error = EINVAL;
520 			goto out;
521 		}
522 		if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME &&
523 		    lt->ia6t_pltime + time_second < time_second) {
524 			error = EINVAL;
525 			goto out;
526 		}
527 		break;
528 	    }
529 	}
530 
531 	switch (cmd) {
532 	case SIOCGIFADDR_IN6:
533 		ifr->ifr_addr = ia->ia_addr;
534 		if ((error = sa6_recoverscope(&ifr->ifr_addr)) != 0)
535 			goto out;
536 		break;
537 
538 	case SIOCGIFDSTADDR_IN6:
539 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
540 			error = EINVAL;
541 			goto out;
542 		}
543 		/*
544 		 * XXX: should we check if ifa_dstaddr is NULL and return
545 		 * an error?
546 		 */
547 		ifr->ifr_dstaddr = ia->ia_dstaddr;
548 		if ((error = sa6_recoverscope(&ifr->ifr_dstaddr)) != 0)
549 			goto out;
550 		break;
551 
552 	case SIOCGIFNETMASK_IN6:
553 		ifr->ifr_addr = ia->ia_prefixmask;
554 		break;
555 
556 	case SIOCGIFAFLAG_IN6:
557 		ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
558 		break;
559 
560 	case SIOCGIFSTAT_IN6:
561 		if (ifp == NULL) {
562 			error = EINVAL;
563 			goto out;
564 		}
565 		bzero(&ifr->ifr_ifru.ifru_stat,
566 		    sizeof(ifr->ifr_ifru.ifru_stat));
567 		ifr->ifr_ifru.ifru_stat =
568 		    *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
569 		break;
570 
571 	case SIOCGIFSTAT_ICMP6:
572 		if (ifp == NULL) {
573 			error = EINVAL;
574 			goto out;
575 		}
576 		bzero(&ifr->ifr_ifru.ifru_icmp6stat,
577 		    sizeof(ifr->ifr_ifru.ifru_icmp6stat));
578 		ifr->ifr_ifru.ifru_icmp6stat =
579 		    *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
580 		break;
581 
582 	case SIOCGIFALIFETIME_IN6:
583 		ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
584 		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
585 			time_t maxexpire;
586 			struct in6_addrlifetime *retlt =
587 			    &ifr->ifr_ifru.ifru_lifetime;
588 
589 			/*
590 			 * XXX: adjust expiration time assuming time_t is
591 			 * signed.
592 			 */
593 			maxexpire = (-1) &
594 			    ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
595 			if (ia->ia6_lifetime.ia6t_vltime <
596 			    maxexpire - ia->ia6_updatetime) {
597 				retlt->ia6t_expire = ia->ia6_updatetime +
598 				    ia->ia6_lifetime.ia6t_vltime;
599 			} else
600 				retlt->ia6t_expire = maxexpire;
601 		}
602 		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
603 			time_t maxexpire;
604 			struct in6_addrlifetime *retlt =
605 			    &ifr->ifr_ifru.ifru_lifetime;
606 
607 			/*
608 			 * XXX: adjust expiration time assuming time_t is
609 			 * signed.
610 			 */
611 			maxexpire = (-1) &
612 			    ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
613 			if (ia->ia6_lifetime.ia6t_pltime <
614 			    maxexpire - ia->ia6_updatetime) {
615 				retlt->ia6t_preferred = ia->ia6_updatetime +
616 				    ia->ia6_lifetime.ia6t_pltime;
617 			} else
618 				retlt->ia6t_preferred = maxexpire;
619 		}
620 		break;
621 
622 	case SIOCSIFALIFETIME_IN6:
623 		ia->ia6_lifetime = ifr->ifr_ifru.ifru_lifetime;
624 		/* for sanity */
625 		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
626 			ia->ia6_lifetime.ia6t_expire =
627 				time_second + ia->ia6_lifetime.ia6t_vltime;
628 		} else
629 			ia->ia6_lifetime.ia6t_expire = 0;
630 		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
631 			ia->ia6_lifetime.ia6t_preferred =
632 				time_second + ia->ia6_lifetime.ia6t_pltime;
633 		} else
634 			ia->ia6_lifetime.ia6t_preferred = 0;
635 		break;
636 
637 	case SIOCAIFADDR_IN6:
638 	{
639 		int i;
640 		struct nd_prefixctl pr0;
641 		struct nd_prefix *pr;
642 
643 		/*
644 		 * first, make or update the interface address structure,
645 		 * and link it to the list.
646 		 */
647 		if ((error = in6_update_ifa(ifp, ifra, ia, 0)) != 0)
648 			goto out;
649 		if (ia != NULL)
650 			ifa_free(&ia->ia_ifa);
651 		if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
652 		    == NULL) {
653 			/*
654 			 * this can happen when the user specify the 0 valid
655 			 * lifetime.
656 			 */
657 			break;
658 		}
659 
660 		if (cmd == ocmd && ifra->ifra_vhid > 0) {
661 			if (carp_attach_p != NULL)
662 				error = (*carp_attach_p)(&ia->ia_ifa,
663 				    ifra->ifra_vhid);
664 			else
665 				error = EPROTONOSUPPORT;
666 			if (error)
667 				goto out;
668 			else
669 				carp_attached = 1;
670 		}
671 
672 		/*
673 		 * then, make the prefix on-link on the interface.
674 		 * XXX: we'd rather create the prefix before the address, but
675 		 * we need at least one address to install the corresponding
676 		 * interface route, so we configure the address first.
677 		 */
678 
679 		/*
680 		 * convert mask to prefix length (prefixmask has already
681 		 * been validated in in6_update_ifa().
682 		 */
683 		bzero(&pr0, sizeof(pr0));
684 		pr0.ndpr_ifp = ifp;
685 		pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
686 		    NULL);
687 		if (pr0.ndpr_plen == 128) {
688 			break;	/* we don't need to install a host route. */
689 		}
690 		pr0.ndpr_prefix = ifra->ifra_addr;
691 		/* apply the mask for safety. */
692 		for (i = 0; i < 4; i++) {
693 			pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
694 			    ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
695 		}
696 		/*
697 		 * XXX: since we don't have an API to set prefix (not address)
698 		 * lifetimes, we just use the same lifetimes as addresses.
699 		 * The (temporarily) installed lifetimes can be overridden by
700 		 * later advertised RAs (when accept_rtadv is non 0), which is
701 		 * an intended behavior.
702 		 */
703 		pr0.ndpr_raf_onlink = 1; /* should be configurable? */
704 		pr0.ndpr_raf_auto =
705 		    ((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
706 		pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
707 		pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
708 
709 		/* add the prefix if not yet. */
710 		if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
711 			/*
712 			 * nd6_prelist_add will install the corresponding
713 			 * interface route.
714 			 */
715 			if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0) {
716 				if (carp_attached)
717 					(*carp_detach_p)(&ia->ia_ifa);
718 				goto out;
719 			}
720 			if (pr == NULL) {
721 				if (carp_attached)
722 					(*carp_detach_p)(&ia->ia_ifa);
723 				log(LOG_ERR, "nd6_prelist_add succeeded but "
724 				    "no prefix\n");
725 				error = EINVAL;
726 				goto out;
727 			}
728 		}
729 
730 		/* relate the address to the prefix */
731 		if (ia->ia6_ndpr == NULL) {
732 			ia->ia6_ndpr = pr;
733 			pr->ndpr_refcnt++;
734 
735 			/*
736 			 * If this is the first autoconf address from the
737 			 * prefix, create a temporary address as well
738 			 * (when required).
739 			 */
740 			if ((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
741 			    V_ip6_use_tempaddr && pr->ndpr_refcnt == 1) {
742 				int e;
743 				if ((e = in6_tmpifadd(ia, 1, 0)) != 0) {
744 					log(LOG_NOTICE, "in6_control: failed "
745 					    "to create a temporary address, "
746 					    "errno=%d\n", e);
747 				}
748 			}
749 		}
750 
751 		/*
752 		 * this might affect the status of autoconfigured addresses,
753 		 * that is, this address might make other addresses detached.
754 		 */
755 		pfxlist_onlink_check();
756 		if (error == 0 && ia) {
757 			if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) {
758 				/*
759 				 * Try to clear the flag when a new
760 				 * IPv6 address is added onto an
761 				 * IFDISABLED interface and it
762 				 * succeeds.
763 				 */
764 				struct in6_ndireq nd;
765 
766 				memset(&nd, 0, sizeof(nd));
767 				nd.ndi.flags = ND_IFINFO(ifp)->flags;
768 				nd.ndi.flags &= ~ND6_IFF_IFDISABLED;
769 				if (nd6_ioctl(SIOCSIFINFO_FLAGS,
770 				    (caddr_t)&nd, ifp) < 0)
771 					log(LOG_NOTICE, "SIOCAIFADDR_IN6: "
772 					    "SIOCSIFINFO_FLAGS for -ifdisabled "
773 					    "failed.");
774 				/*
775 				 * Ignore failure of clearing the flag
776 				 * intentionally.  The failure means
777 				 * address duplication was detected.
778 				 */
779 			}
780 			EVENTHANDLER_INVOKE(ifaddr_event, ifp);
781 		}
782 		break;
783 	}
784 
785 	case SIOCDIFADDR_IN6:
786 	{
787 		struct nd_prefix *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 worry 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 		 * Note that in6_purgeaddr() will decrement ndpr_refcnt.
798 		 */
799 		pr = ia->ia6_ndpr;
800 		in6_purgeaddr(&ia->ia_ifa);
801 		if (pr && pr->ndpr_refcnt == 0)
802 			prelist_remove(pr);
803 		EVENTHANDLER_INVOKE(ifaddr_event, ifp);
804 		break;
805 	}
806 
807 	default:
808 		if (ifp == NULL || ifp->if_ioctl == 0) {
809 			error = EOPNOTSUPP;
810 			goto out;
811 		}
812 		error = (*ifp->if_ioctl)(ifp, cmd, data);
813 		goto out;
814 	}
815 
816 	error = 0;
817 out:
818 	if (ia != NULL)
819 		ifa_free(&ia->ia_ifa);
820 	return (error);
821 }
822 
823 /*
824  * Update parameters of an IPv6 interface address.
825  * If necessary, a new entry is created and linked into address chains.
826  * This function is separated from in6_control().
827  * XXX: should this be performed under splnet()?
828  */
829 int
830 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
831     struct in6_ifaddr *ia, int flags)
832 {
833 	int error = 0, hostIsNew = 0, plen = -1;
834 	struct sockaddr_in6 dst6;
835 	struct in6_addrlifetime *lt;
836 	struct in6_multi_mship *imm;
837 	struct in6_multi *in6m_sol;
838 	struct rtentry *rt;
839 	int delay;
840 	char ip6buf[INET6_ADDRSTRLEN];
841 
842 	/* Validate parameters */
843 	if (ifp == NULL || ifra == NULL) /* this maybe redundant */
844 		return (EINVAL);
845 
846 	/*
847 	 * The destination address for a p2p link must have a family
848 	 * of AF_UNSPEC or AF_INET6.
849 	 */
850 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
851 	    ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
852 	    ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
853 		return (EAFNOSUPPORT);
854 	/*
855 	 * validate ifra_prefixmask.  don't check sin6_family, netmask
856 	 * does not carry fields other than sin6_len.
857 	 */
858 	if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
859 		return (EINVAL);
860 	/*
861 	 * Because the IPv6 address architecture is classless, we require
862 	 * users to specify a (non 0) prefix length (mask) for a new address.
863 	 * We also require the prefix (when specified) mask is valid, and thus
864 	 * reject a non-consecutive mask.
865 	 */
866 	if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
867 		return (EINVAL);
868 	if (ifra->ifra_prefixmask.sin6_len != 0) {
869 		plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
870 		    (u_char *)&ifra->ifra_prefixmask +
871 		    ifra->ifra_prefixmask.sin6_len);
872 		if (plen <= 0)
873 			return (EINVAL);
874 	} else {
875 		/*
876 		 * In this case, ia must not be NULL.  We just use its prefix
877 		 * length.
878 		 */
879 		plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
880 	}
881 	/*
882 	 * If the destination address on a p2p interface is specified,
883 	 * and the address is a scoped one, validate/set the scope
884 	 * zone identifier.
885 	 */
886 	dst6 = ifra->ifra_dstaddr;
887 	if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) != 0 &&
888 	    (dst6.sin6_family == AF_INET6)) {
889 		struct in6_addr in6_tmp;
890 		u_int32_t zoneid;
891 
892 		in6_tmp = dst6.sin6_addr;
893 		if (in6_setscope(&in6_tmp, ifp, &zoneid))
894 			return (EINVAL); /* XXX: should be impossible */
895 
896 		if (dst6.sin6_scope_id != 0) {
897 			if (dst6.sin6_scope_id != zoneid)
898 				return (EINVAL);
899 		} else		/* user omit to specify the ID. */
900 			dst6.sin6_scope_id = zoneid;
901 
902 		/* convert into the internal form */
903 		if (sa6_embedscope(&dst6, 0))
904 			return (EINVAL); /* XXX: should be impossible */
905 	}
906 	/*
907 	 * The destination address can be specified only for a p2p or a
908 	 * loopback interface.  If specified, the corresponding prefix length
909 	 * must be 128.
910 	 */
911 	if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
912 		if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) == 0) {
913 			/* XXX: noisy message */
914 			nd6log((LOG_INFO, "in6_update_ifa: a destination can "
915 			    "be specified for a p2p or a loopback IF only\n"));
916 			return (EINVAL);
917 		}
918 		if (plen != 128) {
919 			nd6log((LOG_INFO, "in6_update_ifa: prefixlen should "
920 			    "be 128 when dstaddr is specified\n"));
921 			return (EINVAL);
922 		}
923 	}
924 	/* lifetime consistency check */
925 	lt = &ifra->ifra_lifetime;
926 	if (lt->ia6t_pltime > lt->ia6t_vltime)
927 		return (EINVAL);
928 	if (lt->ia6t_vltime == 0) {
929 		/*
930 		 * the following log might be noisy, but this is a typical
931 		 * configuration mistake or a tool's bug.
932 		 */
933 		nd6log((LOG_INFO,
934 		    "in6_update_ifa: valid lifetime is 0 for %s\n",
935 		    ip6_sprintf(ip6buf, &ifra->ifra_addr.sin6_addr)));
936 
937 		if (ia == NULL)
938 			return (0); /* there's nothing to do */
939 	}
940 
941 	/*
942 	 * If this is a new address, allocate a new ifaddr and link it
943 	 * into chains.
944 	 */
945 	if (ia == NULL) {
946 		hostIsNew = 1;
947 		/*
948 		 * When in6_update_ifa() is called in a process of a received
949 		 * RA, it is called under an interrupt context.  So, we should
950 		 * call malloc with M_NOWAIT.
951 		 */
952 		ia = (struct in6_ifaddr *) malloc(sizeof(*ia), M_IFADDR,
953 		    M_NOWAIT);
954 		if (ia == NULL)
955 			return (ENOBUFS);
956 		bzero((caddr_t)ia, sizeof(*ia));
957 		ifa_init(&ia->ia_ifa);
958 		LIST_INIT(&ia->ia6_memberships);
959 		/* Initialize the address and masks, and put time stamp */
960 		ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
961 		ia->ia_addr.sin6_family = AF_INET6;
962 		ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
963 		ia->ia6_createtime = time_second;
964 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
965 			/*
966 			 * XXX: some functions expect that ifa_dstaddr is not
967 			 * NULL for p2p interfaces.
968 			 */
969 			ia->ia_ifa.ifa_dstaddr =
970 			    (struct sockaddr *)&ia->ia_dstaddr;
971 		} else {
972 			ia->ia_ifa.ifa_dstaddr = NULL;
973 		}
974 		ia->ia_ifa.ifa_netmask = (struct sockaddr *)&ia->ia_prefixmask;
975 		ia->ia_ifp = ifp;
976 		ifa_ref(&ia->ia_ifa);			/* if_addrhead */
977 		IF_ADDR_WLOCK(ifp);
978 		TAILQ_INSERT_TAIL(&ifp->if_addrhead, &ia->ia_ifa, ifa_link);
979 		IF_ADDR_WUNLOCK(ifp);
980 
981 		ifa_ref(&ia->ia_ifa);			/* in6_ifaddrhead */
982 		IN6_IFADDR_WLOCK();
983 		TAILQ_INSERT_TAIL(&V_in6_ifaddrhead, ia, ia_link);
984 		IN6_IFADDR_WUNLOCK();
985 	}
986 
987 	/* update timestamp */
988 	ia->ia6_updatetime = time_second;
989 
990 	/* set prefix mask */
991 	if (ifra->ifra_prefixmask.sin6_len) {
992 		/*
993 		 * We prohibit changing the prefix length of an existing
994 		 * address, because
995 		 * + such an operation should be rare in IPv6, and
996 		 * + the operation would confuse prefix management.
997 		 */
998 		if (ia->ia_prefixmask.sin6_len &&
999 		    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
1000 			nd6log((LOG_INFO, "in6_update_ifa: the prefix length of an"
1001 			    " existing (%s) address should not be changed\n",
1002 			    ip6_sprintf(ip6buf, &ia->ia_addr.sin6_addr)));
1003 			error = EINVAL;
1004 			goto unlink;
1005 		}
1006 		ia->ia_prefixmask = ifra->ifra_prefixmask;
1007 	}
1008 
1009 	/*
1010 	 * If a new destination address is specified, scrub the old one and
1011 	 * install the new destination.  Note that the interface must be
1012 	 * p2p or loopback (see the check above.)
1013 	 */
1014 	if (dst6.sin6_family == AF_INET6 &&
1015 	    !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr, &ia->ia_dstaddr.sin6_addr)) {
1016 		int e;
1017 
1018 		if ((ia->ia_flags & IFA_ROUTE) != 0 &&
1019 		    (e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST)) != 0) {
1020 			nd6log((LOG_ERR, "in6_update_ifa: failed to remove "
1021 			    "a route to the old destination: %s\n",
1022 			    ip6_sprintf(ip6buf, &ia->ia_addr.sin6_addr)));
1023 			/* proceed anyway... */
1024 		} else
1025 			ia->ia_flags &= ~IFA_ROUTE;
1026 		ia->ia_dstaddr = dst6;
1027 	}
1028 
1029 	/*
1030 	 * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
1031 	 * to see if the address is deprecated or invalidated, but initialize
1032 	 * these members for applications.
1033 	 */
1034 	ia->ia6_lifetime = ifra->ifra_lifetime;
1035 	if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1036 		ia->ia6_lifetime.ia6t_expire =
1037 		    time_second + ia->ia6_lifetime.ia6t_vltime;
1038 	} else
1039 		ia->ia6_lifetime.ia6t_expire = 0;
1040 	if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1041 		ia->ia6_lifetime.ia6t_preferred =
1042 		    time_second + ia->ia6_lifetime.ia6t_pltime;
1043 	} else
1044 		ia->ia6_lifetime.ia6t_preferred = 0;
1045 
1046 	/* reset the interface and routing table appropriately. */
1047 	if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
1048 		goto unlink;
1049 
1050 	/*
1051 	 * configure address flags.
1052 	 */
1053 	ia->ia6_flags = ifra->ifra_flags;
1054 	/*
1055 	 * backward compatibility - if IN6_IFF_DEPRECATED is set from the
1056 	 * userland, make it deprecated.
1057 	 */
1058 	if ((ifra->ifra_flags & IN6_IFF_DEPRECATED) != 0) {
1059 		ia->ia6_lifetime.ia6t_pltime = 0;
1060 		ia->ia6_lifetime.ia6t_preferred = time_second;
1061 	}
1062 	/*
1063 	 * Make the address tentative before joining multicast addresses,
1064 	 * so that corresponding MLD responses would not have a tentative
1065 	 * source address.
1066 	 */
1067 	ia->ia6_flags &= ~IN6_IFF_DUPLICATED;	/* safety */
1068 	if (hostIsNew && in6if_do_dad(ifp))
1069 		ia->ia6_flags |= IN6_IFF_TENTATIVE;
1070 
1071 	/* DAD should be performed after ND6_IFF_IFDISABLED is cleared. */
1072 	if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)
1073 		ia->ia6_flags |= IN6_IFF_TENTATIVE;
1074 
1075 	/*
1076 	 * We are done if we have simply modified an existing address.
1077 	 */
1078 	if (!hostIsNew)
1079 		return (error);
1080 
1081 	/*
1082 	 * Beyond this point, we should call in6_purgeaddr upon an error,
1083 	 * not just go to unlink.
1084 	 */
1085 
1086 	/* Join necessary multicast groups */
1087 	in6m_sol = NULL;
1088 	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
1089 		struct sockaddr_in6 mltaddr, mltmask;
1090 		struct in6_addr llsol;
1091 
1092 		/* join solicited multicast addr for new host id */
1093 		bzero(&llsol, sizeof(struct in6_addr));
1094 		llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
1095 		llsol.s6_addr32[1] = 0;
1096 		llsol.s6_addr32[2] = htonl(1);
1097 		llsol.s6_addr32[3] = ifra->ifra_addr.sin6_addr.s6_addr32[3];
1098 		llsol.s6_addr8[12] = 0xff;
1099 		if ((error = in6_setscope(&llsol, ifp, NULL)) != 0) {
1100 			/* XXX: should not happen */
1101 			log(LOG_ERR, "in6_update_ifa: "
1102 			    "in6_setscope failed\n");
1103 			goto cleanup;
1104 		}
1105 		delay = 0;
1106 		if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1107 			/*
1108 			 * We need a random delay for DAD on the address
1109 			 * being configured.  It also means delaying
1110 			 * transmission of the corresponding MLD report to
1111 			 * avoid report collision.
1112 			 * [RFC 4861, Section 6.3.7]
1113 			 */
1114 			delay = arc4random() %
1115 			    (MAX_RTR_SOLICITATION_DELAY * hz);
1116 		}
1117 		imm = in6_joingroup(ifp, &llsol, &error, delay);
1118 		if (imm == NULL) {
1119 			nd6log((LOG_WARNING,
1120 			    "in6_update_ifa: addmulti failed for "
1121 			    "%s on %s (errno=%d)\n",
1122 			    ip6_sprintf(ip6buf, &llsol), if_name(ifp),
1123 			    error));
1124 			goto cleanup;
1125 		}
1126 		LIST_INSERT_HEAD(&ia->ia6_memberships,
1127 		    imm, i6mm_chain);
1128 		in6m_sol = imm->i6mm_maddr;
1129 
1130 		bzero(&mltmask, sizeof(mltmask));
1131 		mltmask.sin6_len = sizeof(struct sockaddr_in6);
1132 		mltmask.sin6_family = AF_INET6;
1133 		mltmask.sin6_addr = in6mask32;
1134 #define	MLTMASK_LEN  4	/* mltmask's masklen (=32bit=4octet) */
1135 
1136 		/*
1137 		 * join link-local all-nodes address
1138 		 */
1139 		bzero(&mltaddr, sizeof(mltaddr));
1140 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1141 		mltaddr.sin6_family = AF_INET6;
1142 		mltaddr.sin6_addr = in6addr_linklocal_allnodes;
1143 		if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) !=
1144 		    0)
1145 			goto cleanup; /* XXX: should not fail */
1146 
1147 		/*
1148 		 * XXX: do we really need this automatic routes?
1149 		 * We should probably reconsider this stuff.  Most applications
1150 		 * actually do not need the routes, since they usually specify
1151 		 * the outgoing interface.
1152 		 */
1153 		rt = rtalloc1((struct sockaddr *)&mltaddr, 0, 0UL);
1154 		if (rt) {
1155 			/* XXX: only works in !SCOPEDROUTING case. */
1156 			if (memcmp(&mltaddr.sin6_addr,
1157 			    &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
1158 			    MLTMASK_LEN)) {
1159 				RTFREE_LOCKED(rt);
1160 				rt = NULL;
1161 			}
1162 		}
1163 		if (!rt) {
1164 			error = rtrequest(RTM_ADD, (struct sockaddr *)&mltaddr,
1165 			    (struct sockaddr *)&ia->ia_addr,
1166 			    (struct sockaddr *)&mltmask, RTF_UP,
1167 			    (struct rtentry **)0);
1168 			if (error)
1169 				goto cleanup;
1170 		} else {
1171 			RTFREE_LOCKED(rt);
1172 		}
1173 
1174 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
1175 		if (!imm) {
1176 			nd6log((LOG_WARNING,
1177 			    "in6_update_ifa: addmulti failed for "
1178 			    "%s on %s (errno=%d)\n",
1179 			    ip6_sprintf(ip6buf, &mltaddr.sin6_addr),
1180 			    if_name(ifp), error));
1181 			goto cleanup;
1182 		}
1183 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
1184 
1185 		/*
1186 		 * join node information group address
1187 		 */
1188 		delay = 0;
1189 		if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1190 			/*
1191 			 * The spec doesn't say anything about delay for this
1192 			 * group, but the same logic should apply.
1193 			 */
1194 			delay = arc4random() %
1195 			    (MAX_RTR_SOLICITATION_DELAY * hz);
1196 		}
1197 		if (in6_nigroup(ifp, NULL, -1, &mltaddr.sin6_addr) == 0) {
1198 			imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error,
1199 			    delay); /* XXX jinmei */
1200 			if (!imm) {
1201 				nd6log((LOG_WARNING, "in6_update_ifa: "
1202 				    "addmulti failed for %s on %s "
1203 				    "(errno=%d)\n",
1204 				    ip6_sprintf(ip6buf, &mltaddr.sin6_addr),
1205 				    if_name(ifp), error));
1206 				/* XXX not very fatal, go on... */
1207 			} else {
1208 				LIST_INSERT_HEAD(&ia->ia6_memberships,
1209 				    imm, i6mm_chain);
1210 			}
1211 		}
1212 
1213 		/*
1214 		 * join interface-local all-nodes address.
1215 		 * (ff01::1%ifN, and ff01::%ifN/32)
1216 		 */
1217 		mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
1218 		if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL))
1219 		    != 0)
1220 			goto cleanup; /* XXX: should not fail */
1221 		/* XXX: again, do we really need the route? */
1222 		rt = rtalloc1((struct sockaddr *)&mltaddr, 0, 0UL);
1223 		if (rt) {
1224 			if (memcmp(&mltaddr.sin6_addr,
1225 			    &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
1226 			    MLTMASK_LEN)) {
1227 				RTFREE_LOCKED(rt);
1228 				rt = NULL;
1229 			}
1230 		}
1231 		if (!rt) {
1232 			error = rtrequest(RTM_ADD, (struct sockaddr *)&mltaddr,
1233 			    (struct sockaddr *)&ia->ia_addr,
1234 			    (struct sockaddr *)&mltmask, RTF_UP,
1235 			    (struct rtentry **)0);
1236 			if (error)
1237 				goto cleanup;
1238 		} else
1239 			RTFREE_LOCKED(rt);
1240 
1241 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
1242 		if (!imm) {
1243 			nd6log((LOG_WARNING, "in6_update_ifa: "
1244 			    "addmulti failed for %s on %s "
1245 			    "(errno=%d)\n",
1246 			    ip6_sprintf(ip6buf, &mltaddr.sin6_addr),
1247 			    if_name(ifp), error));
1248 			goto cleanup;
1249 		}
1250 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
1251 #undef	MLTMASK_LEN
1252 	}
1253 
1254 	/*
1255 	 * Perform DAD, if needed.
1256 	 * XXX It may be of use, if we can administratively
1257 	 * disable DAD.
1258 	 */
1259 	if (in6if_do_dad(ifp) && ((ifra->ifra_flags & IN6_IFF_NODAD) == 0) &&
1260 	    (ia->ia6_flags & IN6_IFF_TENTATIVE))
1261 	{
1262 		int mindelay, maxdelay;
1263 
1264 		delay = 0;
1265 		if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1266 			/*
1267 			 * We need to impose a delay before sending an NS
1268 			 * for DAD.  Check if we also needed a delay for the
1269 			 * corresponding MLD message.  If we did, the delay
1270 			 * should be larger than the MLD delay (this could be
1271 			 * relaxed a bit, but this simple logic is at least
1272 			 * safe).
1273 			 * XXX: Break data hiding guidelines and look at
1274 			 * state for the solicited multicast group.
1275 			 */
1276 			mindelay = 0;
1277 			if (in6m_sol != NULL &&
1278 			    in6m_sol->in6m_state == MLD_REPORTING_MEMBER) {
1279 				mindelay = in6m_sol->in6m_timer;
1280 			}
1281 			maxdelay = MAX_RTR_SOLICITATION_DELAY * hz;
1282 			if (maxdelay - mindelay == 0)
1283 				delay = 0;
1284 			else {
1285 				delay =
1286 				    (arc4random() % (maxdelay - mindelay)) +
1287 				    mindelay;
1288 			}
1289 		}
1290 		nd6_dad_start((struct ifaddr *)ia, delay);
1291 	}
1292 
1293 	KASSERT(hostIsNew, ("in6_update_ifa: !hostIsNew"));
1294 	ifa_free(&ia->ia_ifa);
1295 	return (error);
1296 
1297   unlink:
1298 	/*
1299 	 * XXX: if a change of an existing address failed, keep the entry
1300 	 * anyway.
1301 	 */
1302 	if (hostIsNew) {
1303 		in6_unlink_ifa(ia, ifp);
1304 		ifa_free(&ia->ia_ifa);
1305 	}
1306 	return (error);
1307 
1308   cleanup:
1309 	KASSERT(hostIsNew, ("in6_update_ifa: cleanup: !hostIsNew"));
1310 	ifa_free(&ia->ia_ifa);
1311 	in6_purgeaddr(&ia->ia_ifa);
1312 	return error;
1313 }
1314 
1315 void
1316 in6_purgeaddr(struct ifaddr *ifa)
1317 {
1318 	struct ifnet *ifp = ifa->ifa_ifp;
1319 	struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1320 	struct in6_multi_mship *imm;
1321 	struct sockaddr_in6 mltaddr, mltmask;
1322 	int plen, error;
1323 	struct rtentry *rt;
1324 	struct ifaddr *ifa0;
1325 
1326 	if (ifa->ifa_carp)
1327 		(*carp_detach_p)(ifa);
1328 
1329 	/*
1330 	 * find another IPv6 address as the gateway for the
1331 	 * link-local and node-local all-nodes multicast
1332 	 * address routes
1333 	 */
1334 	IF_ADDR_RLOCK(ifp);
1335 	TAILQ_FOREACH(ifa0, &ifp->if_addrhead, ifa_link) {
1336 		if ((ifa0->ifa_addr->sa_family != AF_INET6) ||
1337 		    memcmp(&satosin6(ifa0->ifa_addr)->sin6_addr,
1338 			   &ia->ia_addr.sin6_addr,
1339 			   sizeof(struct in6_addr)) == 0)
1340 			continue;
1341 		else
1342 			break;
1343 	}
1344 	if (ifa0 != NULL)
1345 		ifa_ref(ifa0);
1346 	IF_ADDR_RUNLOCK(ifp);
1347 
1348 	/*
1349 	 * Remove the loopback route to the interface address.
1350 	 * The check for the current setting of "nd6_useloopback"
1351 	 * is not needed.
1352 	 */
1353 	if (ia->ia_flags & IFA_RTSELF) {
1354 		error = ifa_del_loopback_route((struct ifaddr *)ia,
1355 				       (struct sockaddr *)&ia->ia_addr);
1356 		if (error == 0)
1357 			ia->ia_flags &= ~IFA_RTSELF;
1358 	}
1359 
1360 	/* stop DAD processing */
1361 	nd6_dad_stop(ifa);
1362 
1363 	in6_ifremloop(ifa);
1364 
1365 	/*
1366 	 * leave from multicast groups we have joined for the interface
1367 	 */
1368 	while ((imm = LIST_FIRST(&ia->ia6_memberships)) != NULL) {
1369 		LIST_REMOVE(imm, i6mm_chain);
1370 		in6_leavegroup(imm);
1371 	}
1372 
1373 	/*
1374 	 * remove the link-local all-nodes address
1375 	 */
1376 	bzero(&mltmask, sizeof(mltmask));
1377 	mltmask.sin6_len = sizeof(struct sockaddr_in6);
1378 	mltmask.sin6_family = AF_INET6;
1379 	mltmask.sin6_addr = in6mask32;
1380 
1381 	bzero(&mltaddr, sizeof(mltaddr));
1382 	mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1383 	mltaddr.sin6_family = AF_INET6;
1384 	mltaddr.sin6_addr = in6addr_linklocal_allnodes;
1385 
1386 	if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
1387 		goto cleanup;
1388 
1389 	rt = rtalloc1((struct sockaddr *)&mltaddr, 0, 0UL);
1390 	if (rt != NULL && rt->rt_gateway != NULL &&
1391 	    (memcmp(&satosin6(rt->rt_gateway)->sin6_addr,
1392 		    &ia->ia_addr.sin6_addr,
1393 		    sizeof(ia->ia_addr.sin6_addr)) == 0)) {
1394 		/*
1395 		 * if no more IPv6 address exists on this interface
1396 		 * then remove the multicast address route
1397 		 */
1398 		if (ifa0 == NULL) {
1399 			memcpy(&mltaddr.sin6_addr, &satosin6(rt_key(rt))->sin6_addr,
1400 			       sizeof(mltaddr.sin6_addr));
1401 			RTFREE_LOCKED(rt);
1402 			error = rtrequest(RTM_DELETE, (struct sockaddr *)&mltaddr,
1403 					  (struct sockaddr *)&ia->ia_addr,
1404 					  (struct sockaddr *)&mltmask, RTF_UP,
1405 					  (struct rtentry **)0);
1406 			if (error)
1407 				log(LOG_INFO, "in6_purgeaddr: link-local all-nodes"
1408 				    "multicast address deletion error\n");
1409 		} else {
1410 			/*
1411 			 * replace the gateway of the route
1412 			 */
1413 			struct sockaddr_in6 sa;
1414 
1415 			bzero(&sa, sizeof(sa));
1416 			sa.sin6_len = sizeof(struct sockaddr_in6);
1417 			sa.sin6_family = AF_INET6;
1418 			memcpy(&sa.sin6_addr, &satosin6(ifa0->ifa_addr)->sin6_addr,
1419 			       sizeof(sa.sin6_addr));
1420 			in6_setscope(&sa.sin6_addr, ifa0->ifa_ifp, NULL);
1421 			memcpy(rt->rt_gateway, &sa, sizeof(sa));
1422 			RTFREE_LOCKED(rt);
1423 		}
1424 	} else {
1425 		if (rt != NULL)
1426 			RTFREE_LOCKED(rt);
1427 	}
1428 
1429 	/*
1430 	 * remove the node-local all-nodes address
1431 	 */
1432 	mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
1433 	if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) !=
1434 	    0)
1435 		goto cleanup;
1436 
1437 	rt = rtalloc1((struct sockaddr *)&mltaddr, 0, 0UL);
1438 	if (rt != NULL && rt->rt_gateway != NULL &&
1439 	    (memcmp(&satosin6(rt->rt_gateway)->sin6_addr,
1440 		    &ia->ia_addr.sin6_addr,
1441 		    sizeof(ia->ia_addr.sin6_addr)) == 0)) {
1442 		/*
1443 		 * if no more IPv6 address exists on this interface
1444 		 * then remove the multicast address route
1445 		 */
1446 		if (ifa0 == NULL) {
1447 			memcpy(&mltaddr.sin6_addr, &satosin6(rt_key(rt))->sin6_addr,
1448 			       sizeof(mltaddr.sin6_addr));
1449 
1450 			RTFREE_LOCKED(rt);
1451 			error = rtrequest(RTM_DELETE, (struct sockaddr *)&mltaddr,
1452 					  (struct sockaddr *)&ia->ia_addr,
1453 					  (struct sockaddr *)&mltmask, RTF_UP,
1454 					  (struct rtentry **)0);
1455 
1456 			if (error)
1457 				log(LOG_INFO, "in6_purgeaddr: node-local all-nodes"
1458 				    "multicast address deletion error\n");
1459 		} else {
1460 			/*
1461 			 * replace the gateway of the route
1462 			 */
1463 			struct sockaddr_in6 sa;
1464 
1465 			bzero(&sa, sizeof(sa));
1466 			sa.sin6_len = sizeof(struct sockaddr_in6);
1467 			sa.sin6_family = AF_INET6;
1468 			memcpy(&sa.sin6_addr, &satosin6(ifa0->ifa_addr)->sin6_addr,
1469 			       sizeof(sa.sin6_addr));
1470 			in6_setscope(&sa.sin6_addr, ifa0->ifa_ifp, NULL);
1471 			memcpy(rt->rt_gateway, &sa, sizeof(sa));
1472 			RTFREE_LOCKED(rt);
1473 		}
1474 	} else {
1475 		if (rt != NULL)
1476 			RTFREE_LOCKED(rt);
1477 	}
1478 
1479 cleanup:
1480 	if (ifa0 != NULL)
1481 		ifa_free(ifa0);
1482 
1483 	plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1484 	if ((ia->ia_flags & IFA_ROUTE) && plen == 128) {
1485 		int error;
1486 		struct sockaddr *dstaddr;
1487 
1488 		/*
1489 		 * use the interface address if configuring an
1490 		 * interface address with a /128 prefix len
1491 		 */
1492 		if (ia->ia_dstaddr.sin6_family == AF_INET6)
1493 			dstaddr = (struct sockaddr *)&ia->ia_dstaddr;
1494 		else
1495 			dstaddr = (struct sockaddr *)&ia->ia_addr;
1496 
1497 		error = rtrequest(RTM_DELETE,
1498 		    (struct sockaddr *)dstaddr,
1499 		    (struct sockaddr *)&ia->ia_addr,
1500 		    (struct sockaddr *)&ia->ia_prefixmask,
1501 		    ia->ia_flags | RTF_HOST, NULL);
1502 		if (error != 0)
1503 			return;
1504 		ia->ia_flags &= ~IFA_ROUTE;
1505 	}
1506 
1507 	in6_unlink_ifa(ia, ifp);
1508 }
1509 
1510 static void
1511 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1512 {
1513 	int	s = splnet();
1514 
1515 	IF_ADDR_WLOCK(ifp);
1516 	TAILQ_REMOVE(&ifp->if_addrhead, &ia->ia_ifa, ifa_link);
1517 	IF_ADDR_WUNLOCK(ifp);
1518 	ifa_free(&ia->ia_ifa);			/* if_addrhead */
1519 
1520 	/*
1521 	 * Defer the release of what might be the last reference to the
1522 	 * in6_ifaddr so that it can't be freed before the remainder of the
1523 	 * cleanup.
1524 	 */
1525 	IN6_IFADDR_WLOCK();
1526 	TAILQ_REMOVE(&V_in6_ifaddrhead, ia, ia_link);
1527 	IN6_IFADDR_WUNLOCK();
1528 
1529 	/*
1530 	 * Release the reference to the base prefix.  There should be a
1531 	 * positive reference.
1532 	 */
1533 	if (ia->ia6_ndpr == NULL) {
1534 		nd6log((LOG_NOTICE,
1535 		    "in6_unlink_ifa: autoconf'ed address "
1536 		    "%p has no prefix\n", ia));
1537 	} else {
1538 		ia->ia6_ndpr->ndpr_refcnt--;
1539 		ia->ia6_ndpr = NULL;
1540 	}
1541 
1542 	/*
1543 	 * Also, if the address being removed is autoconf'ed, call
1544 	 * pfxlist_onlink_check() since the release might affect the status of
1545 	 * other (detached) addresses.
1546 	 */
1547 	if ((ia->ia6_flags & IN6_IFF_AUTOCONF)) {
1548 		pfxlist_onlink_check();
1549 	}
1550 	ifa_free(&ia->ia_ifa);			/* in6_ifaddrhead */
1551 	splx(s);
1552 }
1553 
1554 void
1555 in6_purgeif(struct ifnet *ifp)
1556 {
1557 	struct ifaddr *ifa, *nifa;
1558 
1559 	TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, nifa) {
1560 		if (ifa->ifa_addr->sa_family != AF_INET6)
1561 			continue;
1562 		in6_purgeaddr(ifa);
1563 	}
1564 
1565 	in6_ifdetach(ifp);
1566 }
1567 
1568 /*
1569  * SIOC[GAD]LIFADDR.
1570  *	SIOCGLIFADDR: get first address. (?)
1571  *	SIOCGLIFADDR with IFLR_PREFIX:
1572  *		get first address that matches the specified prefix.
1573  *	SIOCALIFADDR: add the specified address.
1574  *	SIOCALIFADDR with IFLR_PREFIX:
1575  *		add the specified prefix, filling hostid part from
1576  *		the first link-local address.  prefixlen must be <= 64.
1577  *	SIOCDLIFADDR: delete the specified address.
1578  *	SIOCDLIFADDR with IFLR_PREFIX:
1579  *		delete the first address that matches the specified prefix.
1580  * return values:
1581  *	EINVAL on invalid parameters
1582  *	EADDRNOTAVAIL on prefix match failed/specified address not found
1583  *	other values may be returned from in6_ioctl()
1584  *
1585  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1586  * this is to accomodate address naming scheme other than RFC2374,
1587  * in the future.
1588  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1589  * address encoding scheme. (see figure on page 8)
1590  */
1591 static int
1592 in6_lifaddr_ioctl(struct socket *so, u_long cmd, caddr_t data,
1593     struct ifnet *ifp, struct thread *td)
1594 {
1595 	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1596 	struct ifaddr *ifa;
1597 	struct sockaddr *sa;
1598 
1599 	/* sanity checks */
1600 	if (!data || !ifp) {
1601 		panic("invalid argument to in6_lifaddr_ioctl");
1602 		/* NOTREACHED */
1603 	}
1604 
1605 	switch (cmd) {
1606 	case SIOCGLIFADDR:
1607 		/* address must be specified on GET with IFLR_PREFIX */
1608 		if ((iflr->flags & IFLR_PREFIX) == 0)
1609 			break;
1610 		/* FALLTHROUGH */
1611 	case SIOCALIFADDR:
1612 	case SIOCDLIFADDR:
1613 		/* address must be specified on ADD and DELETE */
1614 		sa = (struct sockaddr *)&iflr->addr;
1615 		if (sa->sa_family != AF_INET6)
1616 			return EINVAL;
1617 		if (sa->sa_len != sizeof(struct sockaddr_in6))
1618 			return EINVAL;
1619 		/* XXX need improvement */
1620 		sa = (struct sockaddr *)&iflr->dstaddr;
1621 		if (sa->sa_family && sa->sa_family != AF_INET6)
1622 			return EINVAL;
1623 		if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1624 			return EINVAL;
1625 		break;
1626 	default: /* shouldn't happen */
1627 #if 0
1628 		panic("invalid cmd to in6_lifaddr_ioctl");
1629 		/* NOTREACHED */
1630 #else
1631 		return EOPNOTSUPP;
1632 #endif
1633 	}
1634 	if (sizeof(struct in6_addr) * 8 < iflr->prefixlen)
1635 		return EINVAL;
1636 
1637 	switch (cmd) {
1638 	case SIOCALIFADDR:
1639 	    {
1640 		struct in6_aliasreq ifra;
1641 		struct in6_addr *hostid = NULL;
1642 		int prefixlen;
1643 
1644 		ifa = NULL;
1645 		if ((iflr->flags & IFLR_PREFIX) != 0) {
1646 			struct sockaddr_in6 *sin6;
1647 
1648 			/*
1649 			 * hostid is to fill in the hostid part of the
1650 			 * address.  hostid points to the first link-local
1651 			 * address attached to the interface.
1652 			 */
1653 			ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);
1654 			if (!ifa)
1655 				return EADDRNOTAVAIL;
1656 			hostid = IFA_IN6(ifa);
1657 
1658 			/* prefixlen must be <= 64. */
1659 			if (64 < iflr->prefixlen)
1660 				return EINVAL;
1661 			prefixlen = iflr->prefixlen;
1662 
1663 			/* hostid part must be zero. */
1664 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1665 			if (sin6->sin6_addr.s6_addr32[2] != 0 ||
1666 			    sin6->sin6_addr.s6_addr32[3] != 0) {
1667 				return EINVAL;
1668 			}
1669 		} else
1670 			prefixlen = iflr->prefixlen;
1671 
1672 		/* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1673 		bzero(&ifra, sizeof(ifra));
1674 		bcopy(iflr->iflr_name, ifra.ifra_name, sizeof(ifra.ifra_name));
1675 
1676 		bcopy(&iflr->addr, &ifra.ifra_addr,
1677 		    ((struct sockaddr *)&iflr->addr)->sa_len);
1678 		if (hostid) {
1679 			/* fill in hostid part */
1680 			ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1681 			    hostid->s6_addr32[2];
1682 			ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1683 			    hostid->s6_addr32[3];
1684 		}
1685 
1686 		if (((struct sockaddr *)&iflr->dstaddr)->sa_family) { /* XXX */
1687 			bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
1688 			    ((struct sockaddr *)&iflr->dstaddr)->sa_len);
1689 			if (hostid) {
1690 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1691 				    hostid->s6_addr32[2];
1692 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1693 				    hostid->s6_addr32[3];
1694 			}
1695 		}
1696 		if (ifa != NULL)
1697 			ifa_free(ifa);
1698 
1699 		ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1700 		in6_prefixlen2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1701 
1702 		ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1703 		return in6_control(so, SIOCAIFADDR_IN6, (caddr_t)&ifra, ifp, td);
1704 	    }
1705 	case SIOCGLIFADDR:
1706 	case SIOCDLIFADDR:
1707 	    {
1708 		struct in6_ifaddr *ia;
1709 		struct in6_addr mask, candidate, match;
1710 		struct sockaddr_in6 *sin6;
1711 		int cmp;
1712 
1713 		bzero(&mask, sizeof(mask));
1714 		if (iflr->flags & IFLR_PREFIX) {
1715 			/* lookup a prefix rather than address. */
1716 			in6_prefixlen2mask(&mask, iflr->prefixlen);
1717 
1718 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1719 			bcopy(&sin6->sin6_addr, &match, sizeof(match));
1720 			match.s6_addr32[0] &= mask.s6_addr32[0];
1721 			match.s6_addr32[1] &= mask.s6_addr32[1];
1722 			match.s6_addr32[2] &= mask.s6_addr32[2];
1723 			match.s6_addr32[3] &= mask.s6_addr32[3];
1724 
1725 			/* if you set extra bits, that's wrong */
1726 			if (bcmp(&match, &sin6->sin6_addr, sizeof(match)))
1727 				return EINVAL;
1728 
1729 			cmp = 1;
1730 		} else {
1731 			if (cmd == SIOCGLIFADDR) {
1732 				/* on getting an address, take the 1st match */
1733 				cmp = 0;	/* XXX */
1734 			} else {
1735 				/* on deleting an address, do exact match */
1736 				in6_prefixlen2mask(&mask, 128);
1737 				sin6 = (struct sockaddr_in6 *)&iflr->addr;
1738 				bcopy(&sin6->sin6_addr, &match, sizeof(match));
1739 
1740 				cmp = 1;
1741 			}
1742 		}
1743 
1744 		IF_ADDR_RLOCK(ifp);
1745 		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1746 			if (ifa->ifa_addr->sa_family != AF_INET6)
1747 				continue;
1748 			if (!cmp)
1749 				break;
1750 
1751 			/*
1752 			 * XXX: this is adhoc, but is necessary to allow
1753 			 * a user to specify fe80::/64 (not /10) for a
1754 			 * link-local address.
1755 			 */
1756 			bcopy(IFA_IN6(ifa), &candidate, sizeof(candidate));
1757 			in6_clearscope(&candidate);
1758 			candidate.s6_addr32[0] &= mask.s6_addr32[0];
1759 			candidate.s6_addr32[1] &= mask.s6_addr32[1];
1760 			candidate.s6_addr32[2] &= mask.s6_addr32[2];
1761 			candidate.s6_addr32[3] &= mask.s6_addr32[3];
1762 			if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1763 				break;
1764 		}
1765 		if (ifa != NULL)
1766 			ifa_ref(ifa);
1767 		IF_ADDR_RUNLOCK(ifp);
1768 		if (!ifa)
1769 			return EADDRNOTAVAIL;
1770 		ia = ifa2ia6(ifa);
1771 
1772 		if (cmd == SIOCGLIFADDR) {
1773 			int error;
1774 
1775 			/* fill in the if_laddrreq structure */
1776 			bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin6_len);
1777 			error = sa6_recoverscope(
1778 			    (struct sockaddr_in6 *)&iflr->addr);
1779 			if (error != 0) {
1780 				ifa_free(ifa);
1781 				return (error);
1782 			}
1783 
1784 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1785 				bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
1786 				    ia->ia_dstaddr.sin6_len);
1787 				error = sa6_recoverscope(
1788 				    (struct sockaddr_in6 *)&iflr->dstaddr);
1789 				if (error != 0) {
1790 					ifa_free(ifa);
1791 					return (error);
1792 				}
1793 			} else
1794 				bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
1795 
1796 			iflr->prefixlen =
1797 			    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1798 
1799 			iflr->flags = ia->ia6_flags;	/* XXX */
1800 			ifa_free(ifa);
1801 
1802 			return 0;
1803 		} else {
1804 			struct in6_aliasreq ifra;
1805 
1806 			/* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1807 			bzero(&ifra, sizeof(ifra));
1808 			bcopy(iflr->iflr_name, ifra.ifra_name,
1809 			    sizeof(ifra.ifra_name));
1810 
1811 			bcopy(&ia->ia_addr, &ifra.ifra_addr,
1812 			    ia->ia_addr.sin6_len);
1813 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1814 				bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
1815 				    ia->ia_dstaddr.sin6_len);
1816 			} else {
1817 				bzero(&ifra.ifra_dstaddr,
1818 				    sizeof(ifra.ifra_dstaddr));
1819 			}
1820 			bcopy(&ia->ia_prefixmask, &ifra.ifra_dstaddr,
1821 			    ia->ia_prefixmask.sin6_len);
1822 
1823 			ifra.ifra_flags = ia->ia6_flags;
1824 			ifa_free(ifa);
1825 			return in6_control(so, SIOCDIFADDR_IN6, (caddr_t)&ifra,
1826 			    ifp, td);
1827 		}
1828 	    }
1829 	}
1830 
1831 	return EOPNOTSUPP;	/* just for safety */
1832 }
1833 
1834 /*
1835  * Initialize an interface's intetnet6 address
1836  * and routing table entry.
1837  */
1838 static int
1839 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia,
1840     struct sockaddr_in6 *sin6, int newhost)
1841 {
1842 	int	error = 0, plen, ifacount = 0;
1843 	int	s = splimp();
1844 	struct ifaddr *ifa;
1845 
1846 	/*
1847 	 * Give the interface a chance to initialize
1848 	 * if this is its first address,
1849 	 * and to validate the address if necessary.
1850 	 */
1851 	IF_ADDR_RLOCK(ifp);
1852 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1853 		if (ifa->ifa_addr->sa_family != AF_INET6)
1854 			continue;
1855 		ifacount++;
1856 	}
1857 	IF_ADDR_RUNLOCK(ifp);
1858 
1859 	ia->ia_addr = *sin6;
1860 
1861 	if (ifacount <= 1 && ifp->if_ioctl) {
1862 		error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia);
1863 		if (error) {
1864 			splx(s);
1865 			return (error);
1866 		}
1867 	}
1868 	splx(s);
1869 
1870 	ia->ia_ifa.ifa_metric = ifp->if_metric;
1871 
1872 	/* we could do in(6)_socktrim here, but just omit it at this moment. */
1873 
1874 	/*
1875 	 * Special case:
1876 	 * If a new destination address is specified for a point-to-point
1877 	 * interface, install a route to the destination as an interface
1878 	 * direct route.
1879 	 * XXX: the logic below rejects assigning multiple addresses on a p2p
1880 	 * interface that share the same destination.
1881 	 */
1882 	plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1883 	if (!(ia->ia_flags & IFA_ROUTE) && plen == 128 &&
1884 	    ia->ia_dstaddr.sin6_family == AF_INET6) {
1885 		int rtflags = RTF_UP | RTF_HOST;
1886 
1887 		error = rtrequest(RTM_ADD,
1888 		    (struct sockaddr *)&ia->ia_dstaddr,
1889 		    (struct sockaddr *)&ia->ia_addr,
1890 		    (struct sockaddr *)&ia->ia_prefixmask,
1891 		    ia->ia_flags | rtflags, NULL);
1892 		if (error != 0)
1893 			return (error);
1894 		ia->ia_flags |= IFA_ROUTE;
1895 		/*
1896 		 * Handle the case for ::1 .
1897 		 */
1898 		if (ifp->if_flags & IFF_LOOPBACK)
1899 			ia->ia_flags |= IFA_RTSELF;
1900 	}
1901 
1902 	/*
1903 	 * add a loopback route to self
1904 	 */
1905 	if (!(ia->ia_flags & IFA_RTSELF) && V_nd6_useloopback) {
1906 		error = ifa_add_loopback_route((struct ifaddr *)ia,
1907 				       (struct sockaddr *)&ia->ia_addr);
1908 		if (error == 0)
1909 			ia->ia_flags |= IFA_RTSELF;
1910 	}
1911 
1912 	/* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1913 	if (newhost)
1914 		in6_ifaddloop(&(ia->ia_ifa));
1915 
1916 	return (error);
1917 }
1918 
1919 /*
1920  * Find an IPv6 interface link-local address specific to an interface.
1921  * ifaddr is returned referenced.
1922  */
1923 struct in6_ifaddr *
1924 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
1925 {
1926 	struct ifaddr *ifa;
1927 
1928 	IF_ADDR_RLOCK(ifp);
1929 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1930 		if (ifa->ifa_addr->sa_family != AF_INET6)
1931 			continue;
1932 		if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1933 			if ((((struct in6_ifaddr *)ifa)->ia6_flags &
1934 			     ignoreflags) != 0)
1935 				continue;
1936 			ifa_ref(ifa);
1937 			break;
1938 		}
1939 	}
1940 	IF_ADDR_RUNLOCK(ifp);
1941 
1942 	return ((struct in6_ifaddr *)ifa);
1943 }
1944 
1945 
1946 /*
1947  * find the internet address corresponding to a given interface and address.
1948  * ifaddr is returned referenced.
1949  */
1950 struct in6_ifaddr *
1951 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
1952 {
1953 	struct ifaddr *ifa;
1954 
1955 	IF_ADDR_RLOCK(ifp);
1956 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1957 		if (ifa->ifa_addr->sa_family != AF_INET6)
1958 			continue;
1959 		if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa))) {
1960 			ifa_ref(ifa);
1961 			break;
1962 		}
1963 	}
1964 	IF_ADDR_RUNLOCK(ifp);
1965 
1966 	return ((struct in6_ifaddr *)ifa);
1967 }
1968 
1969 /*
1970  * Convert IP6 address to printable (loggable) representation. Caller
1971  * has to make sure that ip6buf is at least INET6_ADDRSTRLEN long.
1972  */
1973 static char digits[] = "0123456789abcdef";
1974 char *
1975 ip6_sprintf(char *ip6buf, const struct in6_addr *addr)
1976 {
1977 	int i, cnt = 0, maxcnt = 0, idx = 0, index = 0;
1978 	char *cp;
1979 	const u_int16_t *a = (const u_int16_t *)addr;
1980 	const u_int8_t *d;
1981 	int dcolon = 0, zero = 0;
1982 
1983 	cp = ip6buf;
1984 
1985 	for (i = 0; i < 8; i++) {
1986 		if (*(a + i) == 0) {
1987 			cnt++;
1988 			if (cnt == 1)
1989 				idx = i;
1990 		}
1991 		else if (maxcnt < cnt) {
1992 			maxcnt = cnt;
1993 			index = idx;
1994 			cnt = 0;
1995 		}
1996 	}
1997 	if (maxcnt < cnt) {
1998 		maxcnt = cnt;
1999 		index = idx;
2000 	}
2001 
2002 	for (i = 0; i < 8; i++) {
2003 		if (dcolon == 1) {
2004 			if (*a == 0) {
2005 				if (i == 7)
2006 					*cp++ = ':';
2007 				a++;
2008 				continue;
2009 			} else
2010 				dcolon = 2;
2011 		}
2012 		if (*a == 0) {
2013 			if (dcolon == 0 && *(a + 1) == 0 && i == index) {
2014 				if (i == 0)
2015 					*cp++ = ':';
2016 				*cp++ = ':';
2017 				dcolon = 1;
2018 			} else {
2019 				*cp++ = '0';
2020 				*cp++ = ':';
2021 			}
2022 			a++;
2023 			continue;
2024 		}
2025 		d = (const u_char *)a;
2026 		/* Try to eliminate leading zeros in printout like in :0001. */
2027 		zero = 1;
2028 		*cp = digits[*d >> 4];
2029 		if (*cp != '0') {
2030 			zero = 0;
2031 			cp++;
2032 		}
2033 		*cp = digits[*d++ & 0xf];
2034 		if (zero == 0 || (*cp != '0')) {
2035 			zero = 0;
2036 			cp++;
2037 		}
2038 		*cp = digits[*d >> 4];
2039 		if (zero == 0 || (*cp != '0')) {
2040 			zero = 0;
2041 			cp++;
2042 		}
2043 		*cp++ = digits[*d & 0xf];
2044 		*cp++ = ':';
2045 		a++;
2046 	}
2047 	*--cp = '\0';
2048 	return (ip6buf);
2049 }
2050 
2051 int
2052 in6_localaddr(struct in6_addr *in6)
2053 {
2054 	struct in6_ifaddr *ia;
2055 
2056 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
2057 		return 1;
2058 
2059 	IN6_IFADDR_RLOCK();
2060 	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
2061 		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
2062 		    &ia->ia_prefixmask.sin6_addr)) {
2063 			IN6_IFADDR_RUNLOCK();
2064 			return 1;
2065 		}
2066 	}
2067 	IN6_IFADDR_RUNLOCK();
2068 
2069 	return (0);
2070 }
2071 
2072 /*
2073  * Return 1 if an internet address is for the local host and configured
2074  * on one of its interfaces.
2075  */
2076 int
2077 in6_localip(struct in6_addr *in6)
2078 {
2079 	struct in6_ifaddr *ia;
2080 
2081 	IN6_IFADDR_RLOCK();
2082 	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
2083 		if (IN6_ARE_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr)) {
2084 			IN6_IFADDR_RUNLOCK();
2085 			return (1);
2086 		}
2087 	}
2088 	IN6_IFADDR_RUNLOCK();
2089 	return (0);
2090 }
2091 
2092 
2093 int
2094 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
2095 {
2096 	struct in6_ifaddr *ia;
2097 
2098 	IN6_IFADDR_RLOCK();
2099 	TAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
2100 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
2101 				       &sa6->sin6_addr) &&
2102 		    (ia->ia6_flags & IN6_IFF_DEPRECATED) != 0) {
2103 			IN6_IFADDR_RUNLOCK();
2104 			return (1); /* true */
2105 		}
2106 
2107 		/* XXX: do we still have to go thru the rest of the list? */
2108 	}
2109 	IN6_IFADDR_RUNLOCK();
2110 
2111 	return (0);		/* false */
2112 }
2113 
2114 /*
2115  * return length of part which dst and src are equal
2116  * hard coding...
2117  */
2118 int
2119 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
2120 {
2121 	int match = 0;
2122 	u_char *s = (u_char *)src, *d = (u_char *)dst;
2123 	u_char *lim = s + 16, r;
2124 
2125 	while (s < lim)
2126 		if ((r = (*d++ ^ *s++)) != 0) {
2127 			while (r < 128) {
2128 				match++;
2129 				r <<= 1;
2130 			}
2131 			break;
2132 		} else
2133 			match += 8;
2134 	return match;
2135 }
2136 
2137 /* XXX: to be scope conscious */
2138 int
2139 in6_are_prefix_equal(struct in6_addr *p1, struct in6_addr *p2, int len)
2140 {
2141 	int bytelen, bitlen;
2142 
2143 	/* sanity check */
2144 	if (0 > len || len > 128) {
2145 		log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
2146 		    len);
2147 		return (0);
2148 	}
2149 
2150 	bytelen = len / 8;
2151 	bitlen = len % 8;
2152 
2153 	if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
2154 		return (0);
2155 	if (bitlen != 0 &&
2156 	    p1->s6_addr[bytelen] >> (8 - bitlen) !=
2157 	    p2->s6_addr[bytelen] >> (8 - bitlen))
2158 		return (0);
2159 
2160 	return (1);
2161 }
2162 
2163 void
2164 in6_prefixlen2mask(struct in6_addr *maskp, int len)
2165 {
2166 	u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
2167 	int bytelen, bitlen, i;
2168 
2169 	/* sanity check */
2170 	if (0 > len || len > 128) {
2171 		log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
2172 		    len);
2173 		return;
2174 	}
2175 
2176 	bzero(maskp, sizeof(*maskp));
2177 	bytelen = len / 8;
2178 	bitlen = len % 8;
2179 	for (i = 0; i < bytelen; i++)
2180 		maskp->s6_addr[i] = 0xff;
2181 	if (bitlen)
2182 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
2183 }
2184 
2185 /*
2186  * return the best address out of the same scope. if no address was
2187  * found, return the first valid address from designated IF.
2188  */
2189 struct in6_ifaddr *
2190 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
2191 {
2192 	int dst_scope =	in6_addrscope(dst), blen = -1, tlen;
2193 	struct ifaddr *ifa;
2194 	struct in6_ifaddr *besta = 0;
2195 	struct in6_ifaddr *dep[2];	/* last-resort: deprecated */
2196 
2197 	dep[0] = dep[1] = NULL;
2198 
2199 	/*
2200 	 * We first look for addresses in the same scope.
2201 	 * If there is one, return it.
2202 	 * If two or more, return one which matches the dst longest.
2203 	 * If none, return one of global addresses assigned other ifs.
2204 	 */
2205 	IF_ADDR_RLOCK(ifp);
2206 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2207 		if (ifa->ifa_addr->sa_family != AF_INET6)
2208 			continue;
2209 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2210 			continue; /* XXX: is there any case to allow anycast? */
2211 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2212 			continue; /* don't use this interface */
2213 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2214 			continue;
2215 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2216 			if (V_ip6_use_deprecated)
2217 				dep[0] = (struct in6_ifaddr *)ifa;
2218 			continue;
2219 		}
2220 
2221 		if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
2222 			/*
2223 			 * call in6_matchlen() as few as possible
2224 			 */
2225 			if (besta) {
2226 				if (blen == -1)
2227 					blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
2228 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
2229 				if (tlen > blen) {
2230 					blen = tlen;
2231 					besta = (struct in6_ifaddr *)ifa;
2232 				}
2233 			} else
2234 				besta = (struct in6_ifaddr *)ifa;
2235 		}
2236 	}
2237 	if (besta) {
2238 		ifa_ref(&besta->ia_ifa);
2239 		IF_ADDR_RUNLOCK(ifp);
2240 		return (besta);
2241 	}
2242 
2243 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2244 		if (ifa->ifa_addr->sa_family != AF_INET6)
2245 			continue;
2246 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2247 			continue; /* XXX: is there any case to allow anycast? */
2248 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2249 			continue; /* don't use this interface */
2250 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2251 			continue;
2252 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2253 			if (V_ip6_use_deprecated)
2254 				dep[1] = (struct in6_ifaddr *)ifa;
2255 			continue;
2256 		}
2257 
2258 		if (ifa != NULL)
2259 			ifa_ref(ifa);
2260 		IF_ADDR_RUNLOCK(ifp);
2261 		return (struct in6_ifaddr *)ifa;
2262 	}
2263 	IF_ADDR_RUNLOCK(ifp);
2264 
2265 	/* use the last-resort values, that are, deprecated addresses */
2266 	if (dep[0])
2267 		return dep[0];
2268 	if (dep[1])
2269 		return dep[1];
2270 
2271 	return NULL;
2272 }
2273 
2274 /*
2275  * perform DAD when interface becomes IFF_UP.
2276  */
2277 void
2278 in6_if_up(struct ifnet *ifp)
2279 {
2280 	struct ifaddr *ifa;
2281 	struct in6_ifaddr *ia;
2282 
2283 	IF_ADDR_RLOCK(ifp);
2284 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2285 		if (ifa->ifa_addr->sa_family != AF_INET6)
2286 			continue;
2287 		ia = (struct in6_ifaddr *)ifa;
2288 		if (ia->ia6_flags & IN6_IFF_TENTATIVE) {
2289 			/*
2290 			 * The TENTATIVE flag was likely set by hand
2291 			 * beforehand, implicitly indicating the need for DAD.
2292 			 * We may be able to skip the random delay in this
2293 			 * case, but we impose delays just in case.
2294 			 */
2295 			nd6_dad_start(ifa,
2296 			    arc4random() % (MAX_RTR_SOLICITATION_DELAY * hz));
2297 		}
2298 	}
2299 	IF_ADDR_RUNLOCK(ifp);
2300 
2301 	/*
2302 	 * special cases, like 6to4, are handled in in6_ifattach
2303 	 */
2304 	in6_ifattach(ifp, NULL);
2305 }
2306 
2307 int
2308 in6if_do_dad(struct ifnet *ifp)
2309 {
2310 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2311 		return (0);
2312 
2313 	if (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)
2314 		return (0);
2315 
2316 	switch (ifp->if_type) {
2317 #ifdef IFT_DUMMY
2318 	case IFT_DUMMY:
2319 #endif
2320 	case IFT_FAITH:
2321 		/*
2322 		 * These interfaces do not have the IFF_LOOPBACK flag,
2323 		 * but loop packets back.  We do not have to do DAD on such
2324 		 * interfaces.  We should even omit it, because loop-backed
2325 		 * NS would confuse the DAD procedure.
2326 		 */
2327 		return (0);
2328 	default:
2329 		/*
2330 		 * Our DAD routine requires the interface up and running.
2331 		 * However, some interfaces can be up before the RUNNING
2332 		 * status.  Additionaly, users may try to assign addresses
2333 		 * before the interface becomes up (or running).
2334 		 * We simply skip DAD in such a case as a work around.
2335 		 * XXX: we should rather mark "tentative" on such addresses,
2336 		 * and do DAD after the interface becomes ready.
2337 		 */
2338 		if (!((ifp->if_flags & IFF_UP) &&
2339 		    (ifp->if_drv_flags & IFF_DRV_RUNNING)))
2340 			return (0);
2341 
2342 		return (1);
2343 	}
2344 }
2345 
2346 /*
2347  * Calculate max IPv6 MTU through all the interfaces and store it
2348  * to in6_maxmtu.
2349  */
2350 void
2351 in6_setmaxmtu(void)
2352 {
2353 	unsigned long maxmtu = 0;
2354 	struct ifnet *ifp;
2355 
2356 	IFNET_RLOCK_NOSLEEP();
2357 	TAILQ_FOREACH(ifp, &V_ifnet, if_list) {
2358 		/* this function can be called during ifnet initialization */
2359 		if (!ifp->if_afdata[AF_INET6])
2360 			continue;
2361 		if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
2362 		    IN6_LINKMTU(ifp) > maxmtu)
2363 			maxmtu = IN6_LINKMTU(ifp);
2364 	}
2365 	IFNET_RUNLOCK_NOSLEEP();
2366 	if (maxmtu)	     /* update only when maxmtu is positive */
2367 		V_in6_maxmtu = maxmtu;
2368 }
2369 
2370 /*
2371  * Provide the length of interface identifiers to be used for the link attached
2372  * to the given interface.  The length should be defined in "IPv6 over
2373  * xxx-link" document.  Note that address architecture might also define
2374  * the length for a particular set of address prefixes, regardless of the
2375  * link type.  As clarified in rfc2462bis, those two definitions should be
2376  * consistent, and those really are as of August 2004.
2377  */
2378 int
2379 in6_if2idlen(struct ifnet *ifp)
2380 {
2381 	switch (ifp->if_type) {
2382 	case IFT_ETHER:		/* RFC2464 */
2383 #ifdef IFT_PROPVIRTUAL
2384 	case IFT_PROPVIRTUAL:	/* XXX: no RFC. treat it as ether */
2385 #endif
2386 #ifdef IFT_L2VLAN
2387 	case IFT_L2VLAN:	/* ditto */
2388 #endif
2389 #ifdef IFT_IEEE80211
2390 	case IFT_IEEE80211:	/* ditto */
2391 #endif
2392 #ifdef IFT_MIP
2393 	case IFT_MIP:	/* ditto */
2394 #endif
2395 	case IFT_INFINIBAND:
2396 		return (64);
2397 	case IFT_FDDI:		/* RFC2467 */
2398 		return (64);
2399 	case IFT_ISO88025:	/* RFC2470 (IPv6 over Token Ring) */
2400 		return (64);
2401 	case IFT_PPP:		/* RFC2472 */
2402 		return (64);
2403 	case IFT_ARCNET:	/* RFC2497 */
2404 		return (64);
2405 	case IFT_FRELAY:	/* RFC2590 */
2406 		return (64);
2407 	case IFT_IEEE1394:	/* RFC3146 */
2408 		return (64);
2409 	case IFT_GIF:
2410 		return (64);	/* draft-ietf-v6ops-mech-v2-07 */
2411 	case IFT_LOOP:
2412 		return (64);	/* XXX: is this really correct? */
2413 	default:
2414 		/*
2415 		 * Unknown link type:
2416 		 * It might be controversial to use the today's common constant
2417 		 * of 64 for these cases unconditionally.  For full compliance,
2418 		 * we should return an error in this case.  On the other hand,
2419 		 * if we simply miss the standard for the link type or a new
2420 		 * standard is defined for a new link type, the IFID length
2421 		 * is very likely to be the common constant.  As a compromise,
2422 		 * we always use the constant, but make an explicit notice
2423 		 * indicating the "unknown" case.
2424 		 */
2425 		printf("in6_if2idlen: unknown link type (%d)\n", ifp->if_type);
2426 		return (64);
2427 	}
2428 }
2429 
2430 #include <sys/sysctl.h>
2431 
2432 struct in6_llentry {
2433 	struct llentry		base;
2434 	struct sockaddr_in6	l3_addr6;
2435 };
2436 
2437 static struct llentry *
2438 in6_lltable_new(const struct sockaddr *l3addr, u_int flags)
2439 {
2440 	struct in6_llentry *lle;
2441 
2442 	lle = malloc(sizeof(struct in6_llentry), M_LLTABLE,
2443 	    M_DONTWAIT | M_ZERO);
2444 	if (lle == NULL)		/* NB: caller generates msg */
2445 		return NULL;
2446 
2447 	lle->l3_addr6 = *(const struct sockaddr_in6 *)l3addr;
2448 	lle->base.lle_refcnt = 1;
2449 	LLE_LOCK_INIT(&lle->base);
2450 	callout_init_rw(&lle->base.ln_timer_ch, &lle->base.lle_lock,
2451 	    CALLOUT_RETURNUNLOCKED);
2452 
2453 	return &lle->base;
2454 }
2455 
2456 /*
2457  * Deletes an address from the address table.
2458  * This function is called by the timer functions
2459  * such as arptimer() and nd6_llinfo_timer(), and
2460  * the caller does the locking.
2461  */
2462 static void
2463 in6_lltable_free(struct lltable *llt, struct llentry *lle)
2464 {
2465 	LLE_WUNLOCK(lle);
2466 	LLE_LOCK_DESTROY(lle);
2467 	free(lle, M_LLTABLE);
2468 }
2469 
2470 static void
2471 in6_lltable_prefix_free(struct lltable *llt,
2472 			const struct sockaddr *prefix,
2473 			const struct sockaddr *mask,
2474 			u_int flags)
2475 {
2476 	const struct sockaddr_in6 *pfx = (const struct sockaddr_in6 *)prefix;
2477 	const struct sockaddr_in6 *msk = (const struct sockaddr_in6 *)mask;
2478 	struct llentry *lle, *next;
2479 	register int i;
2480 
2481 	/*
2482 	 * (flags & LLE_STATIC) means deleting all entries
2483 	 * including static ND6 entries
2484 	 */
2485 	for (i=0; i < LLTBL_HASHTBL_SIZE; i++) {
2486 		LIST_FOREACH_SAFE(lle, &llt->lle_head[i], lle_next, next) {
2487 			if (IN6_ARE_MASKED_ADDR_EQUAL(
2488 				    &((struct sockaddr_in6 *)L3_ADDR(lle))->sin6_addr,
2489 				    &pfx->sin6_addr,
2490 				    &msk->sin6_addr) &&
2491 			    ((flags & LLE_STATIC) || !(lle->la_flags & LLE_STATIC))) {
2492 				int canceled;
2493 
2494 				canceled = callout_drain(&lle->la_timer);
2495 				LLE_WLOCK(lle);
2496 				if (canceled)
2497 					LLE_REMREF(lle);
2498 				llentry_free(lle);
2499 			}
2500 		}
2501 	}
2502 }
2503 
2504 static int
2505 in6_lltable_rtcheck(struct ifnet *ifp,
2506 		    u_int flags,
2507 		    const struct sockaddr *l3addr)
2508 {
2509 	struct rtentry *rt;
2510 	char ip6buf[INET6_ADDRSTRLEN];
2511 
2512 	KASSERT(l3addr->sa_family == AF_INET6,
2513 	    ("sin_family %d", l3addr->sa_family));
2514 
2515 	/* XXX rtalloc1 should take a const param */
2516 	rt = rtalloc1(__DECONST(struct sockaddr *, l3addr), 0, 0);
2517 	if (rt == NULL || (rt->rt_flags & RTF_GATEWAY) || rt->rt_ifp != ifp) {
2518 		struct ifaddr *ifa;
2519 		/*
2520 		 * Create an ND6 cache for an IPv6 neighbor
2521 		 * that is not covered by our own prefix.
2522 		 */
2523 		/* XXX ifaof_ifpforaddr should take a const param */
2524 		ifa = ifaof_ifpforaddr(__DECONST(struct sockaddr *, l3addr), ifp);
2525 		if (ifa != NULL) {
2526 			ifa_free(ifa);
2527 			if (rt != NULL)
2528 				RTFREE_LOCKED(rt);
2529 			return 0;
2530 		}
2531 		log(LOG_INFO, "IPv6 address: \"%s\" is not on the network\n",
2532 		    ip6_sprintf(ip6buf, &((const struct sockaddr_in6 *)l3addr)->sin6_addr));
2533 		if (rt != NULL)
2534 			RTFREE_LOCKED(rt);
2535 		return EINVAL;
2536 	}
2537 	RTFREE_LOCKED(rt);
2538 	return 0;
2539 }
2540 
2541 static struct llentry *
2542 in6_lltable_lookup(struct lltable *llt, u_int flags,
2543 	const struct sockaddr *l3addr)
2544 {
2545 	const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)l3addr;
2546 	struct ifnet *ifp = llt->llt_ifp;
2547 	struct llentry *lle;
2548 	struct llentries *lleh;
2549 	u_int hashkey;
2550 
2551 	IF_AFDATA_LOCK_ASSERT(ifp);
2552 	KASSERT(l3addr->sa_family == AF_INET6,
2553 	    ("sin_family %d", l3addr->sa_family));
2554 
2555 	hashkey = sin6->sin6_addr.s6_addr32[3];
2556 	lleh = &llt->lle_head[LLATBL_HASH(hashkey, LLTBL_HASHMASK)];
2557 	LIST_FOREACH(lle, lleh, lle_next) {
2558 		struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)L3_ADDR(lle);
2559 		if (lle->la_flags & LLE_DELETED)
2560 			continue;
2561 		if (bcmp(&sa6->sin6_addr, &sin6->sin6_addr,
2562 			 sizeof(struct in6_addr)) == 0)
2563 			break;
2564 	}
2565 
2566 	if (lle == NULL) {
2567 		if (!(flags & LLE_CREATE))
2568 			return (NULL);
2569 		/*
2570 		 * A route that covers the given address must have
2571 		 * been installed 1st because we are doing a resolution,
2572 		 * verify this.
2573 		 */
2574 		if (!(flags & LLE_IFADDR) &&
2575 		    in6_lltable_rtcheck(ifp, flags, l3addr) != 0)
2576 			return NULL;
2577 
2578 		lle = in6_lltable_new(l3addr, flags);
2579 		if (lle == NULL) {
2580 			log(LOG_INFO, "lla_lookup: new lle malloc failed\n");
2581 			return NULL;
2582 		}
2583 		lle->la_flags = flags & ~LLE_CREATE;
2584 		if ((flags & (LLE_CREATE | LLE_IFADDR)) == (LLE_CREATE | LLE_IFADDR)) {
2585 			bcopy(IF_LLADDR(ifp), &lle->ll_addr, ifp->if_addrlen);
2586 			lle->la_flags |= (LLE_VALID | LLE_STATIC);
2587 		}
2588 
2589 		lle->lle_tbl  = llt;
2590 		lle->lle_head = lleh;
2591 		LIST_INSERT_HEAD(lleh, lle, lle_next);
2592 	} else if (flags & LLE_DELETE) {
2593 		if (!(lle->la_flags & LLE_IFADDR) || (flags & LLE_IFADDR)) {
2594 			LLE_WLOCK(lle);
2595 			lle->la_flags = LLE_DELETED;
2596 			LLE_WUNLOCK(lle);
2597 #ifdef DIAGNOSTIC
2598 			log(LOG_INFO, "ifaddr cache = %p  is deleted\n", lle);
2599 #endif
2600 		}
2601 		lle = (void *)-1;
2602 	}
2603 	if (LLE_IS_VALID(lle)) {
2604 		if (flags & LLE_EXCLUSIVE)
2605 			LLE_WLOCK(lle);
2606 		else
2607 			LLE_RLOCK(lle);
2608 	}
2609 	return (lle);
2610 }
2611 
2612 static int
2613 in6_lltable_dump(struct lltable *llt, struct sysctl_req *wr)
2614 {
2615 	struct ifnet *ifp = llt->llt_ifp;
2616 	struct llentry *lle;
2617 	/* XXX stack use */
2618 	struct {
2619 		struct rt_msghdr	rtm;
2620 		struct sockaddr_in6	sin6;
2621 		/*
2622 		 * ndp.c assumes that sdl is word aligned
2623 		 */
2624 #ifdef __LP64__
2625 		uint32_t		pad;
2626 #endif
2627 		struct sockaddr_dl	sdl;
2628 	} ndpc;
2629 	int i, error;
2630 
2631 	if (ifp->if_flags & IFF_LOOPBACK)
2632 		return 0;
2633 
2634 	LLTABLE_LOCK_ASSERT();
2635 
2636 	error = 0;
2637 	for (i = 0; i < LLTBL_HASHTBL_SIZE; i++) {
2638 		LIST_FOREACH(lle, &llt->lle_head[i], lle_next) {
2639 			struct sockaddr_dl *sdl;
2640 
2641 			/* skip deleted or invalid entries */
2642 			if ((lle->la_flags & (LLE_DELETED|LLE_VALID)) != LLE_VALID)
2643 				continue;
2644 			/* Skip if jailed and not a valid IP of the prison. */
2645 			if (prison_if(wr->td->td_ucred, L3_ADDR(lle)) != 0)
2646 				continue;
2647 			/*
2648 			 * produce a msg made of:
2649 			 *  struct rt_msghdr;
2650 			 *  struct sockaddr_in6 (IPv6)
2651 			 *  struct sockaddr_dl;
2652 			 */
2653 			bzero(&ndpc, sizeof(ndpc));
2654 			ndpc.rtm.rtm_msglen = sizeof(ndpc);
2655 			ndpc.rtm.rtm_version = RTM_VERSION;
2656 			ndpc.rtm.rtm_type = RTM_GET;
2657 			ndpc.rtm.rtm_flags = RTF_UP;
2658 			ndpc.rtm.rtm_addrs = RTA_DST | RTA_GATEWAY;
2659 			ndpc.sin6.sin6_family = AF_INET6;
2660 			ndpc.sin6.sin6_len = sizeof(ndpc.sin6);
2661 			bcopy(L3_ADDR(lle), &ndpc.sin6, L3_ADDR_LEN(lle));
2662 
2663 			/* publish */
2664 			if (lle->la_flags & LLE_PUB)
2665 				ndpc.rtm.rtm_flags |= RTF_ANNOUNCE;
2666 
2667 			sdl = &ndpc.sdl;
2668 			sdl->sdl_family = AF_LINK;
2669 			sdl->sdl_len = sizeof(*sdl);
2670 			sdl->sdl_alen = ifp->if_addrlen;
2671 			sdl->sdl_index = ifp->if_index;
2672 			sdl->sdl_type = ifp->if_type;
2673 			bcopy(&lle->ll_addr, LLADDR(sdl), ifp->if_addrlen);
2674 			ndpc.rtm.rtm_rmx.rmx_expire =
2675 			    lle->la_flags & LLE_STATIC ? 0 : lle->la_expire;
2676 			ndpc.rtm.rtm_flags |= (RTF_HOST | RTF_LLDATA);
2677 			if (lle->la_flags & LLE_STATIC)
2678 				ndpc.rtm.rtm_flags |= RTF_STATIC;
2679 			ndpc.rtm.rtm_index = ifp->if_index;
2680 			error = SYSCTL_OUT(wr, &ndpc, sizeof(ndpc));
2681 			if (error)
2682 				break;
2683 		}
2684 	}
2685 	return error;
2686 }
2687 
2688 void *
2689 in6_domifattach(struct ifnet *ifp)
2690 {
2691 	struct in6_ifextra *ext;
2692 
2693 	ext = (struct in6_ifextra *)malloc(sizeof(*ext), M_IFADDR, M_WAITOK);
2694 	bzero(ext, sizeof(*ext));
2695 
2696 	ext->in6_ifstat = (struct in6_ifstat *)malloc(sizeof(struct in6_ifstat),
2697 	    M_IFADDR, M_WAITOK);
2698 	bzero(ext->in6_ifstat, sizeof(*ext->in6_ifstat));
2699 
2700 	ext->icmp6_ifstat =
2701 	    (struct icmp6_ifstat *)malloc(sizeof(struct icmp6_ifstat),
2702 	    M_IFADDR, M_WAITOK);
2703 	bzero(ext->icmp6_ifstat, sizeof(*ext->icmp6_ifstat));
2704 
2705 	ext->nd_ifinfo = nd6_ifattach(ifp);
2706 	ext->scope6_id = scope6_ifattach(ifp);
2707 	ext->lltable = lltable_init(ifp, AF_INET6);
2708 	if (ext->lltable != NULL) {
2709 		ext->lltable->llt_free = in6_lltable_free;
2710 		ext->lltable->llt_prefix_free = in6_lltable_prefix_free;
2711 		ext->lltable->llt_lookup = in6_lltable_lookup;
2712 		ext->lltable->llt_dump = in6_lltable_dump;
2713 	}
2714 
2715 	ext->mld_ifinfo = mld_domifattach(ifp);
2716 
2717 	return ext;
2718 }
2719 
2720 void
2721 in6_domifdetach(struct ifnet *ifp, void *aux)
2722 {
2723 	struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2724 
2725 	mld_domifdetach(ifp);
2726 	scope6_ifdetach(ext->scope6_id);
2727 	nd6_ifdetach(ext->nd_ifinfo);
2728 	lltable_free(ext->lltable);
2729 	free(ext->in6_ifstat, M_IFADDR);
2730 	free(ext->icmp6_ifstat, M_IFADDR);
2731 	free(ext, M_IFADDR);
2732 }
2733 
2734 /*
2735  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2736  * v4 mapped addr or v4 compat addr
2737  */
2738 void
2739 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2740 {
2741 
2742 	bzero(sin, sizeof(*sin));
2743 	sin->sin_len = sizeof(struct sockaddr_in);
2744 	sin->sin_family = AF_INET;
2745 	sin->sin_port = sin6->sin6_port;
2746 	sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
2747 }
2748 
2749 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2750 void
2751 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2752 {
2753 	bzero(sin6, sizeof(*sin6));
2754 	sin6->sin6_len = sizeof(struct sockaddr_in6);
2755 	sin6->sin6_family = AF_INET6;
2756 	sin6->sin6_port = sin->sin_port;
2757 	sin6->sin6_addr.s6_addr32[0] = 0;
2758 	sin6->sin6_addr.s6_addr32[1] = 0;
2759 	sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2760 	sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2761 }
2762 
2763 /* Convert sockaddr_in6 into sockaddr_in. */
2764 void
2765 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2766 {
2767 	struct sockaddr_in *sin_p;
2768 	struct sockaddr_in6 sin6;
2769 
2770 	/*
2771 	 * Save original sockaddr_in6 addr and convert it
2772 	 * to sockaddr_in.
2773 	 */
2774 	sin6 = *(struct sockaddr_in6 *)nam;
2775 	sin_p = (struct sockaddr_in *)nam;
2776 	in6_sin6_2_sin(sin_p, &sin6);
2777 }
2778 
2779 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2780 void
2781 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2782 {
2783 	struct sockaddr_in *sin_p;
2784 	struct sockaddr_in6 *sin6_p;
2785 
2786 	sin6_p = malloc(sizeof *sin6_p, M_SONAME,
2787 	       M_WAITOK);
2788 	sin_p = (struct sockaddr_in *)*nam;
2789 	in6_sin_2_v4mapsin6(sin_p, sin6_p);
2790 	free(*nam, M_SONAME);
2791 	*nam = (struct sockaddr *)sin6_p;
2792 }
2793