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