Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[dragonfly.git] / sys / netinet6 / in6.c
1 /*      $FreeBSD: src/sys/netinet6/in6.c,v 1.7.2.9 2002/04/28 05:40:26 suz Exp $        */
2 /*      $DragonFly: src/sys/netinet6/in6.c,v 1.30 2008/10/03 07:59:20 hasso Exp $       */
3 /*      $KAME: in6.c,v 1.259 2002/01/21 11:37:50 keiichi Exp $  */
4
5 /*
6  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 1982, 1986, 1991, 1993
36  *      The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *      This product includes software developed by the University of
49  *      California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *      @(#)in.c        8.2 (Berkeley) 11/15/93
67  */
68
69 #include "opt_inet.h"
70 #include "opt_inet6.h"
71
72 #include <sys/param.h>
73 #include <sys/errno.h>
74 #include <sys/malloc.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/sockio.h>
78 #include <sys/systm.h>
79 #include <sys/proc.h>
80 #include <sys/priv.h>
81 #include <sys/time.h>
82 #include <sys/kernel.h>
83 #include <sys/syslog.h>
84 #include <sys/thread2.h>
85
86 #include <net/if.h>
87 #include <net/if_types.h>
88 #include <net/route.h>
89 #include <net/if_dl.h>
90
91 #include <netinet/in.h>
92 #include <netinet/in_var.h>
93 #include <netinet/if_ether.h>
94 #include <netinet/in_systm.h>
95 #include <netinet/ip.h>
96 #include <netinet/in_pcb.h>
97
98 #include <netinet/ip6.h>
99 #include <netinet6/ip6_var.h>
100 #include <netinet6/nd6.h>
101 #include <netinet6/mld6_var.h>
102 #include <netinet6/ip6_mroute.h>
103 #include <netinet6/in6_ifattach.h>
104 #include <netinet6/scope6_var.h>
105 #include <netinet6/in6_pcb.h>
106 #include <netinet6/in6_var.h>
107
108 #include <net/net_osdep.h>
109
110 /*
111  * Definitions of some costant IP6 addresses.
112  */
113 const struct in6_addr kin6addr_any = IN6ADDR_ANY_INIT;
114 const struct in6_addr kin6addr_loopback = IN6ADDR_LOOPBACK_INIT;
115 const struct in6_addr kin6addr_nodelocal_allnodes =
116         IN6ADDR_NODELOCAL_ALLNODES_INIT;
117 const struct in6_addr kin6addr_linklocal_allnodes =
118         IN6ADDR_LINKLOCAL_ALLNODES_INIT;
119 const struct in6_addr kin6addr_linklocal_allrouters =
120         IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
121
122 const struct in6_addr in6mask0 = IN6MASK0;
123 const struct in6_addr in6mask32 = IN6MASK32;
124 const struct in6_addr in6mask64 = IN6MASK64;
125 const struct in6_addr in6mask96 = IN6MASK96;
126 const struct in6_addr in6mask128 = IN6MASK128;
127
128 const struct sockaddr_in6 sa6_any = {sizeof(sa6_any), AF_INET6,
129                                      0, 0, IN6ADDR_ANY_INIT, 0};
130
131 static int in6_lifaddr_ioctl (struct socket *, u_long, caddr_t,
132         struct ifnet *, struct thread *);
133 static int in6_ifinit (struct ifnet *, struct in6_ifaddr *,
134                            struct sockaddr_in6 *, int);
135 static void in6_unlink_ifa (struct in6_ifaddr *, struct ifnet *);
136 static void in6_ifloop_request_callback(int, int, struct rt_addrinfo *, struct rtentry *, void *);
137
138 struct in6_multihead in6_multihead;     /* XXX BSS initialization */
139
140 int     (*faithprefix_p)(struct in6_addr *);
141
142 /*
143  * Subroutine for in6_ifaddloop() and in6_ifremloop().
144  * This routine does actual work.
145  */
146 static void
147 in6_ifloop_request(int cmd, struct ifaddr *ifa)
148 {
149         struct sockaddr_in6 all1_sa;
150         struct rt_addrinfo rtinfo;
151         int error;
152
153         bzero(&all1_sa, sizeof(all1_sa));
154         all1_sa.sin6_family = AF_INET6;
155         all1_sa.sin6_len = sizeof(struct sockaddr_in6);
156         all1_sa.sin6_addr = in6mask128;
157
158         /*
159          * We specify the address itself as the gateway, and set the
160          * RTF_LLINFO flag, so that the corresponding host route would have
161          * the flag, and thus applications that assume traditional behavior
162          * would be happy.  Note that we assume the caller of the function
163          * (probably implicitly) set nd6_rtrequest() to ifa->ifa_rtrequest,
164          * which changes the outgoing interface to the loopback interface.
165          */
166         bzero(&rtinfo, sizeof(struct rt_addrinfo));
167         rtinfo.rti_info[RTAX_DST] = ifa->ifa_addr;
168         rtinfo.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
169         rtinfo.rti_info[RTAX_NETMASK] = (struct sockaddr *)&all1_sa;
170         rtinfo.rti_flags = RTF_UP|RTF_HOST|RTF_LLINFO;
171
172         error = rtrequest1_global(cmd, &rtinfo,
173                                   in6_ifloop_request_callback, ifa);
174         if (error != 0) {
175                 log(LOG_ERR, "in6_ifloop_request: "
176                     "%s operation failed for %s (errno=%d)\n",
177                     cmd == RTM_ADD ? "ADD" : "DELETE",
178                     ip6_sprintf(&((struct in6_ifaddr *)ifa)->ia_addr.sin6_addr),
179                     error);
180         }
181 }
182
183 static void
184 in6_ifloop_request_callback(int cmd, int error, struct rt_addrinfo *rtinfo,
185                             struct rtentry *rt, void *arg)
186 {
187         struct ifaddr *ifa = arg;
188
189         if (error)
190                 goto done;
191
192         /*
193          * Make sure rt_ifa be equal to IFA, the second argument of the
194          * function.
195          * We need this because when we refer to rt_ifa->ia6_flags in
196          * ip6_input, we assume that the rt_ifa points to the address instead
197          * of the loopback address.
198          */
199         if (cmd == RTM_ADD && rt && ifa != rt->rt_ifa) {
200                 ++rt->rt_refcnt;
201                 IFAFREE(rt->rt_ifa);
202                 IFAREF(ifa);
203                 rt->rt_ifa = ifa;
204                 --rt->rt_refcnt;
205         }
206
207         /*
208          * Report the addition/removal of the address to the routing socket.
209          * XXX: since we called rtinit for a p2p interface with a destination,
210          *      we end up reporting twice in such a case.  Should we rather
211          *      omit the second report?
212          */
213         if (rt) {
214                 if (mycpuid == 0)
215                         rt_newaddrmsg(cmd, ifa, error, rt);
216                 if (cmd == RTM_DELETE) {
217                         if (rt->rt_refcnt == 0) {
218                                 ++rt->rt_refcnt;
219                                 rtfree(rt);
220                         }
221                 }
222         }
223 done:
224         /* no way to return any new error */
225         ;
226 }
227
228 /*
229  * Add ownaddr as loopback rtentry.  We previously add the route only if
230  * necessary (ex. on a p2p link).  However, since we now manage addresses
231  * separately from prefixes, we should always add the route.  We can't
232  * rely on the cloning mechanism from the corresponding interface route
233  * any more.
234  */
235 void
236 in6_ifaddloop(struct ifaddr *ifa)
237 {
238         struct rtentry *rt;
239
240         /* If there is no loopback entry, allocate one. */
241         rt = rtpurelookup(ifa->ifa_addr);
242         if (rt == NULL || !(rt->rt_flags & RTF_HOST) ||
243             !(rt->rt_ifp->if_flags & IFF_LOOPBACK))
244                 in6_ifloop_request(RTM_ADD, ifa);
245         if (rt != NULL)
246                 rt->rt_refcnt--;
247 }
248
249 /*
250  * Remove loopback rtentry of ownaddr generated by in6_ifaddloop(),
251  * if it exists.
252  */
253 void
254 in6_ifremloop(struct ifaddr *ifa)
255 {
256         struct in6_ifaddr *ia;
257         struct rtentry *rt;
258         int ia_count = 0;
259
260         /*
261          * Some of BSD variants do not remove cloned routes
262          * from an interface direct route, when removing the direct route
263          * (see comments in net/net_osdep.h).  Even for variants that do remove
264          * cloned routes, they could fail to remove the cloned routes when
265          * we handle multple addresses that share a common prefix.
266          * So, we should remove the route corresponding to the deleted address
267          * regardless of the result of in6_is_ifloop_auto().
268          */
269
270         /*
271          * Delete the entry only if exact one ifa exists.  More than one ifa
272          * can exist if we assign a same single address to multiple
273          * (probably p2p) interfaces.
274          * XXX: we should avoid such a configuration in IPv6...
275          */
276         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
277                 if (IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ia->ia_addr.sin6_addr)) {
278                         ia_count++;
279                         if (ia_count > 1)
280                                 break;
281                 }
282         }
283
284         if (ia_count == 1) {
285                 /*
286                  * Before deleting, check if a corresponding loopbacked host
287                  * route surely exists.  With this check, we can avoid to
288                  * delete an interface direct route whose destination is same
289                  * as the address being removed.  This can happen when remofing
290                  * a subnet-router anycast address on an interface attahced
291                  * to a shared medium.
292                  */
293                 rt = rtpurelookup(ifa->ifa_addr);
294                 if (rt != NULL && (rt->rt_flags & RTF_HOST) &&
295                     (rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
296                         rt->rt_refcnt--;
297                         in6_ifloop_request(RTM_DELETE, ifa);
298                 }
299         }
300 }
301
302 int
303 in6_ifindex2scopeid(int idx)
304 {
305         struct ifnet *ifp;
306         struct sockaddr_in6 *sin6;
307         struct ifaddr_container *ifac;
308
309         if (idx < 0 || if_index < idx)
310                 return -1;
311         ifp = ifindex2ifnet[idx];
312
313         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link)
314         {
315                 struct ifaddr *ifa = ifac->ifa;
316
317                 if (ifa->ifa_addr->sa_family != AF_INET6)
318                         continue;
319                 sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
320                 if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))
321                         return sin6->sin6_scope_id & 0xffff;
322         }
323
324         return -1;
325 }
326
327 int
328 in6_mask2len(struct in6_addr *mask, u_char *lim0)
329 {
330         int x = 0, y;
331         u_char *lim = lim0, *p;
332
333         if (lim0 == NULL ||
334             lim0 - (u_char *)mask > sizeof(*mask)) /* ignore the scope_id part */
335                 lim = (u_char *)mask + sizeof(*mask);
336         for (p = (u_char *)mask; p < lim; x++, p++) {
337                 if (*p != 0xff)
338                         break;
339         }
340         y = 0;
341         if (p < lim) {
342                 for (y = 0; y < 8; y++) {
343                         if ((*p & (0x80 >> y)) == 0)
344                                 break;
345                 }
346         }
347
348         /*
349          * when the limit pointer is given, do a stricter check on the
350          * remaining bits.
351          */
352         if (p < lim) {
353                 if (y != 0 && (*p & (0x00ff >> y)) != 0)
354                         return (-1);
355                 for (p = p + 1; p < lim; p++)
356                         if (*p != 0)
357                                 return (-1);
358         }
359
360         return x * 8 + y;
361 }
362
363 void
364 in6_len2mask(struct in6_addr *mask, int len)
365 {
366         int i;
367
368         bzero(mask, sizeof(*mask));
369         for (i = 0; i < len / 8; i++)
370                 mask->s6_addr8[i] = 0xff;
371         if (len % 8)
372                 mask->s6_addr8[i] = (0xff00 >> (len % 8)) & 0xff;
373 }
374
375 #define ifa2ia6(ifa)    ((struct in6_ifaddr *)(ifa))
376 #define ia62ifa(ia6)    (&((ia6)->ia_ifa))
377
378 int
379 in6_control(struct socket *so, u_long cmd, caddr_t data,
380             struct ifnet *ifp, struct thread *td)
381 {
382         struct  in6_ifreq *ifr = (struct in6_ifreq *)data;
383         struct  in6_ifaddr *ia = NULL;
384         struct  in6_aliasreq *ifra = (struct in6_aliasreq *)data;
385         int privileged;
386         int error;
387
388         privileged = 0;
389         if (priv_check(td, PRIV_ROOT) == 0)
390                 privileged++;
391
392         switch (cmd) {
393         case SIOCGETSGCNT_IN6:
394         case SIOCGETMIFCNT_IN6:
395                 return (mrt6_ioctl(cmd, data));
396         }
397
398         switch(cmd) {
399         case SIOCAADDRCTL_POLICY:
400         case SIOCDADDRCTL_POLICY:
401                 if (!privileged)
402                         return (EPERM);
403                 return (in6_src_ioctl(cmd, data));
404         }
405
406         if (ifp == NULL)
407                 return (EOPNOTSUPP);
408
409         switch (cmd) {
410         case SIOCSNDFLUSH_IN6:
411         case SIOCSPFXFLUSH_IN6:
412         case SIOCSRTRFLUSH_IN6:
413         case SIOCSDEFIFACE_IN6:
414         case SIOCSIFINFO_FLAGS:
415                 if (!privileged)
416                         return (EPERM);
417                 /* fall through */
418         case OSIOCGIFINFO_IN6:
419         case SIOCGIFINFO_IN6:
420         case SIOCGDRLST_IN6:
421         case SIOCGPRLST_IN6:
422         case SIOCGNBRINFO_IN6:
423         case SIOCGDEFIFACE_IN6:
424                 return (nd6_ioctl(cmd, data, ifp));
425         }
426
427         switch (cmd) {
428         case SIOCSIFPREFIX_IN6:
429         case SIOCDIFPREFIX_IN6:
430         case SIOCAIFPREFIX_IN6:
431         case SIOCCIFPREFIX_IN6:
432         case SIOCSGIFPREFIX_IN6:
433         case SIOCGIFPREFIX_IN6:
434                 log(LOG_NOTICE,
435                     "prefix ioctls are now invalidated. "
436                     "please use ifconfig.\n");
437                 return (EOPNOTSUPP);
438         }
439
440         switch (cmd) {
441         case SIOCSSCOPE6:
442                 if (!privileged)
443                         return (EPERM);
444                 return (scope6_set(ifp,
445                         (struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
446                 break;
447         case SIOCGSCOPE6:
448                 return (scope6_get(ifp,
449                         (struct scope6_id *)ifr->ifr_ifru.ifru_scope_id));
450                 break;
451         case SIOCGSCOPE6DEF:
452                 return (scope6_get_default((struct scope6_id *)
453                         ifr->ifr_ifru.ifru_scope_id));
454                 break;
455         }
456
457         switch (cmd) {
458         case SIOCALIFADDR:
459         case SIOCDLIFADDR:
460                 if (!privileged)
461                         return (EPERM);
462                 /* fall through */
463         case SIOCGLIFADDR:
464                 return in6_lifaddr_ioctl(so, cmd, data, ifp, td);
465         }
466
467         /*
468          * Find address for this interface, if it exists.
469          */
470         if (ifra->ifra_addr.sin6_family == AF_INET6) { /* XXX */
471                 struct sockaddr_in6 *sa6 =
472                         (struct sockaddr_in6 *)&ifra->ifra_addr;
473
474                 if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
475                         if (sa6->sin6_addr.s6_addr16[1] == 0) {
476                                 /* link ID is not embedded by the user */
477                                 sa6->sin6_addr.s6_addr16[1] =
478                                         htons(ifp->if_index);
479                         } else if (sa6->sin6_addr.s6_addr16[1] !=
480                                     htons(ifp->if_index)) {
481                                 return (EINVAL);        /* link ID contradicts */
482                         }
483                         if (sa6->sin6_scope_id) {
484                                 if (sa6->sin6_scope_id !=
485                                     (u_int32_t)ifp->if_index)
486                                         return (EINVAL);
487                                 sa6->sin6_scope_id = 0; /* XXX: good way? */
488                         }
489                 }
490                 ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr);
491         }
492
493         switch (cmd) {
494         case SIOCSIFADDR_IN6:
495         case SIOCSIFDSTADDR_IN6:
496         case SIOCSIFNETMASK_IN6:
497                 /*
498                  * Since IPv6 allows a node to assign multiple addresses
499                  * on a single interface, SIOCSIFxxx ioctls are not suitable
500                  * and should be unused.
501                  */
502                 /* we decided to obsolete this command (20000704) */
503                 return (EINVAL);
504
505         case SIOCDIFADDR_IN6:
506                 /*
507                  * for IPv4, we look for existing in_ifaddr here to allow
508                  * "ifconfig if0 delete" to remove first IPv4 address on the
509                  * interface.  For IPv6, as the spec allow multiple interface
510                  * address from the day one, we consider "remove the first one"
511                  * semantics to be not preferable.
512                  */
513                 if (ia == NULL)
514                         return (EADDRNOTAVAIL);
515                 /* FALLTHROUGH */
516         case SIOCAIFADDR_IN6:
517                 /*
518                  * We always require users to specify a valid IPv6 address for
519                  * the corresponding operation.
520                  */
521                 if (ifra->ifra_addr.sin6_family != AF_INET6 ||
522                     ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6))
523                         return (EAFNOSUPPORT);
524                 if (!privileged)
525                         return (EPERM);
526
527                 break;
528
529         case SIOCGIFADDR_IN6:
530                 /* This interface is basically deprecated. use SIOCGIFCONF. */
531                 /* fall through */
532         case SIOCGIFAFLAG_IN6:
533         case SIOCGIFNETMASK_IN6:
534         case SIOCGIFDSTADDR_IN6:
535         case SIOCGIFALIFETIME_IN6:
536                 /* must think again about its semantics */
537                 if (ia == NULL)
538                         return (EADDRNOTAVAIL);
539                 break;
540         case SIOCSIFALIFETIME_IN6:
541             {
542                 struct in6_addrlifetime *lt;
543
544                 if (!privileged)
545                         return (EPERM);
546                 if (ia == NULL)
547                         return (EADDRNOTAVAIL);
548                 /* sanity for overflow - beware unsigned */
549                 lt = &ifr->ifr_ifru.ifru_lifetime;
550                 if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
551                  && lt->ia6t_vltime + time_second < time_second) {
552                         return EINVAL;
553                 }
554                 if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
555                  && lt->ia6t_pltime + time_second < time_second) {
556                         return EINVAL;
557                 }
558                 break;
559             }
560         }
561
562         switch (cmd) {
563
564         case SIOCGIFADDR_IN6:
565                 ifr->ifr_addr = ia->ia_addr;
566                 break;
567
568         case SIOCGIFDSTADDR_IN6:
569                 if (!(ifp->if_flags & IFF_POINTOPOINT))
570                         return (EINVAL);
571                 /*
572                  * XXX: should we check if ifa_dstaddr is NULL and return
573                  * an error?
574                  */
575                 ifr->ifr_dstaddr = ia->ia_dstaddr;
576                 break;
577
578         case SIOCGIFNETMASK_IN6:
579                 ifr->ifr_addr = ia->ia_prefixmask;
580                 break;
581
582         case SIOCGIFAFLAG_IN6:
583                 ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
584                 break;
585
586         case SIOCGIFSTAT_IN6:
587                 if (ifp == NULL)
588                         return EINVAL;
589                 bzero(&ifr->ifr_ifru.ifru_stat,
590                         sizeof(ifr->ifr_ifru.ifru_stat));
591                 ifr->ifr_ifru.ifru_stat =
592                         *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
593                 break;
594
595         case SIOCGIFSTAT_ICMP6:
596                 bzero(&ifr->ifr_ifru.ifru_stat,
597                         sizeof(ifr->ifr_ifru.ifru_icmp6stat));
598                 ifr->ifr_ifru.ifru_icmp6stat =
599                         *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
600                 break;
601
602         case SIOCGIFALIFETIME_IN6:
603                 ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
604                 break;
605
606         case SIOCSIFALIFETIME_IN6:
607                 ia->ia6_lifetime = ifr->ifr_ifru.ifru_lifetime;
608                 /* for sanity */
609                 if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
610                         ia->ia6_lifetime.ia6t_expire =
611                                 time_second + ia->ia6_lifetime.ia6t_vltime;
612                 } else
613                         ia->ia6_lifetime.ia6t_expire = 0;
614                 if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
615                         ia->ia6_lifetime.ia6t_preferred =
616                                 time_second + ia->ia6_lifetime.ia6t_pltime;
617                 } else
618                         ia->ia6_lifetime.ia6t_preferred = 0;
619                 break;
620
621         case SIOCAIFADDR_IN6:
622         {
623                 int i, error = 0, iaIsNew;
624                 struct nd_prefix pr0, *pr;
625
626                 if (ia != NULL)
627                         iaIsNew = 0;
628                 else
629                         iaIsNew = 1;
630
631                 /*
632                  * first, make or update the interface address structure,
633                  * and link it to the list.
634                  */
635                 if ((error = in6_update_ifa(ifp, ifra, ia)) != 0)
636                         return (error);
637
638                 /*
639                  * then, make the prefix on-link on the interface.
640                  * XXX: we'd rather create the prefix before the address, but
641                  * we need at least one address to install the corresponding
642                  * interface route, so we configure the address first.
643                  */
644
645                 /*
646                  * convert mask to prefix length (prefixmask has already
647                  * been validated in in6_update_ifa().
648                  */
649                 bzero(&pr0, sizeof(pr0));
650                 pr0.ndpr_ifp = ifp;
651                 pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
652                                              NULL);
653                 if (pr0.ndpr_plen == 128)
654                         break;  /* we don't need to install a host route. */
655                 pr0.ndpr_prefix = ifra->ifra_addr;
656                 pr0.ndpr_mask = ifra->ifra_prefixmask.sin6_addr;
657                 /* apply the mask for safety. */
658                 for (i = 0; i < 4; i++) {
659                         pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
660                                 ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
661                 }
662                 /*
663                  * XXX: since we don't have an API to set prefix (not address)
664                  * lifetimes, we just use the same lifetimes as addresses.
665                  * The (temporarily) installed lifetimes can be overridden by
666                  * later advertised RAs (when accept_rtadv is non 0), which is
667                  * an intended behavior.
668                  */
669                 pr0.ndpr_raf_onlink = 1; /* should be configurable? */
670                 pr0.ndpr_raf_auto =
671                         ((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
672                 pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
673                 pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
674
675                 /* add the prefix if there's one. */
676                 if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
677                         /*
678                          * nd6_prelist_add will install the corresponding
679                          * interface route.
680                          */
681                         if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
682                                 return (error);
683                         if (pr == NULL) {
684                                 log(LOG_ERR, "nd6_prelist_add succeeded but "
685                                     "no prefix\n");
686                                 return (EINVAL); /* XXX panic here? */
687                         }
688                 }
689                 if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
690                     == NULL) {
691                         /* XXX: this should not happen! */
692                         log(LOG_ERR, "in6_control: addition succeeded, but"
693                             " no ifaddr\n");
694                 } else {
695                         if ((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
696                             ia->ia6_ndpr == NULL) { /* new autoconfed addr */
697                                 ia->ia6_ndpr = pr;
698                                 pr->ndpr_refcnt++;
699
700                                 /*
701                                  * If this is the first autoconf address from
702                                  * the prefix, create a temporary address
703                                  * as well (when specified).
704                                  */
705                                 if (ip6_use_tempaddr &&
706                                     pr->ndpr_refcnt == 1) {
707                                         int e;
708                                         if ((e = in6_tmpifadd(ia, 1)) != 0) {
709                                                 log(LOG_NOTICE, "in6_control: "
710                                                     "failed to create a "
711                                                     "temporary address, "
712                                                     "errno=%d\n",
713                                                     e);
714                                         }
715                                 }
716                         }
717
718                         /*
719                          * this might affect the status of autoconfigured
720                          * addresses, that is, this address might make
721                          * other addresses detached.
722                          */
723                         pfxlist_onlink_check();
724                 }
725                 if (error == 0 && ia) {
726                         EVENTHANDLER_INVOKE(ifaddr_event, ifp,
727                         iaIsNew ? IFADDR_EVENT_ADD : IFADDR_EVENT_CHANGE,
728                         &ia->ia_ifa);
729                 }
730                 break;
731         }
732
733         case SIOCDIFADDR_IN6:
734         {
735                 int i = 0;
736                 struct nd_prefix pr0, *pr;
737
738                 /*
739                  * If the address being deleted is the only one that owns
740                  * the corresponding prefix, expire the prefix as well.
741                  * XXX: theoretically, we don't have to warry about such
742                  * relationship, since we separate the address management
743                  * and the prefix management.  We do this, however, to provide
744                  * as much backward compatibility as possible in terms of
745                  * the ioctl operation.
746                  */
747                 bzero(&pr0, sizeof(pr0));
748                 pr0.ndpr_ifp = ifp;
749                 pr0.ndpr_plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr,
750                                              NULL);
751                 if (pr0.ndpr_plen == 128)
752                         goto purgeaddr;
753                 pr0.ndpr_prefix = ia->ia_addr;
754                 pr0.ndpr_mask = ia->ia_prefixmask.sin6_addr;
755                 for (i = 0; i < 4; i++) {
756                         pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
757                                 ia->ia_prefixmask.sin6_addr.s6_addr32[i];
758                 }
759                 /*
760                  * The logic of the following condition is a bit complicated.
761                  * We expire the prefix when
762                  * 1. the address obeys autoconfiguration and it is the
763                  *    only owner of the associated prefix, or
764                  * 2. the address does not obey autoconf and there is no
765                  *    other owner of the prefix.
766                  */
767                 if ((pr = nd6_prefix_lookup(&pr0)) != NULL &&
768                     (((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
769                        pr->ndpr_refcnt == 1) ||
770                      (!(ia->ia6_flags & IN6_IFF_AUTOCONF) &&
771                       pr->ndpr_refcnt == 0))) {
772                         pr->ndpr_expire = 1; /* XXX: just for expiration */
773                 }
774
775 purgeaddr:
776                 EVENTHANDLER_INVOKE(ifaddr_event, ifp, IFADDR_EVENT_DELETE,
777                                     &ia->ia_ifa);
778                 in6_purgeaddr(&ia->ia_ifa);
779                 break;
780         }
781
782         default:
783                 if (ifp == NULL || ifp->if_ioctl == 0)
784                         return (EOPNOTSUPP);
785                 lwkt_serialize_enter(ifp->if_serializer);
786                 error = ifp->if_ioctl(ifp, cmd, data, td->td_proc->p_ucred);
787                 lwkt_serialize_exit(ifp->if_serializer);
788                 return (error);
789         }
790
791         return (0);
792 }
793
794 /*
795  * Update parameters of an IPv6 interface address.
796  * If necessary, a new entry is created and linked into address chains.
797  * This function is separated from in6_control().
798  * XXX: should this be performed under splnet()?
799  */
800 int
801 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
802                struct in6_ifaddr *ia)
803 {
804         int error = 0, hostIsNew = 0, plen = -1;
805         struct in6_ifaddr *oia;
806         struct sockaddr_in6 dst6;
807         struct in6_addrlifetime *lt;
808
809         /* Validate parameters */
810         if (ifp == NULL || ifra == NULL) /* this maybe redundant */
811                 return (EINVAL);
812
813         /*
814          * The destination address for a p2p link must have a family
815          * of AF_UNSPEC or AF_INET6.
816          */
817         if ((ifp->if_flags & IFF_POINTOPOINT) &&
818             ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
819             ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
820                 return (EAFNOSUPPORT);
821         /*
822          * validate ifra_prefixmask.  don't check sin6_family, netmask
823          * does not carry fields other than sin6_len.
824          */
825         if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
826                 return (EINVAL);
827         /*
828          * Because the IPv6 address architecture is classless, we require
829          * users to specify a (non 0) prefix length (mask) for a new address.
830          * We also require the prefix (when specified) mask is valid, and thus
831          * reject a non-consecutive mask.
832          */
833         if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
834                 return (EINVAL);
835         if (ifra->ifra_prefixmask.sin6_len != 0) {
836                 plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
837                                     (u_char *)&ifra->ifra_prefixmask +
838                                     ifra->ifra_prefixmask.sin6_len);
839                 if (plen <= 0)
840                         return (EINVAL);
841         }
842         else {
843                 /*
844                  * In this case, ia must not be NULL.  We just use its prefix
845                  * length.
846                  */
847                 plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
848         }
849         /*
850          * If the destination address on a p2p interface is specified,
851          * and the address is a scoped one, validate/set the scope
852          * zone identifier.
853          */
854         dst6 = ifra->ifra_dstaddr;
855         if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) &&
856             (dst6.sin6_family == AF_INET6)) {
857                 int scopeid;
858
859                 if ((error = in6_recoverscope(&dst6,
860                                               &ifra->ifra_dstaddr.sin6_addr,
861                                               ifp)) != 0)
862                         return (error);
863                 scopeid = in6_addr2scopeid(ifp, &dst6.sin6_addr);
864                 if (dst6.sin6_scope_id == 0) /* user omit to specify the ID. */
865                         dst6.sin6_scope_id = scopeid;
866                 else if (dst6.sin6_scope_id != scopeid)
867                         return (EINVAL); /* scope ID mismatch. */
868                 if ((error = in6_embedscope(&dst6.sin6_addr, &dst6, NULL, NULL))
869                     != 0)
870                         return (error);
871                 dst6.sin6_scope_id = 0; /* XXX */
872         }
873         /*
874          * The destination address can be specified only for a p2p or a
875          * loopback interface.  If specified, the corresponding prefix length
876          * must be 128.
877          */
878         if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
879                 if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
880                         /* XXX: noisy message */
881                         log(LOG_INFO, "in6_update_ifa: a destination can be "
882                             "specified for a p2p or a loopback IF only\n");
883                         return (EINVAL);
884                 }
885                 if (plen != 128) {
886                         /*
887                          * The following message seems noisy, but we dare to
888                          * add it for diagnosis.
889                          */
890                         log(LOG_INFO, "in6_update_ifa: prefixlen must be 128 "
891                             "when dstaddr is specified\n");
892                         return (EINVAL);
893                 }
894         }
895         /* lifetime consistency check */
896         lt = &ifra->ifra_lifetime;
897         if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
898             && lt->ia6t_vltime + time_second < time_second) {
899                 return EINVAL;
900         }
901         if (lt->ia6t_vltime == 0) {
902                 /*
903                  * the following log might be noisy, but this is a typical
904                  * configuration mistake or a tool's bug.
905                  */
906                 log(LOG_INFO,
907                     "in6_update_ifa: valid lifetime is 0 for %s\n",
908                     ip6_sprintf(&ifra->ifra_addr.sin6_addr));
909         }
910         if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
911             && lt->ia6t_pltime + time_second < time_second) {
912                 return EINVAL;
913         }
914
915         /*
916          * If this is a new address, allocate a new ifaddr and link it
917          * into chains.
918          */
919         if (ia == NULL) {
920                 hostIsNew = 1;
921                 /*
922                  * When in6_update_ifa() is called in a process of a received
923                  * RA, it is called under splnet().  So, we should call malloc
924                  * with M_NOWAIT.
925                  */
926                 ia = ifa_create(sizeof(*ia), M_NOWAIT);
927                 if (ia == NULL)
928                         return (ENOBUFS);
929                 /* Initialize the address and masks */
930                 ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
931                 ia->ia_addr.sin6_family = AF_INET6;
932                 ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
933                 if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
934                         /*
935                          * XXX: some functions expect that ifa_dstaddr is not
936                          * NULL for p2p interfaces.
937                          */
938                         ia->ia_ifa.ifa_dstaddr
939                                 = (struct sockaddr *)&ia->ia_dstaddr;
940                 } else {
941                         ia->ia_ifa.ifa_dstaddr = NULL;
942                 }
943                 ia->ia_ifa.ifa_netmask
944                         = (struct sockaddr *)&ia->ia_prefixmask;
945
946                 ia->ia_ifp = ifp;
947                 if ((oia = in6_ifaddr) != NULL) {
948                         for ( ; oia->ia_next; oia = oia->ia_next)
949                                 continue;
950                         oia->ia_next = ia;
951                 } else
952                         in6_ifaddr = ia;
953
954                 ifa_iflink(&ia->ia_ifa, ifp, 1);
955         }
956
957         /* set prefix mask */
958         if (ifra->ifra_prefixmask.sin6_len) {
959                 /*
960                  * We prohibit changing the prefix length of an existing
961                  * address, because
962                  * + such an operation should be rare in IPv6, and
963                  * + the operation would confuse prefix management.
964                  */
965                 if (ia->ia_prefixmask.sin6_len &&
966                     in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
967                         log(LOG_INFO, "in6_update_ifa: the prefix length of an"
968                             " existing (%s) address should not be changed\n",
969                             ip6_sprintf(&ia->ia_addr.sin6_addr));
970                         error = EINVAL;
971                         goto unlink;
972                 }
973                 ia->ia_prefixmask = ifra->ifra_prefixmask;
974         }
975
976         /*
977          * If a new destination address is specified, scrub the old one and
978          * install the new destination.  Note that the interface must be
979          * p2p or loopback (see the check above.)
980          */
981         if (dst6.sin6_family == AF_INET6 &&
982             !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr,
983                                 &ia->ia_dstaddr.sin6_addr)) {
984                 int e;
985
986                 if ((ia->ia_flags & IFA_ROUTE) &&
987                     (e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
988                     != 0) {
989                         log(LOG_ERR, "in6_update_ifa: failed to remove "
990                             "a route to the old destination: %s\n",
991                             ip6_sprintf(&ia->ia_addr.sin6_addr));
992                         /* proceed anyway... */
993                 }
994                 else
995                         ia->ia_flags &= ~IFA_ROUTE;
996                 ia->ia_dstaddr = dst6;
997         }
998
999         /* reset the interface and routing table appropriately. */
1000         if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
1001                 goto unlink;
1002
1003         /*
1004          * Beyond this point, we should call in6_purgeaddr upon an error,
1005          * not just go to unlink.
1006          */
1007
1008 #if 0                           /* disable this mechanism for now */
1009         /* update prefix list */
1010         if (hostIsNew &&
1011             (ifra->ifra_flags & IN6_IFF_NOPFX) == 0) { /* XXX */
1012                 int iilen;
1013
1014                 iilen = (sizeof(ia->ia_prefixmask.sin6_addr) << 3) - plen;
1015                 if ((error = in6_prefix_add_ifid(iilen, ia)) != 0) {
1016                         in6_purgeaddr((struct ifaddr *)ia);
1017                         return (error);
1018                 }
1019         }
1020 #endif
1021
1022         if (ifp->if_flags & IFF_MULTICAST) {
1023                 struct sockaddr_in6 mltaddr, mltmask;
1024                 struct in6_multi *in6m;
1025
1026                 if (hostIsNew) {
1027                         /*
1028                          * join solicited multicast addr for new host id
1029                          */
1030                         struct in6_addr llsol;
1031                         bzero(&llsol, sizeof(struct in6_addr));
1032                         llsol.s6_addr16[0] = htons(0xff02);
1033                         llsol.s6_addr16[1] = htons(ifp->if_index);
1034                         llsol.s6_addr32[1] = 0;
1035                         llsol.s6_addr32[2] = htonl(1);
1036                         llsol.s6_addr32[3] =
1037                                 ifra->ifra_addr.sin6_addr.s6_addr32[3];
1038                         llsol.s6_addr8[12] = 0xff;
1039                         in6_addmulti(&llsol, ifp, &error);
1040                         if (error != 0) {
1041                                 log(LOG_WARNING,
1042                                     "in6_update_ifa: addmulti failed for "
1043                                     "%s on %s (errno=%d)\n",
1044                                     ip6_sprintf(&llsol), if_name(ifp),
1045                                     error);
1046                                 in6_purgeaddr((struct ifaddr *)ia);
1047                                 return (error);
1048                         }
1049                 }
1050
1051                 bzero(&mltmask, sizeof(mltmask));
1052                 mltmask.sin6_len = sizeof(struct sockaddr_in6);
1053                 mltmask.sin6_family = AF_INET6;
1054                 mltmask.sin6_addr = in6mask32;
1055
1056                 /*
1057                  * join link-local all-nodes address
1058                  */
1059                 bzero(&mltaddr, sizeof(mltaddr));
1060                 mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1061                 mltaddr.sin6_family = AF_INET6;
1062                 mltaddr.sin6_addr = kin6addr_linklocal_allnodes;
1063                 mltaddr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1064
1065                 IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1066                 if (in6m == NULL) {
1067                         rtrequest_global(RTM_ADD,
1068                                   (struct sockaddr *)&mltaddr,
1069                                   (struct sockaddr *)&ia->ia_addr,
1070                                   (struct sockaddr *)&mltmask,
1071                                   RTF_UP|RTF_CLONING);  /* xxx */
1072                         in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1073                         if (error != 0) {
1074                                 log(LOG_WARNING,
1075                                     "in6_update_ifa: addmulti failed for "
1076                                     "%s on %s (errno=%d)\n",
1077                                     ip6_sprintf(&mltaddr.sin6_addr),
1078                                     if_name(ifp), error);
1079                         }
1080                 }
1081
1082                 /*
1083                  * join node information group address
1084                  */
1085 #define hostnamelen     strlen(hostname)
1086                 if (in6_nigroup(ifp, hostname, hostnamelen, &mltaddr.sin6_addr)
1087                     == 0) {
1088                         IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1089                         if (in6m == NULL && ia != NULL) {
1090                                 in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1091                                 if (error != 0) {
1092                                         log(LOG_WARNING, "in6_update_ifa: "
1093                                             "addmulti failed for "
1094                                             "%s on %s (errno=%d)\n",
1095                                             ip6_sprintf(&mltaddr.sin6_addr),
1096                                             if_name(ifp), error);
1097                                 }
1098                         }
1099                 }
1100 #undef hostnamelen
1101
1102                 /*
1103                  * join node-local all-nodes address, on loopback.
1104                  * XXX: since "node-local" is obsoleted by interface-local,
1105                  *      we have to join the group on every interface with
1106                  *      some interface-boundary restriction.
1107                  */
1108                 if (ifp->if_flags & IFF_LOOPBACK) {
1109                         struct in6_ifaddr *ia_loop;
1110
1111                         struct in6_addr loop6 = kin6addr_loopback;
1112                         ia_loop = in6ifa_ifpwithaddr(ifp, &loop6);
1113
1114                         mltaddr.sin6_addr = kin6addr_nodelocal_allnodes;
1115
1116                         IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1117                         if (in6m == NULL && ia_loop != NULL) {
1118                                 rtrequest_global(RTM_ADD,
1119                                           (struct sockaddr *)&mltaddr,
1120                                           (struct sockaddr *)&ia_loop->ia_addr,
1121                                           (struct sockaddr *)&mltmask,
1122                                           RTF_UP);
1123                                 in6_addmulti(&mltaddr.sin6_addr, ifp, &error);
1124                                 if (error != 0) {
1125                                         log(LOG_WARNING, "in6_update_ifa: "
1126                                             "addmulti failed for %s on %s "
1127                                             "(errno=%d)\n",
1128                                             ip6_sprintf(&mltaddr.sin6_addr),
1129                                             if_name(ifp), error);
1130                                 }
1131                         }
1132                 }
1133         }
1134
1135         ia->ia6_flags = ifra->ifra_flags;
1136         ia->ia6_flags &= ~IN6_IFF_DUPLICATED;   /*safety*/
1137         ia->ia6_flags &= ~IN6_IFF_NODAD;        /* Mobile IPv6 */
1138
1139         ia->ia6_lifetime = ifra->ifra_lifetime;
1140         /* for sanity */
1141         if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1142                 ia->ia6_lifetime.ia6t_expire =
1143                         time_second + ia->ia6_lifetime.ia6t_vltime;
1144         } else
1145                 ia->ia6_lifetime.ia6t_expire = 0;
1146         if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1147                 ia->ia6_lifetime.ia6t_preferred =
1148                         time_second + ia->ia6_lifetime.ia6t_pltime;
1149         } else
1150                 ia->ia6_lifetime.ia6t_preferred = 0;
1151
1152         /*
1153          * Perform DAD, if needed.
1154          * XXX It may be of use, if we can administratively
1155          * disable DAD.
1156          */
1157         if (in6if_do_dad(ifp) && !(ifra->ifra_flags & IN6_IFF_NODAD)) {
1158                 ia->ia6_flags |= IN6_IFF_TENTATIVE;
1159                 nd6_dad_start((struct ifaddr *)ia, NULL);
1160         }
1161
1162         return (error);
1163
1164 unlink:
1165         /*
1166          * XXX: if a change of an existing address failed, keep the entry
1167          * anyway.
1168          */
1169         if (hostIsNew)
1170                 in6_unlink_ifa(ia, ifp);
1171         return (error);
1172 }
1173
1174 void
1175 in6_purgeaddr(struct ifaddr *ifa)
1176 {
1177         struct ifnet *ifp = ifa->ifa_ifp;
1178         struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1179
1180         /* stop DAD processing */
1181         nd6_dad_stop(ifa);
1182
1183         /*
1184          * delete route to the destination of the address being purged.
1185          * The interface must be p2p or loopback in this case.
1186          */
1187         if ((ia->ia_flags & IFA_ROUTE) && ia->ia_dstaddr.sin6_len != 0) {
1188                 int e;
1189
1190                 if ((e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1191                     != 0) {
1192                         log(LOG_ERR, "in6_purgeaddr: failed to remove "
1193                             "a route to the p2p destination: %s on %s, "
1194                             "errno=%d\n",
1195                             ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
1196                             e);
1197                         /* proceed anyway... */
1198                 }
1199                 else
1200                         ia->ia_flags &= ~IFA_ROUTE;
1201         }
1202
1203         /* Remove ownaddr's loopback rtentry, if it exists. */
1204         in6_ifremloop(&(ia->ia_ifa));
1205
1206         if (ifp->if_flags & IFF_MULTICAST) {
1207                 /*
1208                  * delete solicited multicast addr for deleting host id
1209                  */
1210                 struct in6_multi *in6m;
1211                 struct in6_addr llsol;
1212                 bzero(&llsol, sizeof(struct in6_addr));
1213                 llsol.s6_addr16[0] = htons(0xff02);
1214                 llsol.s6_addr16[1] = htons(ifp->if_index);
1215                 llsol.s6_addr32[1] = 0;
1216                 llsol.s6_addr32[2] = htonl(1);
1217                 llsol.s6_addr32[3] =
1218                         ia->ia_addr.sin6_addr.s6_addr32[3];
1219                 llsol.s6_addr8[12] = 0xff;
1220
1221                 IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1222                 if (in6m)
1223                         in6_delmulti(in6m);
1224         }
1225
1226         in6_unlink_ifa(ia, ifp);
1227 }
1228
1229 static void
1230 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1231 {
1232         int plen, iilen;
1233         struct in6_ifaddr *oia;
1234
1235         crit_enter();
1236
1237         ifa_ifunlink(&ia->ia_ifa, ifp);
1238
1239         oia = ia;
1240         if (oia == (ia = in6_ifaddr))
1241                 in6_ifaddr = ia->ia_next;
1242         else {
1243                 while (ia->ia_next && (ia->ia_next != oia))
1244                         ia = ia->ia_next;
1245                 if (ia->ia_next)
1246                         ia->ia_next = oia->ia_next;
1247                 else {
1248                         /* search failed */
1249                         kprintf("Couldn't unlink in6_ifaddr from in6_ifaddr\n");
1250                 }
1251         }
1252
1253         if (oia->ia6_ifpr) {    /* check for safety */
1254                 plen = in6_mask2len(&oia->ia_prefixmask.sin6_addr, NULL);
1255                 iilen = (sizeof(oia->ia_prefixmask.sin6_addr) << 3) - plen;
1256                 in6_prefix_remove_ifid(iilen, oia);
1257         }
1258
1259         /*
1260          * When an autoconfigured address is being removed, release the
1261          * reference to the base prefix.  Also, since the release might
1262          * affect the status of other (detached) addresses, call
1263          * pfxlist_onlink_check().
1264          */
1265         if (oia->ia6_flags & IN6_IFF_AUTOCONF) {
1266                 if (oia->ia6_ndpr == NULL) {
1267                         log(LOG_NOTICE, "in6_unlink_ifa: autoconf'ed address "
1268                             "%p has no prefix\n", oia);
1269                 } else {
1270                         oia->ia6_ndpr->ndpr_refcnt--;
1271                         oia->ia6_flags &= ~IN6_IFF_AUTOCONF;
1272                         oia->ia6_ndpr = NULL;
1273                 }
1274
1275                 pfxlist_onlink_check();
1276         }
1277
1278         /*
1279          * release another refcnt for the link from in6_ifaddr.
1280          * Note that we should decrement the refcnt at least once for all *BSD.
1281          */
1282         ifa_destroy(&oia->ia_ifa);
1283
1284         crit_exit();
1285 }
1286
1287 void
1288 in6_purgeif(struct ifnet *ifp)
1289 {
1290         struct ifaddr_container *ifac, *next;
1291
1292         TAILQ_FOREACH_MUTABLE(ifac, &ifp->if_addrheads[mycpuid],
1293                               ifa_link, next) {
1294                 if (ifac->ifa->ifa_addr->sa_family != AF_INET6)
1295                         continue;
1296                 in6_purgeaddr(ifac->ifa);
1297         }
1298
1299         in6_ifdetach(ifp);
1300 }
1301
1302 /*
1303  * SIOC[GAD]LIFADDR.
1304  *      SIOCGLIFADDR: get first address. (?)
1305  *      SIOCGLIFADDR with IFLR_PREFIX:
1306  *              get first address that matches the specified prefix.
1307  *      SIOCALIFADDR: add the specified address.
1308  *      SIOCALIFADDR with IFLR_PREFIX:
1309  *              add the specified prefix, filling hostid part from
1310  *              the first link-local address.  prefixlen must be <= 64.
1311  *      SIOCDLIFADDR: delete the specified address.
1312  *      SIOCDLIFADDR with IFLR_PREFIX:
1313  *              delete the first address that matches the specified prefix.
1314  * return values:
1315  *      EINVAL on invalid parameters
1316  *      EADDRNOTAVAIL on prefix match failed/specified address not found
1317  *      other values may be returned from in6_ioctl()
1318  *
1319  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1320  * this is to accomodate address naming scheme other than RFC2374,
1321  * in the future.
1322  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1323  * address encoding scheme. (see figure on page 8)
1324  */
1325 static int
1326 in6_lifaddr_ioctl(struct socket *so, u_long cmd, caddr_t data,
1327                   struct ifnet *ifp, struct thread *td)
1328 {
1329         struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1330         struct sockaddr *sa;
1331
1332         /* sanity checks */
1333         if (!data || !ifp) {
1334                 panic("invalid argument to in6_lifaddr_ioctl");
1335                 /*NOTRECHED*/
1336         }
1337
1338         switch (cmd) {
1339         case SIOCGLIFADDR:
1340                 /* address must be specified on GET with IFLR_PREFIX */
1341                 if (!(iflr->flags & IFLR_PREFIX))
1342                         break;
1343                 /* FALLTHROUGH */
1344         case SIOCALIFADDR:
1345         case SIOCDLIFADDR:
1346                 /* address must be specified on ADD and DELETE */
1347                 sa = (struct sockaddr *)&iflr->addr;
1348                 if (sa->sa_family != AF_INET6)
1349                         return EINVAL;
1350                 if (sa->sa_len != sizeof(struct sockaddr_in6))
1351                         return EINVAL;
1352                 /* XXX need improvement */
1353                 sa = (struct sockaddr *)&iflr->dstaddr;
1354                 if (sa->sa_family && sa->sa_family != AF_INET6)
1355                         return EINVAL;
1356                 if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1357                         return EINVAL;
1358                 break;
1359         default: /* shouldn't happen */
1360 #if 0
1361                 panic("invalid cmd to in6_lifaddr_ioctl");
1362                 /* NOTREACHED */
1363 #else
1364                 return EOPNOTSUPP;
1365 #endif
1366         }
1367         if (sizeof(struct in6_addr) * 8 < iflr->prefixlen)
1368                 return EINVAL;
1369
1370         switch (cmd) {
1371         case SIOCALIFADDR:
1372             {
1373                 struct in6_aliasreq ifra;
1374                 struct in6_addr *hostid = NULL;
1375                 int prefixlen;
1376
1377                 if (iflr->flags & IFLR_PREFIX) {
1378                         struct ifaddr *ifa;
1379                         struct sockaddr_in6 *sin6;
1380
1381                         /*
1382                          * hostid is to fill in the hostid part of the
1383                          * address.  hostid points to the first link-local
1384                          * address attached to the interface.
1385                          */
1386                         ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);
1387                         if (!ifa)
1388                                 return EADDRNOTAVAIL;
1389                         hostid = IFA_IN6(ifa);
1390
1391                         /* prefixlen must be <= 64. */
1392                         if (64 < iflr->prefixlen)
1393                                 return EINVAL;
1394                         prefixlen = iflr->prefixlen;
1395
1396                         /* hostid part must be zero. */
1397                         sin6 = (struct sockaddr_in6 *)&iflr->addr;
1398                         if (sin6->sin6_addr.s6_addr32[2] != 0
1399                          || sin6->sin6_addr.s6_addr32[3] != 0) {
1400                                 return EINVAL;
1401                         }
1402                 } else
1403                         prefixlen = iflr->prefixlen;
1404
1405                 /* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1406                 bzero(&ifra, sizeof(ifra));
1407                 bcopy(iflr->iflr_name, ifra.ifra_name,
1408                         sizeof(ifra.ifra_name));
1409
1410                 bcopy(&iflr->addr, &ifra.ifra_addr,
1411                         ((struct sockaddr *)&iflr->addr)->sa_len);
1412                 if (hostid) {
1413                         /* fill in hostid part */
1414                         ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1415                                 hostid->s6_addr32[2];
1416                         ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1417                                 hostid->s6_addr32[3];
1418                 }
1419
1420                 if (((struct sockaddr *)&iflr->dstaddr)->sa_family) {   /*XXX*/
1421                         bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
1422                                 ((struct sockaddr *)&iflr->dstaddr)->sa_len);
1423                         if (hostid) {
1424                                 ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1425                                         hostid->s6_addr32[2];
1426                                 ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1427                                         hostid->s6_addr32[3];
1428                         }
1429                 }
1430
1431                 ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1432                 in6_len2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1433
1434                 ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1435                 return in6_control(so, SIOCAIFADDR_IN6, (caddr_t)&ifra, ifp, td);
1436             }
1437         case SIOCGLIFADDR:
1438         case SIOCDLIFADDR:
1439             {
1440                 struct ifaddr_container *ifac;
1441                 struct in6_ifaddr *ia;
1442                 struct in6_addr mask, candidate, match;
1443                 struct sockaddr_in6 *sin6;
1444                 int cmp;
1445
1446                 bzero(&mask, sizeof(mask));
1447                 if (iflr->flags & IFLR_PREFIX) {
1448                         /* lookup a prefix rather than address. */
1449                         in6_len2mask(&mask, iflr->prefixlen);
1450
1451                         sin6 = (struct sockaddr_in6 *)&iflr->addr;
1452                         bcopy(&sin6->sin6_addr, &match, sizeof(match));
1453                         match.s6_addr32[0] &= mask.s6_addr32[0];
1454                         match.s6_addr32[1] &= mask.s6_addr32[1];
1455                         match.s6_addr32[2] &= mask.s6_addr32[2];
1456                         match.s6_addr32[3] &= mask.s6_addr32[3];
1457
1458                         /* if you set extra bits, that's wrong */
1459                         if (bcmp(&match, &sin6->sin6_addr, sizeof(match)))
1460                                 return EINVAL;
1461
1462                         cmp = 1;
1463                 } else {
1464                         if (cmd == SIOCGLIFADDR) {
1465                                 /* on getting an address, take the 1st match */
1466                                 cmp = 0;        /* XXX */
1467                         } else {
1468                                 /* on deleting an address, do exact match */
1469                                 in6_len2mask(&mask, 128);
1470                                 sin6 = (struct sockaddr_in6 *)&iflr->addr;
1471                                 bcopy(&sin6->sin6_addr, &match, sizeof(match));
1472
1473                                 cmp = 1;
1474                         }
1475                 }
1476
1477                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1478                         struct ifaddr *ifa = ifac->ifa;
1479
1480                         if (ifa->ifa_addr->sa_family != AF_INET6)
1481                                 continue;
1482                         if (!cmp)
1483                                 break;
1484
1485                         bcopy(IFA_IN6(ifa), &candidate, sizeof(candidate));
1486                         /*
1487                          * XXX: this is adhoc, but is necessary to allow
1488                          * a user to specify fe80::/64 (not /10) for a
1489                          * link-local address.
1490                          */
1491                         if (IN6_IS_ADDR_LINKLOCAL(&candidate))
1492                                 candidate.s6_addr16[1] = 0;
1493                         candidate.s6_addr32[0] &= mask.s6_addr32[0];
1494                         candidate.s6_addr32[1] &= mask.s6_addr32[1];
1495                         candidate.s6_addr32[2] &= mask.s6_addr32[2];
1496                         candidate.s6_addr32[3] &= mask.s6_addr32[3];
1497                         if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1498                                 break;
1499                 }
1500                 if (ifac == NULL)
1501                         return EADDRNOTAVAIL;
1502                 ia = ifa2ia6(ifac->ifa);
1503
1504                 if (cmd == SIOCGLIFADDR) {
1505                         struct sockaddr_in6 *s6;
1506
1507                         /* fill in the if_laddrreq structure */
1508                         bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin6_len);
1509                         s6 = (struct sockaddr_in6 *)&iflr->addr;
1510                         if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1511                                 s6->sin6_addr.s6_addr16[1] = 0;
1512                                 s6->sin6_scope_id =
1513                                         in6_addr2scopeid(ifp, &s6->sin6_addr);
1514                         }
1515                         if (ifp->if_flags & IFF_POINTOPOINT) {
1516                                 bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
1517                                         ia->ia_dstaddr.sin6_len);
1518                                 s6 = (struct sockaddr_in6 *)&iflr->dstaddr;
1519                                 if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1520                                         s6->sin6_addr.s6_addr16[1] = 0;
1521                                         s6->sin6_scope_id =
1522                                                 in6_addr2scopeid(ifp,
1523                                                                  &s6->sin6_addr);
1524                                 }
1525                         } else
1526                                 bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
1527
1528                         iflr->prefixlen =
1529                                 in6_mask2len(&ia->ia_prefixmask.sin6_addr,
1530                                              NULL);
1531
1532                         iflr->flags = ia->ia6_flags;    /* XXX */
1533
1534                         return 0;
1535                 } else {
1536                         struct in6_aliasreq ifra;
1537
1538                         /* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1539                         bzero(&ifra, sizeof(ifra));
1540                         bcopy(iflr->iflr_name, ifra.ifra_name,
1541                               sizeof(ifra.ifra_name));
1542
1543                         bcopy(&ia->ia_addr, &ifra.ifra_addr,
1544                               ia->ia_addr.sin6_len);
1545                         if (ifp->if_flags & IFF_POINTOPOINT)
1546                                 bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
1547                                       ia->ia_dstaddr.sin6_len);
1548                         else
1549                                 bzero(&ifra.ifra_dstaddr,
1550                                       sizeof(ifra.ifra_dstaddr));
1551                         bcopy(&ia->ia_prefixmask, &ifra.ifra_dstaddr,
1552                               ia->ia_prefixmask.sin6_len);
1553
1554                         ifra.ifra_flags = ia->ia6_flags;
1555                         return in6_control(so, SIOCDIFADDR_IN6, (caddr_t)&ifra,
1556                                 ifp, td);
1557                 }
1558             }
1559         }
1560
1561         return EOPNOTSUPP;      /* just for safety */
1562 }
1563
1564 /*
1565  * Initialize an interface's intetnet6 address
1566  * and routing table entry.
1567  */
1568 static int
1569 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia, struct sockaddr_in6 *sin6,
1570            int newhost)
1571 {
1572         int     error = 0, plen, ifacount = 0;
1573         struct ifaddr_container *ifac;
1574
1575         /*
1576          * Give the interface a chance to initialize
1577          * if this is its first address,
1578          * and to validate the address if necessary.
1579          */
1580         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1581                 if (ifac->ifa->ifa_addr == NULL)
1582                         continue;       /* just for safety */
1583                 if (ifac->ifa->ifa_addr->sa_family != AF_INET6)
1584                         continue;
1585                 ifacount++;
1586         }
1587
1588         lwkt_serialize_enter(ifp->if_serializer);
1589
1590         ia->ia_addr = *sin6;
1591
1592         if (ifacount <= 1 && ifp->if_ioctl &&
1593             (error = ifp->if_ioctl(ifp, SIOCSIFADDR, (caddr_t)ia, NULL))) {
1594                 lwkt_serialize_exit(ifp->if_serializer);
1595                 return (error);
1596         }
1597         lwkt_serialize_exit(ifp->if_serializer);
1598
1599         ia->ia_ifa.ifa_metric = ifp->if_metric;
1600
1601         /* we could do in(6)_socktrim here, but just omit it at this moment. */
1602
1603         /*
1604          * Special case:
1605          * If the destination address is specified for a point-to-point
1606          * interface, install a route to the destination as an interface
1607          * direct route.
1608          */
1609         plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1610         if (plen == 128 && ia->ia_dstaddr.sin6_family == AF_INET6) {
1611                 if ((error = rtinit(&(ia->ia_ifa), (int)RTM_ADD,
1612                                     RTF_UP | RTF_HOST)) != 0)
1613                         return (error);
1614                 ia->ia_flags |= IFA_ROUTE;
1615         }
1616         if (plen < 128) {
1617                 /*
1618                  * The RTF_CLONING flag is necessary for in6_is_ifloop_auto().
1619                  */
1620                 ia->ia_ifa.ifa_flags |= RTF_CLONING;
1621         }
1622
1623         /* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1624         if (newhost) {
1625                 /* set the rtrequest function to create llinfo */
1626                 ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1627                 in6_ifaddloop(&(ia->ia_ifa));
1628         }
1629
1630         return (error);
1631 }
1632
1633 struct in6_multi_mship *
1634 in6_joingroup(struct ifnet *ifp, struct in6_addr *addr, int *errorp)
1635 {
1636        struct in6_multi_mship *imm;
1637
1638        imm = kmalloc(sizeof(*imm), M_IPMADDR, M_NOWAIT);
1639        if (!imm) {
1640                *errorp = ENOBUFS;
1641                return NULL;
1642        }
1643        imm->i6mm_maddr = in6_addmulti(addr, ifp, errorp);
1644        if (!imm->i6mm_maddr) {
1645                /* *errorp is alrady set */
1646                kfree(imm, M_IPMADDR);
1647                return NULL;
1648        }
1649        return imm;
1650 }
1651
1652 int
1653 in6_leavegroup(struct in6_multi_mship *imm)
1654 {
1655
1656        if (imm->i6mm_maddr)
1657                in6_delmulti(imm->i6mm_maddr);
1658        kfree(imm,  M_IPMADDR);
1659        return 0;
1660 }
1661
1662 /*
1663  * Add an address to the list of IP6 multicast addresses for a
1664  * given interface.
1665  */
1666 struct  in6_multi *
1667 in6_addmulti(struct in6_addr *maddr6, struct ifnet *ifp, int *errorp)
1668 {
1669         struct  in6_multi *in6m;
1670         struct sockaddr_in6 sin6;
1671         struct ifmultiaddr *ifma;
1672
1673         *errorp = 0;
1674
1675         crit_enter();
1676
1677         /*
1678          * Call generic routine to add membership or increment
1679          * refcount.  It wants addresses in the form of a sockaddr,
1680          * so we build one here (being careful to zero the unused bytes).
1681          */
1682         bzero(&sin6, sizeof sin6);
1683         sin6.sin6_family = AF_INET6;
1684         sin6.sin6_len = sizeof sin6;
1685         sin6.sin6_addr = *maddr6;
1686         *errorp = if_addmulti(ifp, (struct sockaddr *)&sin6, &ifma);
1687         if (*errorp) {
1688                 crit_exit();
1689                 return 0;
1690         }
1691
1692         /*
1693          * If ifma->ifma_protospec is null, then if_addmulti() created
1694          * a new record.  Otherwise, we are done.
1695          */
1696         if (ifma->ifma_protospec != 0) {
1697                 crit_exit();
1698                 return ifma->ifma_protospec;
1699         }
1700
1701         /* XXX - if_addmulti uses M_WAITOK.  Can this really be called
1702            at interrupt time?  If so, need to fix if_addmulti. XXX */
1703         in6m = (struct in6_multi *)kmalloc(sizeof(*in6m), M_IPMADDR, M_NOWAIT);
1704         if (in6m == NULL) {
1705                 crit_exit();
1706                 return (NULL);
1707         }
1708
1709         bzero(in6m, sizeof *in6m);
1710         in6m->in6m_addr = *maddr6;
1711         in6m->in6m_ifp = ifp;
1712         in6m->in6m_ifma = ifma;
1713         ifma->ifma_protospec = in6m;
1714         LIST_INSERT_HEAD(&in6_multihead, in6m, in6m_entry);
1715
1716         /*
1717          * Let MLD6 know that we have joined a new IP6 multicast
1718          * group.
1719          */
1720         mld6_start_listening(in6m);
1721         crit_exit();
1722         return (in6m);
1723 }
1724
1725 /*
1726  * Delete a multicast address record.
1727  */
1728 void
1729 in6_delmulti(struct in6_multi *in6m)
1730 {
1731         struct ifmultiaddr *ifma = in6m->in6m_ifma;
1732
1733         crit_enter();
1734
1735         if (ifma->ifma_refcount == 1) {
1736                 /*
1737                  * No remaining claims to this record; let MLD6 know
1738                  * that we are leaving the multicast group.
1739                  */
1740                 mld6_stop_listening(in6m);
1741                 ifma->ifma_protospec = 0;
1742                 LIST_REMOVE(in6m, in6m_entry);
1743                 kfree(in6m, M_IPMADDR);
1744         }
1745         /* XXX - should be separate API for when we have an ifma? */
1746         if_delmulti(ifma->ifma_ifp, ifma->ifma_addr);
1747         crit_exit();
1748 }
1749
1750 /*
1751  * Find an IPv6 interface link-local address specific to an interface.
1752  */
1753 struct in6_ifaddr *
1754 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
1755 {
1756         struct ifaddr_container *ifac;
1757
1758         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1759                 struct ifaddr *ifa = ifac->ifa;
1760
1761                 if (ifa->ifa_addr == NULL)
1762                         continue;       /* just for safety */
1763                 if (ifa->ifa_addr->sa_family != AF_INET6)
1764                         continue;
1765                 if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1766                         if ((((struct in6_ifaddr *)ifa)->ia6_flags &
1767                              ignoreflags) != 0)
1768                                 continue;
1769                         break;
1770                 }
1771         }
1772         if (ifac != NULL)
1773                 return ((struct in6_ifaddr *)(ifac->ifa));
1774         else
1775                 return (NULL);
1776 }
1777
1778
1779 /*
1780  * find the internet address corresponding to a given interface and address.
1781  */
1782 struct in6_ifaddr *
1783 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
1784 {
1785         struct ifaddr_container *ifac;
1786
1787         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1788                 struct ifaddr *ifa = ifac->ifa;
1789
1790                 if (ifa->ifa_addr == NULL)
1791                         continue;       /* just for safety */
1792                 if (ifa->ifa_addr->sa_family != AF_INET6)
1793                         continue;
1794                 if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
1795                         break;
1796         }
1797         if (ifac != NULL)
1798                 return ((struct in6_ifaddr *)(ifac->ifa));
1799         else
1800                 return (NULL);
1801 }
1802
1803 /*
1804  * find the internet address on a given interface corresponding to a neighbor's
1805  * address.
1806  */
1807 struct in6_ifaddr *
1808 in6ifa_ifplocaladdr(const struct ifnet *ifp, const struct in6_addr *addr)
1809 {
1810         struct ifaddr *ifa;
1811         struct in6_ifaddr *ia;
1812         struct ifaddr_container *ifac;
1813
1814         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
1815                 ifa = ifac->ifa;
1816
1817                 if (ifa->ifa_addr == NULL)
1818                         continue;       /* just for safety */
1819                 if (ifa->ifa_addr->sa_family != AF_INET6)
1820                         continue;
1821                 ia = (struct in6_ifaddr *)ifa;
1822                 if (IN6_ARE_MASKED_ADDR_EQUAL(addr,
1823                                 &ia->ia_addr.sin6_addr,
1824                                 &ia->ia_prefixmask.sin6_addr))
1825                         return ia;
1826         }
1827
1828         return NULL;
1829 }
1830
1831 /*
1832  * Convert IP6 address to printable (loggable) representation.
1833  */
1834 static char digits[] = "0123456789abcdef";
1835 static int ip6round = 0;
1836 char *
1837 ip6_sprintf(const struct in6_addr *addr)
1838 {
1839         static char ip6buf[8][48];
1840         int i;
1841         char *cp;
1842         const u_short *a = (const u_short *)addr;
1843         const u_char *d;
1844         int dcolon = 0;
1845
1846         ip6round = (ip6round + 1) & 7;
1847         cp = ip6buf[ip6round];
1848
1849         for (i = 0; i < 8; i++) {
1850                 if (dcolon == 1) {
1851                         if (*a == 0) {
1852                                 if (i == 7)
1853                                         *cp++ = ':';
1854                                 a++;
1855                                 continue;
1856                         } else
1857                                 dcolon = 2;
1858                 }
1859                 if (*a == 0) {
1860                         if (dcolon == 0 && *(a + 1) == 0) {
1861                                 if (i == 0)
1862                                         *cp++ = ':';
1863                                 *cp++ = ':';
1864                                 dcolon = 1;
1865                         } else {
1866                                 *cp++ = '0';
1867                                 *cp++ = ':';
1868                         }
1869                         a++;
1870                         continue;
1871                 }
1872                 d = (const u_char *)a;
1873                 *cp++ = digits[*d >> 4];
1874                 *cp++ = digits[*d++ & 0xf];
1875                 *cp++ = digits[*d >> 4];
1876                 *cp++ = digits[*d & 0xf];
1877                 *cp++ = ':';
1878                 a++;
1879         }
1880         *--cp = 0;
1881         return (ip6buf[ip6round]);
1882 }
1883
1884 int
1885 in6_localaddr(struct in6_addr *in6)
1886 {
1887         struct in6_ifaddr *ia;
1888
1889         if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
1890                 return 1;
1891
1892         for (ia = in6_ifaddr; ia; ia = ia->ia_next)
1893                 if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
1894                                               &ia->ia_prefixmask.sin6_addr))
1895                         return 1;
1896
1897         return (0);
1898 }
1899
1900 int
1901 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
1902 {
1903         struct in6_ifaddr *ia;
1904
1905         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1906                 if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
1907                                        &sa6->sin6_addr) &&
1908                     (ia->ia6_flags & IN6_IFF_DEPRECATED))
1909                         return (1); /* true */
1910
1911                 /* XXX: do we still have to go thru the rest of the list? */
1912         }
1913
1914         return (0);             /* false */
1915 }
1916
1917 /*
1918  * return length of part which dst and src are equal
1919  * hard coding...
1920  */
1921 int
1922 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
1923 {
1924         int match = 0;
1925         u_char *s = (u_char *)src, *d = (u_char *)dst;
1926         u_char *lim = s + 16, r;
1927
1928         while (s < lim)
1929                 if ((r = (*d++ ^ *s++)) != 0) {
1930                         while (r < 128) {
1931                                 match++;
1932                                 r <<= 1;
1933                         }
1934                         break;
1935                 } else
1936                         match += 8;
1937         return match;
1938 }
1939
1940 /* XXX: to be scope conscious */
1941 int
1942 in6_are_prefix_equal(struct in6_addr *p1, struct in6_addr *p2, int len)
1943 {
1944         int bytelen, bitlen;
1945
1946         /* sanity check */
1947         if (0 > len || len > 128) {
1948                 log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
1949                     len);
1950                 return (0);
1951         }
1952
1953         bytelen = len / 8;
1954         bitlen = len % 8;
1955
1956         if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
1957                 return (0);
1958         if (p1->s6_addr[bytelen] >> (8 - bitlen) !=
1959             p2->s6_addr[bytelen] >> (8 - bitlen))
1960                 return (0);
1961
1962         return (1);
1963 }
1964
1965 void
1966 in6_prefixlen2mask(struct in6_addr *maskp, int len)
1967 {
1968         u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
1969         int bytelen, bitlen, i;
1970
1971         /* sanity check */
1972         if (0 > len || len > 128) {
1973                 log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
1974                     len);
1975                 return;
1976         }
1977
1978         bzero(maskp, sizeof(*maskp));
1979         bytelen = len / 8;
1980         bitlen = len % 8;
1981         for (i = 0; i < bytelen; i++)
1982                 maskp->s6_addr[i] = 0xff;
1983         if (bitlen)
1984                 maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
1985 }
1986
1987 /*
1988  * return the best address out of the same scope
1989  */
1990 struct in6_ifaddr *
1991 in6_ifawithscope(struct ifnet *oifp, struct in6_addr *dst)
1992 {
1993         int dst_scope = in6_addrscope(dst), src_scope, best_scope = 0;
1994         int blen = -1;
1995         struct ifnet *ifp;
1996         struct in6_ifaddr *ifa_best = NULL;
1997
1998         if (oifp == NULL) {
1999 #if 0
2000                 kprintf("in6_ifawithscope: output interface is not specified\n");
2001 #endif
2002                 return (NULL);
2003         }
2004
2005         /*
2006          * We search for all addresses on all interfaces from the beginning.
2007          * Comparing an interface with the outgoing interface will be done
2008          * only at the final stage of tiebreaking.
2009          */
2010         for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2011         {
2012                 struct ifaddr_container *ifac;
2013
2014                 /*
2015                  * We can never take an address that breaks the scope zone
2016                  * of the destination.
2017                  */
2018                 if (in6_addr2scopeid(ifp, dst) != in6_addr2scopeid(oifp, dst))
2019                         continue;
2020
2021                 TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2022                         int tlen = -1, dscopecmp, bscopecmp, matchcmp;
2023                         struct ifaddr *ifa = ifac->ifa;
2024
2025                         if (ifa->ifa_addr->sa_family != AF_INET6)
2026                                 continue;
2027
2028                         src_scope = in6_addrscope(IFA_IN6(ifa));
2029
2030                         /*
2031                          * Don't use an address before completing DAD
2032                          * nor a duplicated address.
2033                          */
2034                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
2035                             IN6_IFF_NOTREADY)
2036                                 continue;
2037
2038                         /* XXX: is there any case to allow anycasts? */
2039                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
2040                             IN6_IFF_ANYCAST)
2041                                 continue;
2042
2043                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
2044                             IN6_IFF_DETACHED)
2045                                 continue;
2046
2047                         /*
2048                          * If this is the first address we find,
2049                          * keep it anyway.
2050                          */
2051                         if (ifa_best == NULL)
2052                                 goto replace;
2053
2054                         /*
2055                          * ifa_best is never NULL beyond this line except
2056                          * within the block labeled "replace".
2057                          */
2058
2059                         /*
2060                          * If ifa_best has a smaller scope than dst and
2061                          * the current address has a larger one than
2062                          * (or equal to) dst, always replace ifa_best.
2063                          * Also, if the current address has a smaller scope
2064                          * than dst, ignore it unless ifa_best also has a
2065                          * smaller scope.
2066                          * Consequently, after the two if-clause below,
2067                          * the followings must be satisfied:
2068                          * (scope(src) < scope(dst) &&
2069                          *  scope(best) < scope(dst))
2070                          *  OR
2071                          * (scope(best) >= scope(dst) &&
2072                          *  scope(src) >= scope(dst))
2073                          */
2074                         if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0 &&
2075                             IN6_ARE_SCOPE_CMP(src_scope, dst_scope) >= 0)
2076                                 goto replace; /* (A) */
2077                         if (IN6_ARE_SCOPE_CMP(src_scope, dst_scope) < 0 &&
2078                             IN6_ARE_SCOPE_CMP(best_scope, dst_scope) >= 0)
2079                                 continue; /* (B) */
2080
2081                         /*
2082                          * A deprecated address SHOULD NOT be used in new
2083                          * communications if an alternate (non-deprecated)
2084                          * address is available and has sufficient scope.
2085                          * RFC 2462, Section 5.5.4.
2086                          */
2087                         if (((struct in6_ifaddr *)ifa)->ia6_flags &
2088                             IN6_IFF_DEPRECATED) {
2089                                 /*
2090                                  * Ignore any deprecated addresses if
2091                                  * specified by configuration.
2092                                  */
2093                                 if (!ip6_use_deprecated)
2094                                         continue;
2095
2096                                 /*
2097                                  * If we have already found a non-deprecated
2098                                  * candidate, just ignore deprecated addresses.
2099                                  */
2100                                 if (!(ifa_best->ia6_flags & IN6_IFF_DEPRECATED))
2101                                         continue;
2102                         }
2103
2104                         /*
2105                          * A non-deprecated address is always preferred
2106                          * to a deprecated one regardless of scopes and
2107                          * address matching (Note invariants ensured by the
2108                          * conditions (A) and (B) above.)
2109                          */
2110                         if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) &&
2111                             !(((struct in6_ifaddr *)ifa)->ia6_flags &
2112                              IN6_IFF_DEPRECATED))
2113                                 goto replace;
2114
2115                         /*
2116                          * When we use temporary addresses described in
2117                          * RFC 3041, we prefer temporary addresses to
2118                          * public autoconf addresses.  Again, note the
2119                          * invariants from (A) and (B).  Also note that we
2120                          * don't have any preference between static addresses
2121                          * and autoconf addresses (despite of whether or not
2122                          * the latter is temporary or public.)
2123                          */
2124                         if (ip6_use_tempaddr) {
2125                                 struct in6_ifaddr *ifat;
2126
2127                                 ifat = (struct in6_ifaddr *)ifa;
2128                                 if ((ifa_best->ia6_flags &
2129                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2130                                      == IN6_IFF_AUTOCONF &&
2131                                     (ifat->ia6_flags &
2132                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2133                                      == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY)) {
2134                                         goto replace;
2135                                 }
2136                                 if ((ifa_best->ia6_flags &
2137                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2138                                     == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY) &&
2139                                     (ifat->ia6_flags &
2140                                      (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2141                                      == IN6_IFF_AUTOCONF) {
2142                                         continue;
2143                                 }
2144                         }
2145
2146                         /*
2147                          * At this point, we have two cases:
2148                          * 1. we are looking at a non-deprecated address,
2149                          *    and ifa_best is also non-deprecated.
2150                          * 2. we are looking at a deprecated address,
2151                          *    and ifa_best is also deprecated.
2152                          * Also, we do not have to consider a case where
2153                          * the scope of if_best is larger(smaller) than dst and
2154                          * the scope of the current address is smaller(larger)
2155                          * than dst. Such a case has already been covered.
2156                          * Tiebreaking is done according to the following
2157                          * items:
2158                          * - the scope comparison between the address and
2159                          *   dst (dscopecmp)
2160                          * - the scope comparison between the address and
2161                          *   ifa_best (bscopecmp)
2162                          * - if the address match dst longer than ifa_best
2163                          *   (matchcmp)
2164                          * - if the address is on the outgoing I/F (outI/F)
2165                          *
2166                          * Roughly speaking, the selection policy is
2167                          * - the most important item is scope. The same scope
2168                          *   is best. Then search for a larger scope.
2169                          *   Smaller scopes are the last resort.
2170                          * - A deprecated address is chosen only when we have
2171                          *   no address that has an enough scope, but is
2172                          *   prefered to any addresses of smaller scopes
2173                          *   (this must be already done above.)
2174                          * - addresses on the outgoing I/F are preferred to
2175                          *   ones on other interfaces if none of above
2176                          *   tiebreaks.  In the table below, the column "bI"
2177                          *   means if the best_ifa is on the outgoing
2178                          *   interface, and the column "sI" means if the ifa
2179                          *   is on the outgoing interface.
2180                          * - If there is no other reasons to choose one,
2181                          *   longest address match against dst is considered.
2182                          *
2183                          * The precise decision table is as follows:
2184                          * dscopecmp bscopecmp    match  bI oI | replace?
2185                          *       N/A     equal      N/A   Y  N |   No (1)
2186                          *       N/A     equal      N/A   N  Y |  Yes (2)
2187                          *       N/A     equal   larger    N/A |  Yes (3)
2188                          *       N/A     equal  !larger    N/A |   No (4)
2189                          *    larger    larger      N/A    N/A |   No (5)
2190                          *    larger   smaller      N/A    N/A |  Yes (6)
2191                          *   smaller    larger      N/A    N/A |  Yes (7)
2192                          *   smaller   smaller      N/A    N/A |   No (8)
2193                          *     equal   smaller      N/A    N/A |  Yes (9)
2194                          *     equal    larger       (already done at A above)
2195                          */
2196                         dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
2197                         bscopecmp = IN6_ARE_SCOPE_CMP(src_scope, best_scope);
2198
2199                         if (bscopecmp == 0) {
2200                                 struct ifnet *bifp = ifa_best->ia_ifp;
2201
2202                                 if (bifp == oifp && ifp != oifp) /* (1) */
2203                                         continue;
2204                                 if (bifp != oifp && ifp == oifp) /* (2) */
2205                                         goto replace;
2206
2207                                 /*
2208                                  * Both bifp and ifp are on the outgoing
2209                                  * interface, or both two are on a different
2210                                  * interface from the outgoing I/F.
2211                                  * now we need address matching against dst
2212                                  * for tiebreaking.
2213                                  */
2214                                 tlen = in6_matchlen(IFA_IN6(ifa), dst);
2215                                 matchcmp = tlen - blen;
2216                                 if (matchcmp > 0) /* (3) */
2217                                         goto replace;
2218                                 continue; /* (4) */
2219                         }
2220                         if (dscopecmp > 0) {
2221                                 if (bscopecmp > 0) /* (5) */
2222                                         continue;
2223                                 goto replace; /* (6) */
2224                         }
2225                         if (dscopecmp < 0) {
2226                                 if (bscopecmp > 0) /* (7) */
2227                                         goto replace;
2228                                 continue; /* (8) */
2229                         }
2230
2231                         /* now dscopecmp must be 0 */
2232                         if (bscopecmp < 0)
2233                                 goto replace; /* (9) */
2234
2235                   replace:
2236                         ifa_best = (struct in6_ifaddr *)ifa;
2237                         blen = tlen >= 0 ? tlen :
2238                                 in6_matchlen(IFA_IN6(ifa), dst);
2239                         best_scope = in6_addrscope(&ifa_best->ia_addr.sin6_addr);
2240                 }
2241         }
2242
2243         /* count statistics for future improvements */
2244         if (ifa_best == NULL)
2245                 ip6stat.ip6s_sources_none++;
2246         else {
2247                 if (oifp == ifa_best->ia_ifp)
2248                         ip6stat.ip6s_sources_sameif[best_scope]++;
2249                 else
2250                         ip6stat.ip6s_sources_otherif[best_scope]++;
2251
2252                 if (best_scope == dst_scope)
2253                         ip6stat.ip6s_sources_samescope[best_scope]++;
2254                 else
2255                         ip6stat.ip6s_sources_otherscope[best_scope]++;
2256
2257                 if (ifa_best->ia6_flags & IN6_IFF_DEPRECATED)
2258                         ip6stat.ip6s_sources_deprecated[best_scope]++;
2259         }
2260
2261         return (ifa_best);
2262 }
2263
2264 /*
2265  * return the best address out of the same scope. if no address was
2266  * found, return the first valid address from designated IF.
2267  */
2268 struct in6_ifaddr *
2269 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
2270 {
2271         int dst_scope = in6_addrscope(dst), blen = -1, tlen;
2272         struct ifaddr_container *ifac;
2273         struct in6_ifaddr *besta = 0;
2274         struct in6_ifaddr *dep[2];      /* last-resort: deprecated */
2275
2276         dep[0] = dep[1] = NULL;
2277
2278         /*
2279          * We first look for addresses in the same scope.
2280          * If there is one, return it.
2281          * If two or more, return one which matches the dst longest.
2282          * If none, return one of global addresses assigned other ifs.
2283          */
2284         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2285                 struct ifaddr *ifa = ifac->ifa;
2286
2287                 if (ifa->ifa_addr->sa_family != AF_INET6)
2288                         continue;
2289                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2290                         continue; /* XXX: is there any case to allow anycast? */
2291                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2292                         continue; /* don't use this interface */
2293                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2294                         continue;
2295                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2296                         if (ip6_use_deprecated)
2297                                 dep[0] = (struct in6_ifaddr *)ifa;
2298                         continue;
2299                 }
2300
2301                 if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
2302                         /*
2303                          * call in6_matchlen() as few as possible
2304                          */
2305                         if (besta) {
2306                                 if (blen == -1)
2307                                         blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
2308                                 tlen = in6_matchlen(IFA_IN6(ifa), dst);
2309                                 if (tlen > blen) {
2310                                         blen = tlen;
2311                                         besta = (struct in6_ifaddr *)ifa;
2312                                 }
2313                         } else
2314                                 besta = (struct in6_ifaddr *)ifa;
2315                 }
2316         }
2317         if (besta)
2318                 return (besta);
2319
2320         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2321                 struct ifaddr *ifa = ifac->ifa;
2322
2323                 if (ifa->ifa_addr->sa_family != AF_INET6)
2324                         continue;
2325                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2326                         continue; /* XXX: is there any case to allow anycast? */
2327                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2328                         continue; /* don't use this interface */
2329                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2330                         continue;
2331                 if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2332                         if (ip6_use_deprecated)
2333                                 dep[1] = (struct in6_ifaddr *)ifa;
2334                         continue;
2335                 }
2336
2337                 return (struct in6_ifaddr *)ifa;
2338         }
2339
2340         /* use the last-resort values, that are, deprecated addresses */
2341         if (dep[0])
2342                 return dep[0];
2343         if (dep[1])
2344                 return dep[1];
2345
2346         return NULL;
2347 }
2348
2349 /*
2350  * perform DAD when interface becomes IFF_UP.
2351  */
2352 void
2353 in6_if_up(struct ifnet *ifp)
2354 {
2355         struct ifaddr_container *ifac;
2356         struct in6_ifaddr *ia;
2357         int dad_delay;          /* delay ticks before DAD output */
2358
2359         /*
2360          * special cases, like 6to4, are handled in in6_ifattach
2361          */
2362         in6_ifattach(ifp, NULL);
2363
2364         dad_delay = 0;
2365         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2366                 struct ifaddr *ifa = ifac->ifa;
2367
2368                 if (ifa->ifa_addr->sa_family != AF_INET6)
2369                         continue;
2370                 ia = (struct in6_ifaddr *)ifa;
2371                 if (ia->ia6_flags & IN6_IFF_TENTATIVE)
2372                         nd6_dad_start(ifa, &dad_delay);
2373         }
2374 }
2375
2376 int
2377 in6if_do_dad(struct ifnet *ifp)
2378 {
2379         if (ifp->if_flags & IFF_LOOPBACK)
2380                 return (0);
2381
2382         switch (ifp->if_type) {
2383 #ifdef IFT_DUMMY
2384         case IFT_DUMMY:
2385 #endif
2386         case IFT_FAITH:
2387                 /*
2388                  * These interfaces do not have the IFF_LOOPBACK flag,
2389                  * but loop packets back.  We do not have to do DAD on such
2390                  * interfaces.  We should even omit it, because loop-backed
2391                  * NS would confuse the DAD procedure.
2392                  */
2393                 return (0);
2394         default:
2395                 /*
2396                  * Our DAD routine requires the interface up and running.
2397                  * However, some interfaces can be up before the RUNNING
2398                  * status.  Additionaly, users may try to assign addresses
2399                  * before the interface becomes up (or running).
2400                  * We simply skip DAD in such a case as a work around.
2401                  * XXX: we should rather mark "tentative" on such addresses,
2402                  * and do DAD after the interface becomes ready.
2403                  */
2404                 if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) !=
2405                     (IFF_UP|IFF_RUNNING))
2406                         return (0);
2407
2408                 return (1);
2409         }
2410 }
2411
2412 /*
2413  * Calculate max IPv6 MTU through all the interfaces and store it
2414  * to in6_maxmtu.
2415  */
2416 void
2417 in6_setmaxmtu(void)
2418 {
2419         unsigned long maxmtu = 0;
2420         struct ifnet *ifp;
2421
2422         for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2423         {
2424                 if (!(ifp->if_flags & IFF_LOOPBACK) &&
2425                     ND_IFINFO(ifp)->linkmtu > maxmtu)
2426                         maxmtu =  ND_IFINFO(ifp)->linkmtu;
2427         }
2428         if (maxmtu)     /* update only when maxmtu is positive */
2429                 in6_maxmtu = maxmtu;
2430 }
2431
2432 void *
2433 in6_domifattach(struct ifnet *ifp)
2434 {
2435         struct in6_ifextra *ext;
2436
2437         ext = (struct in6_ifextra *)kmalloc(sizeof(*ext), M_IFADDR, M_WAITOK);
2438         bzero(ext, sizeof(*ext));
2439
2440         ext->in6_ifstat = (struct in6_ifstat *)kmalloc(sizeof(struct in6_ifstat),
2441                 M_IFADDR, M_WAITOK);
2442         bzero(ext->in6_ifstat, sizeof(*ext->in6_ifstat));
2443
2444         ext->icmp6_ifstat =
2445                 (struct icmp6_ifstat *)kmalloc(sizeof(struct icmp6_ifstat),
2446                         M_IFADDR, M_WAITOK);
2447         bzero(ext->icmp6_ifstat, sizeof(*ext->icmp6_ifstat));
2448
2449         ext->nd_ifinfo = nd6_ifattach(ifp);
2450         ext->scope6_id = scope6_ifattach(ifp);
2451         return ext;
2452 }
2453
2454 void
2455 in6_domifdetach(struct ifnet *ifp, void *aux)
2456 {
2457         struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2458         scope6_ifdetach(ext->scope6_id);
2459         nd6_ifdetach(ext->nd_ifinfo);
2460         kfree(ext->in6_ifstat, M_IFADDR);
2461         kfree(ext->icmp6_ifstat, M_IFADDR);
2462         kfree(ext, M_IFADDR);
2463 }
2464
2465 /*
2466  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2467  * v4 mapped addr or v4 compat addr
2468  */
2469 void
2470 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2471 {
2472         bzero(sin, sizeof(*sin));
2473         sin->sin_len = sizeof(struct sockaddr_in);
2474         sin->sin_family = AF_INET;
2475         sin->sin_port = sin6->sin6_port;
2476         sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
2477 }
2478
2479 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2480 void
2481 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2482 {
2483         bzero(sin6, sizeof(*sin6));
2484         sin6->sin6_len = sizeof(struct sockaddr_in6);
2485         sin6->sin6_family = AF_INET6;
2486         sin6->sin6_port = sin->sin_port;
2487         sin6->sin6_addr.s6_addr32[0] = 0;
2488         sin6->sin6_addr.s6_addr32[1] = 0;
2489         sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2490         sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2491 }
2492
2493 /* Convert sockaddr_in6 into sockaddr_in. */
2494 void
2495 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2496 {
2497         struct sockaddr_in *sin_p;
2498         struct sockaddr_in6 sin6;
2499
2500         /*
2501          * Save original sockaddr_in6 addr and convert it
2502          * to sockaddr_in.
2503          */
2504         sin6 = *(struct sockaddr_in6 *)nam;
2505         sin_p = (struct sockaddr_in *)nam;
2506         in6_sin6_2_sin(sin_p, &sin6);
2507 }
2508
2509 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2510 void
2511 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2512 {
2513         struct sockaddr_in *sin_p;
2514         struct sockaddr_in6 *sin6_p;
2515
2516         MALLOC(sin6_p, struct sockaddr_in6 *, sizeof *sin6_p, M_SONAME,
2517                M_WAITOK);
2518         sin_p = (struct sockaddr_in *)*nam;
2519         in6_sin_2_v4mapsin6(sin_p, sin6_p);
2520         FREE(*nam, M_SONAME);
2521         *nam = (struct sockaddr *)sin6_p;
2522 }