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