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