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