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