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