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