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