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