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