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