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