]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/nd6.c
one-true-awk: import 20210221 (1e4bc42c53a1) which fixes a number of bugs
[FreeBSD/FreeBSD.git] / sys / netinet6 / nd6.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: nd6.c,v 1.144 2001/05/24 07:44:00 itojun Exp $
32  */
33
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_route.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/eventhandler.h>
44 #include <sys/callout.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/mutex.h>
49 #include <sys/socket.h>
50 #include <sys/sockio.h>
51 #include <sys/time.h>
52 #include <sys/kernel.h>
53 #include <sys/protosw.h>
54 #include <sys/errno.h>
55 #include <sys/syslog.h>
56 #include <sys/rwlock.h>
57 #include <sys/queue.h>
58 #include <sys/sdt.h>
59 #include <sys/sysctl.h>
60
61 #include <net/if.h>
62 #include <net/if_var.h>
63 #include <net/if_dl.h>
64 #include <net/if_types.h>
65 #include <net/route.h>
66 #include <net/route/route_ctl.h>
67 #include <net/route/nhop.h>
68 #include <net/vnet.h>
69
70 #include <netinet/in.h>
71 #include <netinet/in_kdtrace.h>
72 #include <net/if_llatbl.h>
73 #include <netinet/if_ether.h>
74 #include <netinet6/in6_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet6/ip6_var.h>
77 #include <netinet6/scope6_var.h>
78 #include <netinet6/nd6.h>
79 #include <netinet6/in6_ifattach.h>
80 #include <netinet/icmp6.h>
81 #include <netinet6/send.h>
82
83 #include <sys/limits.h>
84
85 #include <security/mac/mac_framework.h>
86
87 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
88 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
89
90 #define SIN6(s) ((const struct sockaddr_in6 *)(s))
91
92 MALLOC_DEFINE(M_IP6NDP, "ip6ndp", "IPv6 Neighbor Discovery");
93
94 /* timer values */
95 VNET_DEFINE(int, nd6_prune)     = 1;    /* walk list every 1 seconds */
96 VNET_DEFINE(int, nd6_delay)     = 5;    /* delay first probe time 5 second */
97 VNET_DEFINE(int, nd6_umaxtries) = 3;    /* maximum unicast query */
98 VNET_DEFINE(int, nd6_mmaxtries) = 3;    /* maximum multicast query */
99 VNET_DEFINE(int, nd6_useloopback) = 1;  /* use loopback interface for
100                                          * local traffic */
101 VNET_DEFINE(int, nd6_gctimer)   = (60 * 60 * 24); /* 1 day: garbage
102                                          * collection timer */
103
104 /* preventing too many loops in ND option parsing */
105 VNET_DEFINE_STATIC(int, nd6_maxndopt) = 10; /* max # of ND options allowed */
106
107 VNET_DEFINE(int, nd6_maxnudhint) = 0;   /* max # of subsequent upper
108                                          * layer hints */
109 VNET_DEFINE_STATIC(int, nd6_maxqueuelen) = 16; /* max pkts cached in unresolved
110                                          * ND entries */
111 #define V_nd6_maxndopt                  VNET(nd6_maxndopt)
112 #define V_nd6_maxqueuelen               VNET(nd6_maxqueuelen)
113
114 #ifdef ND6_DEBUG
115 VNET_DEFINE(int, nd6_debug) = 1;
116 #else
117 VNET_DEFINE(int, nd6_debug) = 0;
118 #endif
119
120 static eventhandler_tag lle_event_eh, iflladdr_event_eh, ifnet_link_event_eh;
121
122 VNET_DEFINE(struct nd_prhead, nd_prefix);
123 VNET_DEFINE(struct rwlock, nd6_lock);
124 VNET_DEFINE(uint64_t, nd6_list_genid);
125 VNET_DEFINE(struct mtx, nd6_onlink_mtx);
126
127 VNET_DEFINE(int, nd6_recalc_reachtm_interval) = ND6_RECALC_REACHTM_INTERVAL;
128 #define V_nd6_recalc_reachtm_interval   VNET(nd6_recalc_reachtm_interval)
129
130 int     (*send_sendso_input_hook)(struct mbuf *, struct ifnet *, int, int);
131
132 static int nd6_is_new_addr_neighbor(const struct sockaddr_in6 *,
133         struct ifnet *);
134 static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
135 static void nd6_slowtimo(void *);
136 static int regen_tmpaddr(struct in6_ifaddr *);
137 static void nd6_free(struct llentry **, int);
138 static void nd6_free_redirect(const struct llentry *);
139 static void nd6_llinfo_timer(void *);
140 static void nd6_llinfo_settimer_locked(struct llentry *, long);
141 static void clear_llinfo_pqueue(struct llentry *);
142 static int nd6_resolve_slow(struct ifnet *, int, struct mbuf *,
143     const struct sockaddr_in6 *, u_char *, uint32_t *, struct llentry **);
144 static int nd6_need_cache(struct ifnet *);
145
146 VNET_DEFINE_STATIC(struct callout, nd6_slowtimo_ch);
147 #define V_nd6_slowtimo_ch               VNET(nd6_slowtimo_ch)
148
149 VNET_DEFINE_STATIC(struct callout, nd6_timer_ch);
150 #define V_nd6_timer_ch                  VNET(nd6_timer_ch)
151
152 SYSCTL_DECL(_net_inet6_icmp6);
153
154 static void
155 nd6_lle_event(void *arg __unused, struct llentry *lle, int evt)
156 {
157         struct rt_addrinfo rtinfo;
158         struct sockaddr_in6 dst;
159         struct sockaddr_dl gw;
160         struct ifnet *ifp;
161         int type;
162         int fibnum;
163
164         LLE_WLOCK_ASSERT(lle);
165
166         if (lltable_get_af(lle->lle_tbl) != AF_INET6)
167                 return;
168
169         switch (evt) {
170         case LLENTRY_RESOLVED:
171                 type = RTM_ADD;
172                 KASSERT(lle->la_flags & LLE_VALID,
173                     ("%s: %p resolved but not valid?", __func__, lle));
174                 break;
175         case LLENTRY_EXPIRED:
176                 type = RTM_DELETE;
177                 break;
178         default:
179                 return;
180         }
181
182         ifp = lltable_get_ifp(lle->lle_tbl);
183
184         bzero(&dst, sizeof(dst));
185         bzero(&gw, sizeof(gw));
186         bzero(&rtinfo, sizeof(rtinfo));
187         lltable_fill_sa_entry(lle, (struct sockaddr *)&dst);
188         dst.sin6_scope_id = in6_getscopezone(ifp,
189             in6_addrscope(&dst.sin6_addr));
190         gw.sdl_len = sizeof(struct sockaddr_dl);
191         gw.sdl_family = AF_LINK;
192         gw.sdl_alen = ifp->if_addrlen;
193         gw.sdl_index = ifp->if_index;
194         gw.sdl_type = ifp->if_type;
195         if (evt == LLENTRY_RESOLVED)
196                 bcopy(lle->ll_addr, gw.sdl_data, ifp->if_addrlen);
197         rtinfo.rti_info[RTAX_DST] = (struct sockaddr *)&dst;
198         rtinfo.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&gw;
199         rtinfo.rti_addrs = RTA_DST | RTA_GATEWAY;
200         fibnum = V_rt_add_addr_allfibs ? RT_ALL_FIBS : ifp->if_fib;
201         rt_missmsg_fib(type, &rtinfo, RTF_HOST | RTF_LLDATA | (
202             type == RTM_ADD ? RTF_UP: 0), 0, fibnum);
203 }
204
205 /*
206  * A handler for interface link layer address change event.
207  */
208 static void
209 nd6_iflladdr(void *arg __unused, struct ifnet *ifp)
210 {
211         if (ifp->if_afdata[AF_INET6] == NULL)
212                 return;
213
214         lltable_update_ifaddr(LLTABLE6(ifp));
215 }
216
217 void
218 nd6_init(void)
219 {
220
221         mtx_init(&V_nd6_onlink_mtx, "nd6 onlink", NULL, MTX_DEF);
222         rw_init(&V_nd6_lock, "nd6 list");
223
224         LIST_INIT(&V_nd_prefix);
225         nd6_defrouter_init();
226
227         /* Start timers. */
228         callout_init(&V_nd6_slowtimo_ch, 0);
229         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
230             nd6_slowtimo, curvnet);
231
232         callout_init(&V_nd6_timer_ch, 0);
233         callout_reset(&V_nd6_timer_ch, hz, nd6_timer, curvnet);
234
235         nd6_dad_init();
236         if (IS_DEFAULT_VNET(curvnet)) {
237                 lle_event_eh = EVENTHANDLER_REGISTER(lle_event, nd6_lle_event,
238                     NULL, EVENTHANDLER_PRI_ANY);
239                 iflladdr_event_eh = EVENTHANDLER_REGISTER(iflladdr_event,
240                     nd6_iflladdr, NULL, EVENTHANDLER_PRI_ANY);
241                 ifnet_link_event_eh = EVENTHANDLER_REGISTER(ifnet_link_event,
242                     nd6_ifnet_link_event, NULL, EVENTHANDLER_PRI_ANY);
243         }
244 }
245
246 #ifdef VIMAGE
247 void
248 nd6_destroy()
249 {
250
251         callout_drain(&V_nd6_slowtimo_ch);
252         callout_drain(&V_nd6_timer_ch);
253         if (IS_DEFAULT_VNET(curvnet)) {
254                 EVENTHANDLER_DEREGISTER(ifnet_link_event, ifnet_link_event_eh);
255                 EVENTHANDLER_DEREGISTER(lle_event, lle_event_eh);
256                 EVENTHANDLER_DEREGISTER(iflladdr_event, iflladdr_event_eh);
257         }
258         rw_destroy(&V_nd6_lock);
259         mtx_destroy(&V_nd6_onlink_mtx);
260 }
261 #endif
262
263 struct nd_ifinfo *
264 nd6_ifattach(struct ifnet *ifp)
265 {
266         struct nd_ifinfo *nd;
267
268         nd = malloc(sizeof(*nd), M_IP6NDP, M_WAITOK | M_ZERO);
269         nd->initialized = 1;
270
271         nd->chlim = IPV6_DEFHLIM;
272         nd->basereachable = REACHABLE_TIME;
273         nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
274         nd->retrans = RETRANS_TIMER;
275
276         nd->flags = ND6_IFF_PERFORMNUD;
277
278         /* Set IPv6 disabled on all interfaces but loopback by default. */
279         if ((ifp->if_flags & IFF_LOOPBACK) == 0)
280                 nd->flags |= ND6_IFF_IFDISABLED;
281
282         /* A loopback interface always has ND6_IFF_AUTO_LINKLOCAL.
283          * XXXHRS: Clear ND6_IFF_AUTO_LINKLOCAL on an IFT_BRIDGE interface by
284          * default regardless of the V_ip6_auto_linklocal configuration to
285          * give a reasonable default behavior.
286          */
287         if ((V_ip6_auto_linklocal && ifp->if_type != IFT_BRIDGE) ||
288             (ifp->if_flags & IFF_LOOPBACK))
289                 nd->flags |= ND6_IFF_AUTO_LINKLOCAL;
290         /*
291          * A loopback interface does not need to accept RTADV.
292          * XXXHRS: Clear ND6_IFF_ACCEPT_RTADV on an IFT_BRIDGE interface by
293          * default regardless of the V_ip6_accept_rtadv configuration to
294          * prevent the interface from accepting RA messages arrived
295          * on one of the member interfaces with ND6_IFF_ACCEPT_RTADV.
296          */
297         if (V_ip6_accept_rtadv &&
298             !(ifp->if_flags & IFF_LOOPBACK) &&
299             (ifp->if_type != IFT_BRIDGE)) {
300                         nd->flags |= ND6_IFF_ACCEPT_RTADV;
301                         /* If we globally accept rtadv, assume IPv6 on. */
302                         nd->flags &= ~ND6_IFF_IFDISABLED;
303         }
304         if (V_ip6_no_radr && !(ifp->if_flags & IFF_LOOPBACK))
305                 nd->flags |= ND6_IFF_NO_RADR;
306
307         /* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
308         nd6_setmtu0(ifp, nd);
309
310         return nd;
311 }
312
313 void
314 nd6_ifdetach(struct ifnet *ifp, struct nd_ifinfo *nd)
315 {
316         struct epoch_tracker et;
317         struct ifaddr *ifa, *next;
318
319         NET_EPOCH_ENTER(et);
320         CK_STAILQ_FOREACH_SAFE(ifa, &ifp->if_addrhead, ifa_link, next) {
321                 if (ifa->ifa_addr->sa_family != AF_INET6)
322                         continue;
323
324                 /* stop DAD processing */
325                 nd6_dad_stop(ifa);
326         }
327         NET_EPOCH_EXIT(et);
328
329         free(nd, M_IP6NDP);
330 }
331
332 /*
333  * Reset ND level link MTU. This function is called when the physical MTU
334  * changes, which means we might have to adjust the ND level MTU.
335  */
336 void
337 nd6_setmtu(struct ifnet *ifp)
338 {
339         if (ifp->if_afdata[AF_INET6] == NULL)
340                 return;
341
342         nd6_setmtu0(ifp, ND_IFINFO(ifp));
343 }
344
345 /* XXX todo: do not maintain copy of ifp->if_mtu in ndi->maxmtu */
346 void
347 nd6_setmtu0(struct ifnet *ifp, struct nd_ifinfo *ndi)
348 {
349         u_int32_t omaxmtu;
350
351         omaxmtu = ndi->maxmtu;
352         ndi->maxmtu = ifp->if_mtu;
353
354         /*
355          * Decreasing the interface MTU under IPV6 minimum MTU may cause
356          * undesirable situation.  We thus notify the operator of the change
357          * explicitly.  The check for omaxmtu is necessary to restrict the
358          * log to the case of changing the MTU, not initializing it.
359          */
360         if (omaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
361                 log(LOG_NOTICE, "nd6_setmtu0: "
362                     "new link MTU on %s (%lu) is too small for IPv6\n",
363                     if_name(ifp), (unsigned long)ndi->maxmtu);
364         }
365
366         if (ndi->maxmtu > V_in6_maxmtu)
367                 in6_setmaxmtu(); /* check all interfaces just in case */
368
369 }
370
371 void
372 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
373 {
374
375         bzero(ndopts, sizeof(*ndopts));
376         ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
377         ndopts->nd_opts_last
378                 = (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
379
380         if (icmp6len == 0) {
381                 ndopts->nd_opts_done = 1;
382                 ndopts->nd_opts_search = NULL;
383         }
384 }
385
386 /*
387  * Take one ND option.
388  */
389 struct nd_opt_hdr *
390 nd6_option(union nd_opts *ndopts)
391 {
392         struct nd_opt_hdr *nd_opt;
393         int olen;
394
395         KASSERT(ndopts != NULL, ("%s: ndopts == NULL", __func__));
396         KASSERT(ndopts->nd_opts_last != NULL, ("%s: uninitialized ndopts",
397             __func__));
398         if (ndopts->nd_opts_search == NULL)
399                 return NULL;
400         if (ndopts->nd_opts_done)
401                 return NULL;
402
403         nd_opt = ndopts->nd_opts_search;
404
405         /* make sure nd_opt_len is inside the buffer */
406         if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
407                 bzero(ndopts, sizeof(*ndopts));
408                 return NULL;
409         }
410
411         olen = nd_opt->nd_opt_len << 3;
412         if (olen == 0) {
413                 /*
414                  * Message validation requires that all included
415                  * options have a length that is greater than zero.
416                  */
417                 bzero(ndopts, sizeof(*ndopts));
418                 return NULL;
419         }
420
421         ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
422         if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
423                 /* option overruns the end of buffer, invalid */
424                 bzero(ndopts, sizeof(*ndopts));
425                 return NULL;
426         } else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
427                 /* reached the end of options chain */
428                 ndopts->nd_opts_done = 1;
429                 ndopts->nd_opts_search = NULL;
430         }
431         return nd_opt;
432 }
433
434 /*
435  * Parse multiple ND options.
436  * This function is much easier to use, for ND routines that do not need
437  * multiple options of the same type.
438  */
439 int
440 nd6_options(union nd_opts *ndopts)
441 {
442         struct nd_opt_hdr *nd_opt;
443         int i = 0;
444
445         KASSERT(ndopts != NULL, ("%s: ndopts == NULL", __func__));
446         KASSERT(ndopts->nd_opts_last != NULL, ("%s: uninitialized ndopts",
447             __func__));
448         if (ndopts->nd_opts_search == NULL)
449                 return 0;
450
451         while (1) {
452                 nd_opt = nd6_option(ndopts);
453                 if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
454                         /*
455                          * Message validation requires that all included
456                          * options have a length that is greater than zero.
457                          */
458                         ICMP6STAT_INC(icp6s_nd_badopt);
459                         bzero(ndopts, sizeof(*ndopts));
460                         return -1;
461                 }
462
463                 if (nd_opt == NULL)
464                         goto skip1;
465
466                 switch (nd_opt->nd_opt_type) {
467                 case ND_OPT_SOURCE_LINKADDR:
468                 case ND_OPT_TARGET_LINKADDR:
469                 case ND_OPT_MTU:
470                 case ND_OPT_REDIRECTED_HEADER:
471                 case ND_OPT_NONCE:
472                         if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
473                                 nd6log((LOG_INFO,
474                                     "duplicated ND6 option found (type=%d)\n",
475                                     nd_opt->nd_opt_type));
476                                 /* XXX bark? */
477                         } else {
478                                 ndopts->nd_opt_array[nd_opt->nd_opt_type]
479                                         = nd_opt;
480                         }
481                         break;
482                 case ND_OPT_PREFIX_INFORMATION:
483                         if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
484                                 ndopts->nd_opt_array[nd_opt->nd_opt_type]
485                                         = nd_opt;
486                         }
487                         ndopts->nd_opts_pi_end =
488                                 (struct nd_opt_prefix_info *)nd_opt;
489                         break;
490                 /* What about ND_OPT_ROUTE_INFO? RFC 4191 */
491                 case ND_OPT_RDNSS:      /* RFC 6106 */
492                 case ND_OPT_DNSSL:      /* RFC 6106 */
493                         /*
494                          * Silently ignore options we know and do not care about
495                          * in the kernel.
496                          */
497                         break;
498                 default:
499                         /*
500                          * Unknown options must be silently ignored,
501                          * to accommodate future extension to the protocol.
502                          */
503                         nd6log((LOG_DEBUG,
504                             "nd6_options: unsupported option %d - "
505                             "option ignored\n", nd_opt->nd_opt_type));
506                 }
507
508 skip1:
509                 i++;
510                 if (i > V_nd6_maxndopt) {
511                         ICMP6STAT_INC(icp6s_nd_toomanyopt);
512                         nd6log((LOG_INFO, "too many loop in nd opt\n"));
513                         break;
514                 }
515
516                 if (ndopts->nd_opts_done)
517                         break;
518         }
519
520         return 0;
521 }
522
523 /*
524  * ND6 timer routine to handle ND6 entries
525  */
526 static void
527 nd6_llinfo_settimer_locked(struct llentry *ln, long tick)
528 {
529         int canceled;
530
531         LLE_WLOCK_ASSERT(ln);
532
533         if (tick < 0) {
534                 ln->la_expire = 0;
535                 ln->ln_ntick = 0;
536                 canceled = callout_stop(&ln->lle_timer);
537         } else {
538                 ln->la_expire = time_uptime + tick / hz;
539                 LLE_ADDREF(ln);
540                 if (tick > INT_MAX) {
541                         ln->ln_ntick = tick - INT_MAX;
542                         canceled = callout_reset(&ln->lle_timer, INT_MAX,
543                             nd6_llinfo_timer, ln);
544                 } else {
545                         ln->ln_ntick = 0;
546                         canceled = callout_reset(&ln->lle_timer, tick,
547                             nd6_llinfo_timer, ln);
548                 }
549         }
550         if (canceled > 0)
551                 LLE_REMREF(ln);
552 }
553
554 /*
555  * Gets source address of the first packet in hold queue
556  * and stores it in @src.
557  * Returns pointer to @src (if hold queue is not empty) or NULL.
558  *
559  * Set noinline to be dtrace-friendly
560  */
561 static __noinline struct in6_addr *
562 nd6_llinfo_get_holdsrc(struct llentry *ln, struct in6_addr *src)
563 {
564         struct ip6_hdr hdr;
565         struct mbuf *m;
566
567         if (ln->la_hold == NULL)
568                 return (NULL);
569
570         /*
571          * assume every packet in la_hold has the same IP header
572          */
573         m = ln->la_hold;
574         if (sizeof(hdr) > m->m_len)
575                 return (NULL);
576
577         m_copydata(m, 0, sizeof(hdr), (caddr_t)&hdr);
578         *src = hdr.ip6_src;
579
580         return (src);
581 }
582
583 /*
584  * Checks if we need to switch from STALE state.
585  *
586  * RFC 4861 requires switching from STALE to DELAY state
587  * on first packet matching entry, waiting V_nd6_delay and
588  * transition to PROBE state (if upper layer confirmation was
589  * not received).
590  *
591  * This code performs a bit differently:
592  * On packet hit we don't change state (but desired state
593  * can be guessed by control plane). However, after V_nd6_delay
594  * seconds code will transition to PROBE state (so DELAY state
595  * is kinda skipped in most situations).
596  *
597  * Typically, V_nd6_gctimer is bigger than V_nd6_delay, so
598  * we perform the following upon entering STALE state:
599  *
600  * 1) Arm timer to run each V_nd6_delay seconds to make sure that
601  * if packet was transmitted at the start of given interval, we
602  * would be able to switch to PROBE state in V_nd6_delay seconds
603  * as user expects.
604  *
605  * 2) Reschedule timer until original V_nd6_gctimer expires keeping
606  * lle in STALE state (remaining timer value stored in lle_remtime).
607  *
608  * 3) Reschedule timer if packet was transmitted less that V_nd6_delay
609  * seconds ago.
610  *
611  * Returns non-zero value if the entry is still STALE (storing
612  * the next timer interval in @pdelay).
613  *
614  * Returns zero value if original timer expired or we need to switch to
615  * PROBE (store that in @do_switch variable).
616  */
617 static int
618 nd6_is_stale(struct llentry *lle, long *pdelay, int *do_switch)
619 {
620         int nd_delay, nd_gctimer, r_skip_req;
621         time_t lle_hittime;
622         long delay;
623
624         *do_switch = 0;
625         nd_gctimer = V_nd6_gctimer;
626         nd_delay = V_nd6_delay;
627
628         LLE_REQ_LOCK(lle);
629         r_skip_req = lle->r_skip_req;
630         lle_hittime = lle->lle_hittime;
631         LLE_REQ_UNLOCK(lle);
632
633         if (r_skip_req > 0) {
634                 /*
635                  * Nonzero r_skip_req value was set upon entering
636                  * STALE state. Since value was not changed, no
637                  * packets were passed using this lle. Ask for
638                  * timer reschedule and keep STALE state.
639                  */
640                 delay = (long)(MIN(nd_gctimer, nd_delay));
641                 delay *= hz;
642                 if (lle->lle_remtime > delay)
643                         lle->lle_remtime -= delay;
644                 else {
645                         delay = lle->lle_remtime;
646                         lle->lle_remtime = 0;
647                 }
648
649                 if (delay == 0) {
650                         /*
651                          * The original ng6_gctime timeout ended,
652                          * no more rescheduling.
653                          */
654                         return (0);
655                 }
656
657                 *pdelay = delay;
658                 return (1);
659         }
660
661         /*
662          * Packet received. Verify timestamp
663          */
664         delay = (long)(time_uptime - lle_hittime);
665         if (delay < nd_delay) {
666                 /*
667                  * V_nd6_delay still not passed since the first
668                  * hit in STALE state.
669                  * Reshedule timer and return.
670                  */
671                 *pdelay = (long)(nd_delay - delay) * hz;
672                 return (1);
673         }
674
675         /* Request switching to probe */
676         *do_switch = 1;
677         return (0);
678 }
679
680 /*
681  * Switch @lle state to new state optionally arming timers.
682  *
683  * Set noinline to be dtrace-friendly
684  */
685 __noinline void
686 nd6_llinfo_setstate(struct llentry *lle, int newstate)
687 {
688         struct ifnet *ifp;
689         int nd_gctimer, nd_delay;
690         long delay, remtime;
691
692         delay = 0;
693         remtime = 0;
694
695         switch (newstate) {
696         case ND6_LLINFO_INCOMPLETE:
697                 ifp = lle->lle_tbl->llt_ifp;
698                 delay = (long)ND_IFINFO(ifp)->retrans * hz / 1000;
699                 break;
700         case ND6_LLINFO_REACHABLE:
701                 if (!ND6_LLINFO_PERMANENT(lle)) {
702                         ifp = lle->lle_tbl->llt_ifp;
703                         delay = (long)ND_IFINFO(ifp)->reachable * hz;
704                 }
705                 break;
706         case ND6_LLINFO_STALE:
707
708                 /*
709                  * Notify fast path that we want to know if any packet
710                  * is transmitted by setting r_skip_req.
711                  */
712                 LLE_REQ_LOCK(lle);
713                 lle->r_skip_req = 1;
714                 LLE_REQ_UNLOCK(lle);
715                 nd_delay = V_nd6_delay;
716                 nd_gctimer = V_nd6_gctimer;
717
718                 delay = (long)(MIN(nd_gctimer, nd_delay)) * hz;
719                 remtime = (long)nd_gctimer * hz - delay;
720                 break;
721         case ND6_LLINFO_DELAY:
722                 lle->la_asked = 0;
723                 delay = (long)V_nd6_delay * hz;
724                 break;
725         }
726
727         if (delay > 0)
728                 nd6_llinfo_settimer_locked(lle, delay);
729
730         lle->lle_remtime = remtime;
731         lle->ln_state = newstate;
732 }
733
734 /*
735  * Timer-dependent part of nd state machine.
736  *
737  * Set noinline to be dtrace-friendly
738  */
739 static __noinline void
740 nd6_llinfo_timer(void *arg)
741 {
742         struct epoch_tracker et;
743         struct llentry *ln;
744         struct in6_addr *dst, *pdst, *psrc, src;
745         struct ifnet *ifp;
746         struct nd_ifinfo *ndi;
747         int do_switch, send_ns;
748         long delay;
749
750         KASSERT(arg != NULL, ("%s: arg NULL", __func__));
751         ln = (struct llentry *)arg;
752         ifp = lltable_get_ifp(ln->lle_tbl);
753         CURVNET_SET(ifp->if_vnet);
754
755         ND6_RLOCK();
756         LLE_WLOCK(ln);
757         if (callout_pending(&ln->lle_timer)) {
758                 /*
759                  * Here we are a bit odd here in the treatment of 
760                  * active/pending. If the pending bit is set, it got
761                  * rescheduled before I ran. The active
762                  * bit we ignore, since if it was stopped
763                  * in ll_tablefree() and was currently running
764                  * it would have return 0 so the code would
765                  * not have deleted it since the callout could
766                  * not be stopped so we want to go through
767                  * with the delete here now. If the callout
768                  * was restarted, the pending bit will be back on and
769                  * we just want to bail since the callout_reset would
770                  * return 1 and our reference would have been removed
771                  * by nd6_llinfo_settimer_locked above since canceled
772                  * would have been 1.
773                  */
774                 LLE_WUNLOCK(ln);
775                 ND6_RUNLOCK();
776                 CURVNET_RESTORE();
777                 return;
778         }
779         NET_EPOCH_ENTER(et);
780         ndi = ND_IFINFO(ifp);
781         send_ns = 0;
782         dst = &ln->r_l3addr.addr6;
783         pdst = dst;
784
785         if (ln->ln_ntick > 0) {
786                 if (ln->ln_ntick > INT_MAX) {
787                         ln->ln_ntick -= INT_MAX;
788                         nd6_llinfo_settimer_locked(ln, INT_MAX);
789                 } else {
790                         ln->ln_ntick = 0;
791                         nd6_llinfo_settimer_locked(ln, ln->ln_ntick);
792                 }
793                 goto done;
794         }
795
796         if (ln->la_flags & LLE_STATIC) {
797                 goto done;
798         }
799
800         if (ln->la_flags & LLE_DELETED) {
801                 nd6_free(&ln, 0);
802                 goto done;
803         }
804
805         switch (ln->ln_state) {
806         case ND6_LLINFO_INCOMPLETE:
807                 if (ln->la_asked < V_nd6_mmaxtries) {
808                         ln->la_asked++;
809                         send_ns = 1;
810                         /* Send NS to multicast address */
811                         pdst = NULL;
812                 } else {
813                         struct mbuf *m = ln->la_hold;
814                         if (m) {
815                                 struct mbuf *m0;
816
817                                 /*
818                                  * assuming every packet in la_hold has the
819                                  * same IP header.  Send error after unlock.
820                                  */
821                                 m0 = m->m_nextpkt;
822                                 m->m_nextpkt = NULL;
823                                 ln->la_hold = m0;
824                                 clear_llinfo_pqueue(ln);
825                         }
826                         nd6_free(&ln, 0);
827                         if (m != NULL) {
828                                 struct mbuf *n = m;
829
830                                 /*
831                                  * if there are any ummapped mbufs, we
832                                  * must free them, rather than using
833                                  * them for an ICMP, as they cannot be
834                                  * checksummed.
835                                  */
836                                 while ((n = n->m_next) != NULL) {
837                                         if (n->m_flags & M_EXTPG)
838                                                 break;
839                                 }
840                                 if (n != NULL) {
841                                         m_freem(m);
842                                         m = NULL;
843                                 } else {
844                                         icmp6_error2(m, ICMP6_DST_UNREACH,
845                                             ICMP6_DST_UNREACH_ADDR, 0, ifp);
846                                 }
847                         }
848                 }
849                 break;
850         case ND6_LLINFO_REACHABLE:
851                 if (!ND6_LLINFO_PERMANENT(ln))
852                         nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
853                 break;
854
855         case ND6_LLINFO_STALE:
856                 if (nd6_is_stale(ln, &delay, &do_switch) != 0) {
857                         /*
858                          * No packet has used this entry and GC timeout
859                          * has not been passed. Reshedule timer and
860                          * return.
861                          */
862                         nd6_llinfo_settimer_locked(ln, delay);
863                         break;
864                 }
865
866                 if (do_switch == 0) {
867                         /*
868                          * GC timer has ended and entry hasn't been used.
869                          * Run Garbage collector (RFC 4861, 5.3)
870                          */
871                         if (!ND6_LLINFO_PERMANENT(ln))
872                                 nd6_free(&ln, 1);
873                         break;
874                 }
875
876                 /* Entry has been used AND delay timer has ended. */
877
878                 /* FALLTHROUGH */
879
880         case ND6_LLINFO_DELAY:
881                 if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
882                         /* We need NUD */
883                         ln->la_asked = 1;
884                         nd6_llinfo_setstate(ln, ND6_LLINFO_PROBE);
885                         send_ns = 1;
886                 } else
887                         nd6_llinfo_setstate(ln, ND6_LLINFO_STALE); /* XXX */
888                 break;
889         case ND6_LLINFO_PROBE:
890                 if (ln->la_asked < V_nd6_umaxtries) {
891                         ln->la_asked++;
892                         send_ns = 1;
893                 } else {
894                         nd6_free(&ln, 0);
895                 }
896                 break;
897         default:
898                 panic("%s: paths in a dark night can be confusing: %d",
899                     __func__, ln->ln_state);
900         }
901 done:
902         if (ln != NULL)
903                 ND6_RUNLOCK();
904         if (send_ns != 0) {
905                 nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
906                 psrc = nd6_llinfo_get_holdsrc(ln, &src);
907                 LLE_FREE_LOCKED(ln);
908                 ln = NULL;
909                 nd6_ns_output(ifp, psrc, pdst, dst, NULL);
910         }
911
912         if (ln != NULL)
913                 LLE_FREE_LOCKED(ln);
914         NET_EPOCH_EXIT(et);
915         CURVNET_RESTORE();
916 }
917
918 /*
919  * ND6 timer routine to expire default route list and prefix list
920  */
921 void
922 nd6_timer(void *arg)
923 {
924         CURVNET_SET((struct vnet *) arg);
925         struct epoch_tracker et;
926         struct nd_prhead prl;
927         struct nd_prefix *pr, *npr;
928         struct ifnet *ifp;
929         struct in6_ifaddr *ia6, *nia6;
930         uint64_t genid;
931
932         LIST_INIT(&prl);
933
934         NET_EPOCH_ENTER(et);
935         nd6_defrouter_timer();
936
937         /*
938          * expire interface addresses.
939          * in the past the loop was inside prefix expiry processing.
940          * However, from a stricter speci-confrmance standpoint, we should
941          * rather separate address lifetimes and prefix lifetimes.
942          *
943          * XXXRW: in6_ifaddrhead locking.
944          */
945   addrloop:
946         CK_STAILQ_FOREACH_SAFE(ia6, &V_in6_ifaddrhead, ia_link, nia6) {
947                 /* check address lifetime */
948                 if (IFA6_IS_INVALID(ia6)) {
949                         int regen = 0;
950
951                         /*
952                          * If the expiring address is temporary, try
953                          * regenerating a new one.  This would be useful when
954                          * we suspended a laptop PC, then turned it on after a
955                          * period that could invalidate all temporary
956                          * addresses.  Although we may have to restart the
957                          * loop (see below), it must be after purging the
958                          * address.  Otherwise, we'd see an infinite loop of
959                          * regeneration.
960                          */
961                         if (V_ip6_use_tempaddr &&
962                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
963                                 if (regen_tmpaddr(ia6) == 0)
964                                         regen = 1;
965                         }
966
967                         in6_purgeaddr(&ia6->ia_ifa);
968
969                         if (regen)
970                                 goto addrloop; /* XXX: see below */
971                 } else if (IFA6_IS_DEPRECATED(ia6)) {
972                         int oldflags = ia6->ia6_flags;
973
974                         ia6->ia6_flags |= IN6_IFF_DEPRECATED;
975
976                         /*
977                          * If a temporary address has just become deprecated,
978                          * regenerate a new one if possible.
979                          */
980                         if (V_ip6_use_tempaddr &&
981                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
982                             (oldflags & IN6_IFF_DEPRECATED) == 0) {
983                                 if (regen_tmpaddr(ia6) == 0) {
984                                         /*
985                                          * A new temporary address is
986                                          * generated.
987                                          * XXX: this means the address chain
988                                          * has changed while we are still in
989                                          * the loop.  Although the change
990                                          * would not cause disaster (because
991                                          * it's not a deletion, but an
992                                          * addition,) we'd rather restart the
993                                          * loop just for safety.  Or does this
994                                          * significantly reduce performance??
995                                          */
996                                         goto addrloop;
997                                 }
998                         }
999                 } else if ((ia6->ia6_flags & IN6_IFF_TENTATIVE) != 0) {
1000                         /*
1001                          * Schedule DAD for a tentative address.  This happens
1002                          * if the interface was down or not running
1003                          * when the address was configured.
1004                          */
1005                         int delay;
1006
1007                         delay = arc4random() %
1008                             (MAX_RTR_SOLICITATION_DELAY * hz);
1009                         nd6_dad_start((struct ifaddr *)ia6, delay);
1010                 } else {
1011                         /*
1012                          * Check status of the interface.  If it is down,
1013                          * mark the address as tentative for future DAD.
1014                          */
1015                         ifp = ia6->ia_ifp;
1016                         if ((ND_IFINFO(ifp)->flags & ND6_IFF_NO_DAD) == 0 &&
1017                             ((ifp->if_flags & IFF_UP) == 0 ||
1018                             (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
1019                             (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) != 0)){
1020                                 ia6->ia6_flags &= ~IN6_IFF_DUPLICATED;
1021                                 ia6->ia6_flags |= IN6_IFF_TENTATIVE;
1022                         }
1023
1024                         /*
1025                          * A new RA might have made a deprecated address
1026                          * preferred.
1027                          */
1028                         ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
1029                 }
1030         }
1031         NET_EPOCH_EXIT(et);
1032
1033         ND6_WLOCK();
1034 restart:
1035         LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
1036                 /*
1037                  * Expire prefixes. Since the pltime is only used for
1038                  * autoconfigured addresses, pltime processing for prefixes is
1039                  * not necessary.
1040                  *
1041                  * Only unlink after all derived addresses have expired. This
1042                  * may not occur until two hours after the prefix has expired
1043                  * per RFC 4862. If the prefix expires before its derived
1044                  * addresses, mark it off-link. This will be done automatically
1045                  * after unlinking if no address references remain.
1046                  */
1047                 if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME ||
1048                     time_uptime - pr->ndpr_lastupdate <= pr->ndpr_vltime)
1049                         continue;
1050
1051                 if (pr->ndpr_addrcnt == 0) {
1052                         nd6_prefix_unlink(pr, &prl);
1053                         continue;
1054                 }
1055                 if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1056                         genid = V_nd6_list_genid;
1057                         nd6_prefix_ref(pr);
1058                         ND6_WUNLOCK();
1059                         ND6_ONLINK_LOCK();
1060                         (void)nd6_prefix_offlink(pr);
1061                         ND6_ONLINK_UNLOCK();
1062                         ND6_WLOCK();
1063                         nd6_prefix_rele(pr);
1064                         if (genid != V_nd6_list_genid)
1065                                 goto restart;
1066                 }
1067         }
1068         ND6_WUNLOCK();
1069
1070         while ((pr = LIST_FIRST(&prl)) != NULL) {
1071                 LIST_REMOVE(pr, ndpr_entry);
1072                 nd6_prefix_del(pr);
1073         }
1074
1075         callout_reset(&V_nd6_timer_ch, V_nd6_prune * hz,
1076             nd6_timer, curvnet);
1077
1078         CURVNET_RESTORE();
1079 }
1080
1081 /*
1082  * ia6 - deprecated/invalidated temporary address
1083  */
1084 static int
1085 regen_tmpaddr(struct in6_ifaddr *ia6)
1086 {
1087         struct ifaddr *ifa;
1088         struct ifnet *ifp;
1089         struct in6_ifaddr *public_ifa6 = NULL;
1090
1091         NET_EPOCH_ASSERT();
1092
1093         ifp = ia6->ia_ifa.ifa_ifp;
1094         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1095                 struct in6_ifaddr *it6;
1096
1097                 if (ifa->ifa_addr->sa_family != AF_INET6)
1098                         continue;
1099
1100                 it6 = (struct in6_ifaddr *)ifa;
1101
1102                 /* ignore no autoconf addresses. */
1103                 if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1104                         continue;
1105
1106                 /* ignore autoconf addresses with different prefixes. */
1107                 if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
1108                         continue;
1109
1110                 /*
1111                  * Now we are looking at an autoconf address with the same
1112                  * prefix as ours.  If the address is temporary and is still
1113                  * preferred, do not create another one.  It would be rare, but
1114                  * could happen, for example, when we resume a laptop PC after
1115                  * a long period.
1116                  */
1117                 if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1118                     !IFA6_IS_DEPRECATED(it6)) {
1119                         public_ifa6 = NULL;
1120                         break;
1121                 }
1122
1123                 /*
1124                  * This is a public autoconf address that has the same prefix
1125                  * as ours.  If it is preferred, keep it.  We can't break the
1126                  * loop here, because there may be a still-preferred temporary
1127                  * address with the prefix.
1128                  */
1129                 if (!IFA6_IS_DEPRECATED(it6))
1130                         public_ifa6 = it6;
1131         }
1132         if (public_ifa6 != NULL)
1133                 ifa_ref(&public_ifa6->ia_ifa);
1134
1135         if (public_ifa6 != NULL) {
1136                 int e;
1137
1138                 if ((e = in6_tmpifadd(public_ifa6, 0, 0)) != 0) {
1139                         ifa_free(&public_ifa6->ia_ifa);
1140                         log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
1141                             " tmp addr,errno=%d\n", e);
1142                         return (-1);
1143                 }
1144                 ifa_free(&public_ifa6->ia_ifa);
1145                 return (0);
1146         }
1147
1148         return (-1);
1149 }
1150
1151 /*
1152  * Remove prefix and default router list entries corresponding to ifp. Neighbor
1153  * cache entries are freed in in6_domifdetach().
1154  */
1155 void
1156 nd6_purge(struct ifnet *ifp)
1157 {
1158         struct nd_prhead prl;
1159         struct nd_prefix *pr, *npr;
1160
1161         LIST_INIT(&prl);
1162
1163         /* Purge default router list entries toward ifp. */
1164         nd6_defrouter_purge(ifp);
1165
1166         ND6_WLOCK();
1167         /*
1168          * Remove prefixes on ifp. We should have already removed addresses on
1169          * this interface, so no addresses should be referencing these prefixes.
1170          */
1171         LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
1172                 if (pr->ndpr_ifp == ifp)
1173                         nd6_prefix_unlink(pr, &prl);
1174         }
1175         ND6_WUNLOCK();
1176
1177         /* Delete the unlinked prefix objects. */
1178         while ((pr = LIST_FIRST(&prl)) != NULL) {
1179                 LIST_REMOVE(pr, ndpr_entry);
1180                 nd6_prefix_del(pr);
1181         }
1182
1183         /* cancel default outgoing interface setting */
1184         if (V_nd6_defifindex == ifp->if_index)
1185                 nd6_setdefaultiface(0);
1186
1187         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1188                 /* Refresh default router list. */
1189                 defrouter_select_fib(ifp->if_fib);
1190         }
1191 }
1192
1193 /* 
1194  * the caller acquires and releases the lock on the lltbls
1195  * Returns the llentry locked
1196  */
1197 struct llentry *
1198 nd6_lookup(const struct in6_addr *addr6, int flags, struct ifnet *ifp)
1199 {
1200         struct sockaddr_in6 sin6;
1201         struct llentry *ln;
1202
1203         bzero(&sin6, sizeof(sin6));
1204         sin6.sin6_len = sizeof(struct sockaddr_in6);
1205         sin6.sin6_family = AF_INET6;
1206         sin6.sin6_addr = *addr6;
1207
1208         IF_AFDATA_LOCK_ASSERT(ifp);
1209
1210         ln = lla_lookup(LLTABLE6(ifp), flags, (struct sockaddr *)&sin6);
1211
1212         return (ln);
1213 }
1214
1215 static struct llentry *
1216 nd6_alloc(const struct in6_addr *addr6, int flags, struct ifnet *ifp)
1217 {
1218         struct sockaddr_in6 sin6;
1219         struct llentry *ln;
1220
1221         bzero(&sin6, sizeof(sin6));
1222         sin6.sin6_len = sizeof(struct sockaddr_in6);
1223         sin6.sin6_family = AF_INET6;
1224         sin6.sin6_addr = *addr6;
1225
1226         ln = lltable_alloc_entry(LLTABLE6(ifp), 0, (struct sockaddr *)&sin6);
1227         if (ln != NULL)
1228                 ln->ln_state = ND6_LLINFO_NOSTATE;
1229
1230         return (ln);
1231 }
1232
1233 /*
1234  * Test whether a given IPv6 address is a neighbor or not, ignoring
1235  * the actual neighbor cache.  The neighbor cache is ignored in order
1236  * to not reenter the routing code from within itself.
1237  */
1238 static int
1239 nd6_is_new_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
1240 {
1241         struct nd_prefix *pr;
1242         struct ifaddr *ifa;
1243         struct rt_addrinfo info;
1244         struct sockaddr_in6 rt_key;
1245         const struct sockaddr *dst6;
1246         uint64_t genid;
1247         int error, fibnum;
1248
1249         /*
1250          * A link-local address is always a neighbor.
1251          * XXX: a link does not necessarily specify a single interface.
1252          */
1253         if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
1254                 struct sockaddr_in6 sin6_copy;
1255                 u_int32_t zone;
1256
1257                 /*
1258                  * We need sin6_copy since sa6_recoverscope() may modify the
1259                  * content (XXX).
1260                  */
1261                 sin6_copy = *addr;
1262                 if (sa6_recoverscope(&sin6_copy))
1263                         return (0); /* XXX: should be impossible */
1264                 if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
1265                         return (0);
1266                 if (sin6_copy.sin6_scope_id == zone)
1267                         return (1);
1268                 else
1269                         return (0);
1270         }
1271
1272         bzero(&rt_key, sizeof(rt_key));
1273         bzero(&info, sizeof(info));
1274         info.rti_info[RTAX_DST] = (struct sockaddr *)&rt_key;
1275
1276         /*
1277          * If the address matches one of our addresses,
1278          * it should be a neighbor.
1279          * If the address matches one of our on-link prefixes, it should be a
1280          * neighbor.
1281          */
1282         ND6_RLOCK();
1283 restart:
1284         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1285                 if (pr->ndpr_ifp != ifp)
1286                         continue;
1287
1288                 if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1289                         dst6 = (const struct sockaddr *)&pr->ndpr_prefix;
1290
1291                         /*
1292                          * We only need to check all FIBs if add_addr_allfibs
1293                          * is unset. If set, checking any FIB will suffice.
1294                          */
1295                         fibnum = V_rt_add_addr_allfibs ? rt_numfibs - 1 : 0;
1296                         for (; fibnum < rt_numfibs; fibnum++) {
1297                                 genid = V_nd6_list_genid;
1298                                 ND6_RUNLOCK();
1299
1300                                 /*
1301                                  * Restore length field before
1302                                  * retrying lookup
1303                                  */
1304                                 rt_key.sin6_len = sizeof(rt_key);
1305                                 error = rib_lookup_info(fibnum, dst6, 0, 0,
1306                                                         &info);
1307
1308                                 ND6_RLOCK();
1309                                 if (genid != V_nd6_list_genid)
1310                                         goto restart;
1311                                 if (error == 0)
1312                                         break;
1313                         }
1314                         if (error != 0)
1315                                 continue;
1316
1317                         /*
1318                          * This is the case where multiple interfaces
1319                          * have the same prefix, but only one is installed 
1320                          * into the routing table and that prefix entry
1321                          * is not the one being examined here.
1322                          */
1323                         if (!IN6_ARE_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
1324                             &rt_key.sin6_addr))
1325                                 continue;
1326                 }
1327
1328                 if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
1329                     &addr->sin6_addr, &pr->ndpr_mask)) {
1330                         ND6_RUNLOCK();
1331                         return (1);
1332                 }
1333         }
1334         ND6_RUNLOCK();
1335
1336         /*
1337          * If the address is assigned on the node of the other side of
1338          * a p2p interface, the address should be a neighbor.
1339          */
1340         if (ifp->if_flags & IFF_POINTOPOINT) {
1341                 struct epoch_tracker et;
1342
1343                 NET_EPOCH_ENTER(et);
1344                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1345                         if (ifa->ifa_addr->sa_family != addr->sin6_family)
1346                                 continue;
1347                         if (ifa->ifa_dstaddr != NULL &&
1348                             sa_equal(addr, ifa->ifa_dstaddr)) {
1349                                 NET_EPOCH_EXIT(et);
1350                                 return 1;
1351                         }
1352                 }
1353                 NET_EPOCH_EXIT(et);
1354         }
1355
1356         /*
1357          * If the default router list is empty, all addresses are regarded
1358          * as on-link, and thus, as a neighbor.
1359          */
1360         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV &&
1361             nd6_defrouter_list_empty() &&
1362             V_nd6_defifindex == ifp->if_index) {
1363                 return (1);
1364         }
1365
1366         return (0);
1367 }
1368
1369 /*
1370  * Detect if a given IPv6 address identifies a neighbor on a given link.
1371  * XXX: should take care of the destination of a p2p link?
1372  */
1373 int
1374 nd6_is_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
1375 {
1376         struct llentry *lle;
1377         int rc = 0;
1378
1379         NET_EPOCH_ASSERT();
1380         IF_AFDATA_UNLOCK_ASSERT(ifp);
1381         if (nd6_is_new_addr_neighbor(addr, ifp))
1382                 return (1);
1383
1384         /*
1385          * Even if the address matches none of our addresses, it might be
1386          * in the neighbor cache.
1387          */
1388         if ((lle = nd6_lookup(&addr->sin6_addr, 0, ifp)) != NULL) {
1389                 LLE_RUNLOCK(lle);
1390                 rc = 1;
1391         }
1392         return (rc);
1393 }
1394
1395 /*
1396  * Free an nd6 llinfo entry.
1397  * Since the function would cause significant changes in the kernel, DO NOT
1398  * make it global, unless you have a strong reason for the change, and are sure
1399  * that the change is safe.
1400  *
1401  * Set noinline to be dtrace-friendly
1402  */
1403 static __noinline void
1404 nd6_free(struct llentry **lnp, int gc)
1405 {
1406         struct ifnet *ifp;
1407         struct llentry *ln;
1408         struct nd_defrouter *dr;
1409
1410         ln = *lnp;
1411         *lnp = NULL;
1412
1413         LLE_WLOCK_ASSERT(ln);
1414         ND6_RLOCK_ASSERT();
1415
1416         ifp = lltable_get_ifp(ln->lle_tbl);
1417         if ((ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) != 0)
1418                 dr = defrouter_lookup_locked(&ln->r_l3addr.addr6, ifp);
1419         else
1420                 dr = NULL;
1421         ND6_RUNLOCK();
1422
1423         if ((ln->la_flags & LLE_DELETED) == 0)
1424                 EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_EXPIRED);
1425
1426         /*
1427          * we used to have pfctlinput(PRC_HOSTDEAD) here.
1428          * even though it is not harmful, it was not really necessary.
1429          */
1430
1431         /* cancel timer */
1432         nd6_llinfo_settimer_locked(ln, -1);
1433
1434         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1435                 if (dr != NULL && dr->expire &&
1436                     ln->ln_state == ND6_LLINFO_STALE && gc) {
1437                         /*
1438                          * If the reason for the deletion is just garbage
1439                          * collection, and the neighbor is an active default
1440                          * router, do not delete it.  Instead, reset the GC
1441                          * timer using the router's lifetime.
1442                          * Simply deleting the entry would affect default
1443                          * router selection, which is not necessarily a good
1444                          * thing, especially when we're using router preference
1445                          * values.
1446                          * XXX: the check for ln_state would be redundant,
1447                          *      but we intentionally keep it just in case.
1448                          */
1449                         if (dr->expire > time_uptime)
1450                                 nd6_llinfo_settimer_locked(ln,
1451                                     (dr->expire - time_uptime) * hz);
1452                         else
1453                                 nd6_llinfo_settimer_locked(ln,
1454                                     (long)V_nd6_gctimer * hz);
1455
1456                         LLE_REMREF(ln);
1457                         LLE_WUNLOCK(ln);
1458                         defrouter_rele(dr);
1459                         return;
1460                 }
1461
1462                 if (dr) {
1463                         /*
1464                          * Unreachablity of a router might affect the default
1465                          * router selection and on-link detection of advertised
1466                          * prefixes.
1467                          */
1468
1469                         /*
1470                          * Temporarily fake the state to choose a new default
1471                          * router and to perform on-link determination of
1472                          * prefixes correctly.
1473                          * Below the state will be set correctly,
1474                          * or the entry itself will be deleted.
1475                          */
1476                         ln->ln_state = ND6_LLINFO_INCOMPLETE;
1477                 }
1478
1479                 if (ln->ln_router || dr) {
1480                         /*
1481                          * We need to unlock to avoid a LOR with rt6_flush() with the
1482                          * rnh and for the calls to pfxlist_onlink_check() and
1483                          * defrouter_select_fib() in the block further down for calls
1484                          * into nd6_lookup().  We still hold a ref.
1485                          */
1486                         LLE_WUNLOCK(ln);
1487
1488                         /*
1489                          * rt6_flush must be called whether or not the neighbor
1490                          * is in the Default Router List.
1491                          * See a corresponding comment in nd6_na_input().
1492                          */
1493                         rt6_flush(&ln->r_l3addr.addr6, ifp);
1494                 }
1495
1496                 if (dr) {
1497                         /*
1498                          * Since defrouter_select_fib() does not affect the
1499                          * on-link determination and MIP6 needs the check
1500                          * before the default router selection, we perform
1501                          * the check now.
1502                          */
1503                         pfxlist_onlink_check();
1504
1505                         /*
1506                          * Refresh default router list.
1507                          */
1508                         defrouter_select_fib(dr->ifp->if_fib);
1509                 }
1510
1511                 /*
1512                  * If this entry was added by an on-link redirect, remove the
1513                  * corresponding host route.
1514                  */
1515                 if (ln->la_flags & LLE_REDIRECT)
1516                         nd6_free_redirect(ln);
1517
1518                 if (ln->ln_router || dr)
1519                         LLE_WLOCK(ln);
1520         }
1521
1522         /*
1523          * Save to unlock. We still hold an extra reference and will not
1524          * free(9) in llentry_free() if someone else holds one as well.
1525          */
1526         LLE_WUNLOCK(ln);
1527         IF_AFDATA_LOCK(ifp);
1528         LLE_WLOCK(ln);
1529         /* Guard against race with other llentry_free(). */
1530         if (ln->la_flags & LLE_LINKED) {
1531                 /* Remove callout reference */
1532                 LLE_REMREF(ln);
1533                 lltable_unlink_entry(ln->lle_tbl, ln);
1534         }
1535         IF_AFDATA_UNLOCK(ifp);
1536
1537         llentry_free(ln);
1538         if (dr != NULL)
1539                 defrouter_rele(dr);
1540 }
1541
1542 static int
1543 nd6_isdynrte(const struct rtentry *rt, const struct nhop_object *nh, void *xap)
1544 {
1545
1546         if (nh->nh_flags & NHF_REDIRECT)
1547                 return (1);
1548
1549         return (0);
1550 }
1551
1552 /*
1553  * Remove the rtentry for the given llentry,
1554  * both of which were installed by a redirect.
1555  */
1556 static void
1557 nd6_free_redirect(const struct llentry *ln)
1558 {
1559         int fibnum;
1560         struct sockaddr_in6 sin6;
1561         struct rt_addrinfo info;
1562         struct rib_cmd_info rc;
1563         struct epoch_tracker et;
1564
1565         lltable_fill_sa_entry(ln, (struct sockaddr *)&sin6);
1566         memset(&info, 0, sizeof(info));
1567         info.rti_info[RTAX_DST] = (struct sockaddr *)&sin6;
1568         info.rti_filter = nd6_isdynrte;
1569
1570         NET_EPOCH_ENTER(et);
1571         for (fibnum = 0; fibnum < rt_numfibs; fibnum++)
1572                 rib_action(fibnum, RTM_DELETE, &info, &rc);
1573         NET_EPOCH_EXIT(et);
1574 }
1575
1576 /*
1577  * Updates status of the default router route.
1578  */
1579 static void
1580 check_release_defrouter(struct rib_cmd_info *rc, void *_cbdata)
1581 {
1582         struct nd_defrouter *dr;
1583         struct nhop_object *nh;
1584
1585         nh = rc->rc_nh_old;
1586
1587         if ((nh != NULL) && (nh->nh_flags & NHF_DEFAULT)) {
1588                 dr = defrouter_lookup(&nh->gw6_sa.sin6_addr, nh->nh_ifp);
1589                 if (dr != NULL) {
1590                         dr->installed = 0;
1591                         defrouter_rele(dr);
1592                 }
1593         }
1594 }
1595
1596 void
1597 nd6_subscription_cb(struct rib_head *rnh, struct rib_cmd_info *rc, void *arg)
1598 {
1599
1600 #ifdef ROUTE_MPATH
1601         rib_decompose_notification(rc, check_release_defrouter, NULL);
1602 #else
1603         check_release_defrouter(rc, NULL);
1604 #endif
1605 }
1606
1607 int
1608 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1609 {
1610         struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1611         struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1612         struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1613         struct epoch_tracker et;
1614         int error = 0;
1615
1616         if (ifp->if_afdata[AF_INET6] == NULL)
1617                 return (EPFNOSUPPORT);
1618         switch (cmd) {
1619         case OSIOCGIFINFO_IN6:
1620 #define ND      ndi->ndi
1621                 /* XXX: old ndp(8) assumes a positive value for linkmtu. */
1622                 bzero(&ND, sizeof(ND));
1623                 ND.linkmtu = IN6_LINKMTU(ifp);
1624                 ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
1625                 ND.basereachable = ND_IFINFO(ifp)->basereachable;
1626                 ND.reachable = ND_IFINFO(ifp)->reachable;
1627                 ND.retrans = ND_IFINFO(ifp)->retrans;
1628                 ND.flags = ND_IFINFO(ifp)->flags;
1629                 ND.recalctm = ND_IFINFO(ifp)->recalctm;
1630                 ND.chlim = ND_IFINFO(ifp)->chlim;
1631                 break;
1632         case SIOCGIFINFO_IN6:
1633                 ND = *ND_IFINFO(ifp);
1634                 break;
1635         case SIOCSIFINFO_IN6:
1636                 /*
1637                  * used to change host variables from userland.
1638                  * intended for a use on router to reflect RA configurations.
1639                  */
1640                 /* 0 means 'unspecified' */
1641                 if (ND.linkmtu != 0) {
1642                         if (ND.linkmtu < IPV6_MMTU ||
1643                             ND.linkmtu > IN6_LINKMTU(ifp)) {
1644                                 error = EINVAL;
1645                                 break;
1646                         }
1647                         ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
1648                 }
1649
1650                 if (ND.basereachable != 0) {
1651                         int obasereachable = ND_IFINFO(ifp)->basereachable;
1652
1653                         ND_IFINFO(ifp)->basereachable = ND.basereachable;
1654                         if (ND.basereachable != obasereachable)
1655                                 ND_IFINFO(ifp)->reachable =
1656                                     ND_COMPUTE_RTIME(ND.basereachable);
1657                 }
1658                 if (ND.retrans != 0)
1659                         ND_IFINFO(ifp)->retrans = ND.retrans;
1660                 if (ND.chlim != 0)
1661                         ND_IFINFO(ifp)->chlim = ND.chlim;
1662                 /* FALLTHROUGH */
1663         case SIOCSIFINFO_FLAGS:
1664         {
1665                 struct ifaddr *ifa;
1666                 struct in6_ifaddr *ia;
1667
1668                 if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1669                     !(ND.flags & ND6_IFF_IFDISABLED)) {
1670                         /* ifdisabled 1->0 transision */
1671
1672                         /*
1673                          * If the interface is marked as ND6_IFF_IFDISABLED and
1674                          * has an link-local address with IN6_IFF_DUPLICATED,
1675                          * do not clear ND6_IFF_IFDISABLED.
1676                          * See RFC 4862, Section 5.4.5.
1677                          */
1678                         NET_EPOCH_ENTER(et);
1679                         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1680                                 if (ifa->ifa_addr->sa_family != AF_INET6)
1681                                         continue;
1682                                 ia = (struct in6_ifaddr *)ifa;
1683                                 if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
1684                                     IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1685                                         break;
1686                         }
1687                         NET_EPOCH_EXIT(et);
1688
1689                         if (ifa != NULL) {
1690                                 /* LLA is duplicated. */
1691                                 ND.flags |= ND6_IFF_IFDISABLED;
1692                                 log(LOG_ERR, "Cannot enable an interface"
1693                                     " with a link-local address marked"
1694                                     " duplicate.\n");
1695                         } else {
1696                                 ND_IFINFO(ifp)->flags &= ~ND6_IFF_IFDISABLED;
1697                                 if (ifp->if_flags & IFF_UP)
1698                                         in6_if_up(ifp);
1699                         }
1700                 } else if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1701                             (ND.flags & ND6_IFF_IFDISABLED)) {
1702                         /* ifdisabled 0->1 transision */
1703                         /* Mark all IPv6 address as tentative. */
1704
1705                         ND_IFINFO(ifp)->flags |= ND6_IFF_IFDISABLED;
1706                         if (V_ip6_dad_count > 0 &&
1707                             (ND_IFINFO(ifp)->flags & ND6_IFF_NO_DAD) == 0) {
1708                                 NET_EPOCH_ENTER(et);
1709                                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead,
1710                                     ifa_link) {
1711                                         if (ifa->ifa_addr->sa_family !=
1712                                             AF_INET6)
1713                                                 continue;
1714                                         ia = (struct in6_ifaddr *)ifa;
1715                                         ia->ia6_flags |= IN6_IFF_TENTATIVE;
1716                                 }
1717                                 NET_EPOCH_EXIT(et);
1718                         }
1719                 }
1720
1721                 if (ND.flags & ND6_IFF_AUTO_LINKLOCAL) {
1722                         if (!(ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL)) {
1723                                 /* auto_linklocal 0->1 transision */
1724
1725                                 /* If no link-local address on ifp, configure */
1726                                 ND_IFINFO(ifp)->flags |= ND6_IFF_AUTO_LINKLOCAL;
1727                                 in6_ifattach(ifp, NULL);
1728                         } else if (!(ND.flags & ND6_IFF_IFDISABLED) &&
1729                             ifp->if_flags & IFF_UP) {
1730                                 /*
1731                                  * When the IF already has
1732                                  * ND6_IFF_AUTO_LINKLOCAL, no link-local
1733                                  * address is assigned, and IFF_UP, try to
1734                                  * assign one.
1735                                  */
1736                                 NET_EPOCH_ENTER(et);
1737                                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead,
1738                                     ifa_link) {
1739                                         if (ifa->ifa_addr->sa_family !=
1740                                             AF_INET6)
1741                                                 continue;
1742                                         ia = (struct in6_ifaddr *)ifa;
1743                                         if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1744                                                 break;
1745                                 }
1746                                 NET_EPOCH_EXIT(et);
1747                                 if (ifa != NULL)
1748                                         /* No LLA is configured. */
1749                                         in6_ifattach(ifp, NULL);
1750                         }
1751                 }
1752                 ND_IFINFO(ifp)->flags = ND.flags;
1753                 break;
1754         }
1755 #undef ND
1756         case SIOCSNDFLUSH_IN6:  /* XXX: the ioctl name is confusing... */
1757                 /* sync kernel routing table with the default router list */
1758                 defrouter_reset();
1759                 defrouter_select_fib(RT_ALL_FIBS);
1760                 break;
1761         case SIOCSPFXFLUSH_IN6:
1762         {
1763                 /* flush all the prefix advertised by routers */
1764                 struct in6_ifaddr *ia, *ia_next;
1765                 struct nd_prefix *pr, *next;
1766                 struct nd_prhead prl;
1767
1768                 LIST_INIT(&prl);
1769
1770                 ND6_WLOCK();
1771                 LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, next) {
1772                         if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1773                                 continue; /* XXX */
1774                         nd6_prefix_unlink(pr, &prl);
1775                 }
1776                 ND6_WUNLOCK();
1777
1778                 while ((pr = LIST_FIRST(&prl)) != NULL) {
1779                         LIST_REMOVE(pr, ndpr_entry);
1780                         /* XXXRW: in6_ifaddrhead locking. */
1781                         CK_STAILQ_FOREACH_SAFE(ia, &V_in6_ifaddrhead, ia_link,
1782                             ia_next) {
1783                                 if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1784                                         continue;
1785
1786                                 if (ia->ia6_ndpr == pr)
1787                                         in6_purgeaddr(&ia->ia_ifa);
1788                         }
1789                         nd6_prefix_del(pr);
1790                 }
1791                 break;
1792         }
1793         case SIOCSRTRFLUSH_IN6:
1794         {
1795                 /* flush all the default routers */
1796
1797                 defrouter_reset();
1798                 nd6_defrouter_flush_all();
1799                 defrouter_select_fib(RT_ALL_FIBS);
1800                 break;
1801         }
1802         case SIOCGNBRINFO_IN6:
1803         {
1804                 struct llentry *ln;
1805                 struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1806
1807                 if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
1808                         return (error);
1809
1810                 NET_EPOCH_ENTER(et);
1811                 ln = nd6_lookup(&nb_addr, 0, ifp);
1812                 NET_EPOCH_EXIT(et);
1813
1814                 if (ln == NULL) {
1815                         error = EINVAL;
1816                         break;
1817                 }
1818                 nbi->state = ln->ln_state;
1819                 nbi->asked = ln->la_asked;
1820                 nbi->isrouter = ln->ln_router;
1821                 if (ln->la_expire == 0)
1822                         nbi->expire = 0;
1823                 else
1824                         nbi->expire = ln->la_expire + ln->lle_remtime / hz +
1825                             (time_second - time_uptime);
1826                 LLE_RUNLOCK(ln);
1827                 break;
1828         }
1829         case SIOCGDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1830                 ndif->ifindex = V_nd6_defifindex;
1831                 break;
1832         case SIOCSDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1833                 return (nd6_setdefaultiface(ndif->ifindex));
1834         }
1835         return (error);
1836 }
1837
1838 /*
1839  * Calculates new isRouter value based on provided parameters and
1840  * returns it.
1841  */
1842 static int
1843 nd6_is_router(int type, int code, int is_new, int old_addr, int new_addr,
1844     int ln_router)
1845 {
1846
1847         /*
1848          * ICMP6 type dependent behavior.
1849          *
1850          * NS: clear IsRouter if new entry
1851          * RS: clear IsRouter
1852          * RA: set IsRouter if there's lladdr
1853          * redir: clear IsRouter if new entry
1854          *
1855          * RA case, (1):
1856          * The spec says that we must set IsRouter in the following cases:
1857          * - If lladdr exist, set IsRouter.  This means (1-5).
1858          * - If it is old entry (!newentry), set IsRouter.  This means (7).
1859          * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1860          * A quetion arises for (1) case.  (1) case has no lladdr in the
1861          * neighbor cache, this is similar to (6).
1862          * This case is rare but we figured that we MUST NOT set IsRouter.
1863          *
1864          *   is_new  old_addr new_addr      NS  RS  RA  redir
1865          *                                                      D R
1866          *      0       n       n       (1)     c   ?     s
1867          *      0       y       n       (2)     c   s     s
1868          *      0       n       y       (3)     c   s     s
1869          *      0       y       y       (4)     c   s     s
1870          *      0       y       y       (5)     c   s     s
1871          *      1       --      n       (6) c   c       c s
1872          *      1       --      y       (7) c   c   s   c s
1873          *
1874          *                                      (c=clear s=set)
1875          */
1876         switch (type & 0xff) {
1877         case ND_NEIGHBOR_SOLICIT:
1878                 /*
1879                  * New entry must have is_router flag cleared.
1880                  */
1881                 if (is_new)                                     /* (6-7) */
1882                         ln_router = 0;
1883                 break;
1884         case ND_REDIRECT:
1885                 /*
1886                  * If the icmp is a redirect to a better router, always set the
1887                  * is_router flag.  Otherwise, if the entry is newly created,
1888                  * clear the flag.  [RFC 2461, sec 8.3]
1889                  */
1890                 if (code == ND_REDIRECT_ROUTER)
1891                         ln_router = 1;
1892                 else {
1893                         if (is_new)                             /* (6-7) */
1894                                 ln_router = 0;
1895                 }
1896                 break;
1897         case ND_ROUTER_SOLICIT:
1898                 /*
1899                  * is_router flag must always be cleared.
1900                  */
1901                 ln_router = 0;
1902                 break;
1903         case ND_ROUTER_ADVERT:
1904                 /*
1905                  * Mark an entry with lladdr as a router.
1906                  */
1907                 if ((!is_new && (old_addr || new_addr)) ||      /* (2-5) */
1908                     (is_new && new_addr)) {                     /* (7) */
1909                         ln_router = 1;
1910                 }
1911                 break;
1912         }
1913
1914         return (ln_router);
1915 }
1916
1917 /*
1918  * Create neighbor cache entry and cache link-layer address,
1919  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1920  *
1921  * type - ICMP6 type
1922  * code - type dependent information
1923  *
1924  */
1925 void
1926 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1927     int lladdrlen, int type, int code)
1928 {
1929         struct llentry *ln = NULL, *ln_tmp;
1930         int is_newentry;
1931         int do_update;
1932         int olladdr;
1933         int llchange;
1934         int flags;
1935         uint16_t router = 0;
1936         struct sockaddr_in6 sin6;
1937         struct mbuf *chain = NULL;
1938         u_char linkhdr[LLE_MAX_LINKHDR];
1939         size_t linkhdrsize;
1940         int lladdr_off;
1941
1942         NET_EPOCH_ASSERT();
1943         IF_AFDATA_UNLOCK_ASSERT(ifp);
1944
1945         KASSERT(ifp != NULL, ("%s: ifp == NULL", __func__));
1946         KASSERT(from != NULL, ("%s: from == NULL", __func__));
1947
1948         /* nothing must be updated for unspecified address */
1949         if (IN6_IS_ADDR_UNSPECIFIED(from))
1950                 return;
1951
1952         /*
1953          * Validation about ifp->if_addrlen and lladdrlen must be done in
1954          * the caller.
1955          *
1956          * XXX If the link does not have link-layer adderss, what should
1957          * we do? (ifp->if_addrlen == 0)
1958          * Spec says nothing in sections for RA, RS and NA.  There's small
1959          * description on it in NS section (RFC 2461 7.2.3).
1960          */
1961         flags = lladdr ? LLE_EXCLUSIVE : 0;
1962         ln = nd6_lookup(from, flags, ifp);
1963         is_newentry = 0;
1964         if (ln == NULL) {
1965                 flags |= LLE_EXCLUSIVE;
1966                 ln = nd6_alloc(from, 0, ifp);
1967                 if (ln == NULL)
1968                         return;
1969
1970                 /*
1971                  * Since we already know all the data for the new entry,
1972                  * fill it before insertion.
1973                  */
1974                 if (lladdr != NULL) {
1975                         linkhdrsize = sizeof(linkhdr);
1976                         if (lltable_calc_llheader(ifp, AF_INET6, lladdr,
1977                             linkhdr, &linkhdrsize, &lladdr_off) != 0)
1978                                 return;
1979                         lltable_set_entry_addr(ifp, ln, linkhdr, linkhdrsize,
1980                             lladdr_off);
1981                 }
1982
1983                 IF_AFDATA_WLOCK(ifp);
1984                 LLE_WLOCK(ln);
1985                 /* Prefer any existing lle over newly-created one */
1986                 ln_tmp = nd6_lookup(from, LLE_EXCLUSIVE, ifp);
1987                 if (ln_tmp == NULL)
1988                         lltable_link_entry(LLTABLE6(ifp), ln);
1989                 IF_AFDATA_WUNLOCK(ifp);
1990                 if (ln_tmp == NULL) {
1991                         /* No existing lle, mark as new entry (6,7) */
1992                         is_newentry = 1;
1993                         if (lladdr != NULL) {   /* (7) */
1994                                 nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
1995                                 EVENTHANDLER_INVOKE(lle_event, ln,
1996                                     LLENTRY_RESOLVED);
1997                         }
1998                 } else {
1999                         lltable_free_entry(LLTABLE6(ifp), ln);
2000                         ln = ln_tmp;
2001                         ln_tmp = NULL;
2002                 }
2003         } 
2004         /* do nothing if static ndp is set */
2005         if ((ln->la_flags & LLE_STATIC)) {
2006                 if (flags & LLE_EXCLUSIVE)
2007                         LLE_WUNLOCK(ln);
2008                 else
2009                         LLE_RUNLOCK(ln);
2010                 return;
2011         }
2012
2013         olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
2014         if (olladdr && lladdr) {
2015                 llchange = bcmp(lladdr, ln->ll_addr,
2016                     ifp->if_addrlen);
2017         } else if (!olladdr && lladdr)
2018                 llchange = 1;
2019         else
2020                 llchange = 0;
2021
2022         /*
2023          * newentry olladdr  lladdr  llchange   (*=record)
2024          *      0       n       n       --      (1)
2025          *      0       y       n       --      (2)
2026          *      0       n       y       y       (3) * STALE
2027          *      0       y       y       n       (4) *
2028          *      0       y       y       y       (5) * STALE
2029          *      1       --      n       --      (6)   NOSTATE(= PASSIVE)
2030          *      1       --      y       --      (7) * STALE
2031          */
2032
2033         do_update = 0;
2034         if (is_newentry == 0 && llchange != 0) {
2035                 do_update = 1;  /* (3,5) */
2036
2037                 /*
2038                  * Record source link-layer address
2039                  * XXX is it dependent to ifp->if_type?
2040                  */
2041                 linkhdrsize = sizeof(linkhdr);
2042                 if (lltable_calc_llheader(ifp, AF_INET6, lladdr,
2043                     linkhdr, &linkhdrsize, &lladdr_off) != 0)
2044                         return;
2045
2046                 if (lltable_try_set_entry_addr(ifp, ln, linkhdr, linkhdrsize,
2047                     lladdr_off) == 0) {
2048                         /* Entry was deleted */
2049                         return;
2050                 }
2051
2052                 nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
2053
2054                 EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
2055
2056                 if (ln->la_hold != NULL)
2057                         nd6_grab_holdchain(ln, &chain, &sin6);
2058         }
2059
2060         /* Calculates new router status */
2061         router = nd6_is_router(type, code, is_newentry, olladdr,
2062             lladdr != NULL ? 1 : 0, ln->ln_router);
2063
2064         ln->ln_router = router;
2065         /* Mark non-router redirects with special flag */
2066         if ((type & 0xFF) == ND_REDIRECT && code != ND_REDIRECT_ROUTER)
2067                 ln->la_flags |= LLE_REDIRECT;
2068
2069         if (flags & LLE_EXCLUSIVE)
2070                 LLE_WUNLOCK(ln);
2071         else
2072                 LLE_RUNLOCK(ln);
2073
2074         if (chain != NULL)
2075                 nd6_flush_holdchain(ifp, chain, &sin6);
2076
2077         /*
2078          * When the link-layer address of a router changes, select the
2079          * best router again.  In particular, when the neighbor entry is newly
2080          * created, it might affect the selection policy.
2081          * Question: can we restrict the first condition to the "is_newentry"
2082          * case?
2083          * XXX: when we hear an RA from a new router with the link-layer
2084          * address option, defrouter_select_fib() is called twice, since
2085          * defrtrlist_update called the function as well.  However, I believe
2086          * we can compromise the overhead, since it only happens the first
2087          * time.
2088          * XXX: although defrouter_select_fib() should not have a bad effect
2089          * for those are not autoconfigured hosts, we explicitly avoid such
2090          * cases for safety.
2091          */
2092         if ((do_update || is_newentry) && router &&
2093             ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
2094                 /*
2095                  * guaranteed recursion
2096                  */
2097                 defrouter_select_fib(ifp->if_fib);
2098         }
2099 }
2100
2101 static void
2102 nd6_slowtimo(void *arg)
2103 {
2104         struct epoch_tracker et;
2105         CURVNET_SET((struct vnet *) arg);
2106         struct nd_ifinfo *nd6if;
2107         struct ifnet *ifp;
2108
2109         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
2110             nd6_slowtimo, curvnet);
2111         NET_EPOCH_ENTER(et);
2112         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2113                 if (ifp->if_afdata[AF_INET6] == NULL)
2114                         continue;
2115                 nd6if = ND_IFINFO(ifp);
2116                 if (nd6if->basereachable && /* already initialized */
2117                     (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
2118                         /*
2119                          * Since reachable time rarely changes by router
2120                          * advertisements, we SHOULD insure that a new random
2121                          * value gets recomputed at least once every few hours.
2122                          * (RFC 2461, 6.3.4)
2123                          */
2124                         nd6if->recalctm = V_nd6_recalc_reachtm_interval;
2125                         nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
2126                 }
2127         }
2128         NET_EPOCH_EXIT(et);
2129         CURVNET_RESTORE();
2130 }
2131
2132 void
2133 nd6_grab_holdchain(struct llentry *ln, struct mbuf **chain,
2134     struct sockaddr_in6 *sin6)
2135 {
2136
2137         LLE_WLOCK_ASSERT(ln);
2138
2139         *chain = ln->la_hold;
2140         ln->la_hold = NULL;
2141         lltable_fill_sa_entry(ln, (struct sockaddr *)sin6);
2142
2143         if (ln->ln_state == ND6_LLINFO_STALE) {
2144                 /*
2145                  * The first time we send a packet to a
2146                  * neighbor whose entry is STALE, we have
2147                  * to change the state to DELAY and a sets
2148                  * a timer to expire in DELAY_FIRST_PROBE_TIME
2149                  * seconds to ensure do neighbor unreachability
2150                  * detection on expiration.
2151                  * (RFC 2461 7.3.3)
2152                  */
2153                 nd6_llinfo_setstate(ln, ND6_LLINFO_DELAY);
2154         }
2155 }
2156
2157 int
2158 nd6_output_ifp(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
2159     struct sockaddr_in6 *dst, struct route *ro)
2160 {
2161         int error;
2162         int ip6len;
2163         struct ip6_hdr *ip6;
2164         struct m_tag *mtag;
2165
2166 #ifdef MAC
2167         mac_netinet6_nd6_send(ifp, m);
2168 #endif
2169
2170         /*
2171          * If called from nd6_ns_output() (NS), nd6_na_output() (NA),
2172          * icmp6_redirect_output() (REDIRECT) or from rip6_output() (RS, RA
2173          * as handled by rtsol and rtadvd), mbufs will be tagged for SeND
2174          * to be diverted to user space.  When re-injected into the kernel,
2175          * send_output() will directly dispatch them to the outgoing interface.
2176          */
2177         if (send_sendso_input_hook != NULL) {
2178                 mtag = m_tag_find(m, PACKET_TAG_ND_OUTGOING, NULL);
2179                 if (mtag != NULL) {
2180                         ip6 = mtod(m, struct ip6_hdr *);
2181                         ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
2182                         /* Use the SEND socket */
2183                         error = send_sendso_input_hook(m, ifp, SND_OUT,
2184                             ip6len);
2185                         /* -1 == no app on SEND socket */
2186                         if (error == 0 || error != -1)
2187                             return (error);
2188                 }
2189         }
2190
2191         m_clrprotoflags(m);     /* Avoid confusing lower layers. */
2192         IP_PROBE(send, NULL, NULL, mtod(m, struct ip6_hdr *), ifp, NULL,
2193             mtod(m, struct ip6_hdr *));
2194
2195         if ((ifp->if_flags & IFF_LOOPBACK) == 0)
2196                 origifp = ifp;
2197
2198         error = (*ifp->if_output)(origifp, m, (struct sockaddr *)dst, ro);
2199         return (error);
2200 }
2201
2202 /*
2203  * Lookup link headerfor @sa_dst address. Stores found
2204  * data in @desten buffer. Copy of lle ln_flags can be also
2205  * saved in @pflags if @pflags is non-NULL.
2206  *
2207  * If destination LLE does not exists or lle state modification
2208  * is required, call "slow" version.
2209  *
2210  * Return values:
2211  * - 0 on success (address copied to buffer).
2212  * - EWOULDBLOCK (no local error, but address is still unresolved)
2213  * - other errors (alloc failure, etc)
2214  */
2215 int
2216 nd6_resolve(struct ifnet *ifp, int is_gw, struct mbuf *m,
2217     const struct sockaddr *sa_dst, u_char *desten, uint32_t *pflags,
2218     struct llentry **plle)
2219 {
2220         struct llentry *ln = NULL;
2221         const struct sockaddr_in6 *dst6;
2222
2223         NET_EPOCH_ASSERT();
2224
2225         if (pflags != NULL)
2226                 *pflags = 0;
2227
2228         dst6 = (const struct sockaddr_in6 *)sa_dst;
2229
2230         /* discard the packet if IPv6 operation is disabled on the interface */
2231         if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
2232                 m_freem(m);
2233                 return (ENETDOWN); /* better error? */
2234         }
2235
2236         if (m != NULL && m->m_flags & M_MCAST) {
2237                 switch (ifp->if_type) {
2238                 case IFT_ETHER:
2239                 case IFT_L2VLAN:
2240                 case IFT_BRIDGE:
2241                         ETHER_MAP_IPV6_MULTICAST(&dst6->sin6_addr,
2242                                                  desten);
2243                         return (0);
2244                 default:
2245                         m_freem(m);
2246                         return (EAFNOSUPPORT);
2247                 }
2248         }
2249
2250         ln = nd6_lookup(&dst6->sin6_addr, plle ? LLE_EXCLUSIVE : LLE_UNLOCKED,
2251             ifp);
2252         if (ln != NULL && (ln->r_flags & RLLE_VALID) != 0) {
2253                 /* Entry found, let's copy lle info */
2254                 bcopy(ln->r_linkdata, desten, ln->r_hdrlen);
2255                 if (pflags != NULL)
2256                         *pflags = LLE_VALID | (ln->r_flags & RLLE_IFADDR);
2257                 /* Check if we have feedback request from nd6 timer */
2258                 if (ln->r_skip_req != 0) {
2259                         LLE_REQ_LOCK(ln);
2260                         ln->r_skip_req = 0; /* Notify that entry was used */
2261                         ln->lle_hittime = time_uptime;
2262                         LLE_REQ_UNLOCK(ln);
2263                 }
2264                 if (plle) {
2265                         LLE_ADDREF(ln);
2266                         *plle = ln;
2267                         LLE_WUNLOCK(ln);
2268                 }
2269                 return (0);
2270         } else if (plle && ln)
2271                 LLE_WUNLOCK(ln);
2272
2273         return (nd6_resolve_slow(ifp, 0, m, dst6, desten, pflags, plle));
2274 }
2275
2276 /*
2277  * Do L2 address resolution for @sa_dst address. Stores found
2278  * address in @desten buffer. Copy of lle ln_flags can be also
2279  * saved in @pflags if @pflags is non-NULL.
2280  *
2281  * Heavy version.
2282  * Function assume that destination LLE does not exist,
2283  * is invalid or stale, so LLE_EXCLUSIVE lock needs to be acquired.
2284  *
2285  * Set noinline to be dtrace-friendly
2286  */
2287 static __noinline int
2288 nd6_resolve_slow(struct ifnet *ifp, int flags, struct mbuf *m,
2289     const struct sockaddr_in6 *dst, u_char *desten, uint32_t *pflags,
2290     struct llentry **plle)
2291 {
2292         struct llentry *lle = NULL, *lle_tmp;
2293         struct in6_addr *psrc, src;
2294         int send_ns, ll_len;
2295         char *lladdr;
2296
2297         NET_EPOCH_ASSERT();
2298
2299         /*
2300          * Address resolution or Neighbor Unreachability Detection
2301          * for the next hop.
2302          * At this point, the destination of the packet must be a unicast
2303          * or an anycast address(i.e. not a multicast).
2304          */
2305         if (lle == NULL) {
2306                 lle = nd6_lookup(&dst->sin6_addr, LLE_EXCLUSIVE, ifp);
2307                 if ((lle == NULL) && nd6_is_addr_neighbor(dst, ifp))  {
2308                         /*
2309                          * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
2310                          * the condition below is not very efficient.  But we believe
2311                          * it is tolerable, because this should be a rare case.
2312                          */
2313                         lle = nd6_alloc(&dst->sin6_addr, 0, ifp);
2314                         if (lle == NULL) {
2315                                 char ip6buf[INET6_ADDRSTRLEN];
2316                                 log(LOG_DEBUG,
2317                                     "nd6_output: can't allocate llinfo for %s "
2318                                     "(ln=%p)\n",
2319                                     ip6_sprintf(ip6buf, &dst->sin6_addr), lle);
2320                                 m_freem(m);
2321                                 return (ENOBUFS);
2322                         }
2323
2324                         IF_AFDATA_WLOCK(ifp);
2325                         LLE_WLOCK(lle);
2326                         /* Prefer any existing entry over newly-created one */
2327                         lle_tmp = nd6_lookup(&dst->sin6_addr, LLE_EXCLUSIVE, ifp);
2328                         if (lle_tmp == NULL)
2329                                 lltable_link_entry(LLTABLE6(ifp), lle);
2330                         IF_AFDATA_WUNLOCK(ifp);
2331                         if (lle_tmp != NULL) {
2332                                 lltable_free_entry(LLTABLE6(ifp), lle);
2333                                 lle = lle_tmp;
2334                                 lle_tmp = NULL;
2335                         }
2336                 }
2337         } 
2338         if (lle == NULL) {
2339                 m_freem(m);
2340                 return (ENOBUFS);
2341         }
2342
2343         LLE_WLOCK_ASSERT(lle);
2344
2345         /*
2346          * The first time we send a packet to a neighbor whose entry is
2347          * STALE, we have to change the state to DELAY and a sets a timer to
2348          * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
2349          * neighbor unreachability detection on expiration.
2350          * (RFC 2461 7.3.3)
2351          */
2352         if (lle->ln_state == ND6_LLINFO_STALE)
2353                 nd6_llinfo_setstate(lle, ND6_LLINFO_DELAY);
2354
2355         /*
2356          * If the neighbor cache entry has a state other than INCOMPLETE
2357          * (i.e. its link-layer address is already resolved), just
2358          * send the packet.
2359          */
2360         if (lle->ln_state > ND6_LLINFO_INCOMPLETE) {
2361                 if (flags & LLE_ADDRONLY) {
2362                         lladdr = lle->ll_addr;
2363                         ll_len = ifp->if_addrlen;
2364                 } else {
2365                         lladdr = lle->r_linkdata;
2366                         ll_len = lle->r_hdrlen;
2367                 }
2368                 bcopy(lladdr, desten, ll_len);
2369                 if (pflags != NULL)
2370                         *pflags = lle->la_flags;
2371                 if (plle) {
2372                         LLE_ADDREF(lle);
2373                         *plle = lle;
2374                 }
2375                 LLE_WUNLOCK(lle);
2376                 return (0);
2377         }
2378
2379         /*
2380          * There is a neighbor cache entry, but no ethernet address
2381          * response yet.  Append this latest packet to the end of the
2382          * packet queue in the mbuf.  When it exceeds nd6_maxqueuelen,
2383          * the oldest packet in the queue will be removed.
2384          */
2385
2386         if (lle->la_hold != NULL) {
2387                 struct mbuf *m_hold;
2388                 int i;
2389                 
2390                 i = 0;
2391                 for (m_hold = lle->la_hold; m_hold; m_hold = m_hold->m_nextpkt){
2392                         i++;
2393                         if (m_hold->m_nextpkt == NULL) {
2394                                 m_hold->m_nextpkt = m;
2395                                 break;
2396                         }
2397                 }
2398                 while (i >= V_nd6_maxqueuelen) {
2399                         m_hold = lle->la_hold;
2400                         lle->la_hold = lle->la_hold->m_nextpkt;
2401                         m_freem(m_hold);
2402                         i--;
2403                 }
2404         } else {
2405                 lle->la_hold = m;
2406         }
2407
2408         /*
2409          * If there has been no NS for the neighbor after entering the
2410          * INCOMPLETE state, send the first solicitation.
2411          * Note that for newly-created lle la_asked will be 0,
2412          * so we will transition from ND6_LLINFO_NOSTATE to
2413          * ND6_LLINFO_INCOMPLETE state here.
2414          */
2415         psrc = NULL;
2416         send_ns = 0;
2417         if (lle->la_asked == 0) {
2418                 lle->la_asked++;
2419                 send_ns = 1;
2420                 psrc = nd6_llinfo_get_holdsrc(lle, &src);
2421
2422                 nd6_llinfo_setstate(lle, ND6_LLINFO_INCOMPLETE);
2423         }
2424         LLE_WUNLOCK(lle);
2425         if (send_ns != 0)
2426                 nd6_ns_output(ifp, psrc, NULL, &dst->sin6_addr, NULL);
2427
2428         return (EWOULDBLOCK);
2429 }
2430
2431 /*
2432  * Do L2 address resolution for @sa_dst address. Stores found
2433  * address in @desten buffer. Copy of lle ln_flags can be also
2434  * saved in @pflags if @pflags is non-NULL.
2435  *
2436  * Return values:
2437  * - 0 on success (address copied to buffer).
2438  * - EWOULDBLOCK (no local error, but address is still unresolved)
2439  * - other errors (alloc failure, etc)
2440  */
2441 int
2442 nd6_resolve_addr(struct ifnet *ifp, int flags, const struct sockaddr *dst,
2443     char *desten, uint32_t *pflags)
2444 {
2445         int error;
2446
2447         flags |= LLE_ADDRONLY;
2448         error = nd6_resolve_slow(ifp, flags, NULL,
2449             (const struct sockaddr_in6 *)dst, desten, pflags, NULL);
2450         return (error);
2451 }
2452
2453 int
2454 nd6_flush_holdchain(struct ifnet *ifp, struct mbuf *chain,
2455     struct sockaddr_in6 *dst)
2456 {
2457         struct mbuf *m, *m_head;
2458         int error = 0;
2459
2460         m_head = chain;
2461
2462         while (m_head) {
2463                 m = m_head;
2464                 m_head = m_head->m_nextpkt;
2465                 m->m_nextpkt = NULL;
2466                 error = nd6_output_ifp(ifp, ifp, m, dst, NULL);
2467         }
2468
2469         /*
2470          * XXX
2471          * note that intermediate errors are blindly ignored
2472          */
2473         return (error);
2474 }
2475
2476 static int
2477 nd6_need_cache(struct ifnet *ifp)
2478 {
2479         /*
2480          * XXX: we currently do not make neighbor cache on any interface
2481          * other than Ethernet and GIF.
2482          *
2483          * RFC2893 says:
2484          * - unidirectional tunnels needs no ND
2485          */
2486         switch (ifp->if_type) {
2487         case IFT_ETHER:
2488         case IFT_IEEE1394:
2489         case IFT_L2VLAN:
2490         case IFT_INFINIBAND:
2491         case IFT_BRIDGE:
2492         case IFT_PROPVIRTUAL:
2493                 return (1);
2494         default:
2495                 return (0);
2496         }
2497 }
2498
2499 /*
2500  * Add pernament ND6 link-layer record for given
2501  * interface address.
2502  *
2503  * Very similar to IPv4 arp_ifinit(), but:
2504  * 1) IPv6 DAD is performed in different place
2505  * 2) It is called by IPv6 protocol stack in contrast to
2506  * arp_ifinit() which is typically called in SIOCSIFADDR
2507  * driver ioctl handler.
2508  *
2509  */
2510 int
2511 nd6_add_ifa_lle(struct in6_ifaddr *ia)
2512 {
2513         struct ifnet *ifp;
2514         struct llentry *ln, *ln_tmp;
2515         struct sockaddr *dst;
2516
2517         ifp = ia->ia_ifa.ifa_ifp;
2518         if (nd6_need_cache(ifp) == 0)
2519                 return (0);
2520
2521         dst = (struct sockaddr *)&ia->ia_addr;
2522         ln = lltable_alloc_entry(LLTABLE6(ifp), LLE_IFADDR, dst);
2523         if (ln == NULL)
2524                 return (ENOBUFS);
2525
2526         IF_AFDATA_WLOCK(ifp);
2527         LLE_WLOCK(ln);
2528         /* Unlink any entry if exists */
2529         ln_tmp = lla_lookup(LLTABLE6(ifp), LLE_EXCLUSIVE, dst);
2530         if (ln_tmp != NULL)
2531                 lltable_unlink_entry(LLTABLE6(ifp), ln_tmp);
2532         lltable_link_entry(LLTABLE6(ifp), ln);
2533         IF_AFDATA_WUNLOCK(ifp);
2534
2535         if (ln_tmp != NULL)
2536                 EVENTHANDLER_INVOKE(lle_event, ln_tmp, LLENTRY_EXPIRED);
2537         EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
2538
2539         LLE_WUNLOCK(ln);
2540         if (ln_tmp != NULL)
2541                 llentry_free(ln_tmp);
2542
2543         return (0);
2544 }
2545
2546 /*
2547  * Removes either all lle entries for given @ia, or lle
2548  * corresponding to @ia address.
2549  */
2550 void
2551 nd6_rem_ifa_lle(struct in6_ifaddr *ia, int all)
2552 {
2553         struct sockaddr_in6 mask, addr;
2554         struct sockaddr *saddr, *smask;
2555         struct ifnet *ifp;
2556
2557         ifp = ia->ia_ifa.ifa_ifp;
2558         memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
2559         memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
2560         saddr = (struct sockaddr *)&addr;
2561         smask = (struct sockaddr *)&mask;
2562
2563         if (all != 0)
2564                 lltable_prefix_free(AF_INET6, saddr, smask, LLE_STATIC);
2565         else
2566                 lltable_delete_addr(LLTABLE6(ifp), LLE_IFADDR, saddr);
2567 }
2568
2569 static void 
2570 clear_llinfo_pqueue(struct llentry *ln)
2571 {
2572         struct mbuf *m_hold, *m_hold_next;
2573
2574         for (m_hold = ln->la_hold; m_hold; m_hold = m_hold_next) {
2575                 m_hold_next = m_hold->m_nextpkt;
2576                 m_freem(m_hold);
2577         }
2578
2579         ln->la_hold = NULL;
2580 }
2581
2582 static int
2583 nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2584 {
2585         struct in6_prefix p;
2586         struct sockaddr_in6 s6;
2587         struct nd_prefix *pr;
2588         struct nd_pfxrouter *pfr;
2589         time_t maxexpire;
2590         int error;
2591         char ip6buf[INET6_ADDRSTRLEN];
2592
2593         if (req->newptr)
2594                 return (EPERM);
2595
2596         error = sysctl_wire_old_buffer(req, 0);
2597         if (error != 0)
2598                 return (error);
2599
2600         bzero(&p, sizeof(p));
2601         p.origin = PR_ORIG_RA;
2602         bzero(&s6, sizeof(s6));
2603         s6.sin6_family = AF_INET6;
2604         s6.sin6_len = sizeof(s6);
2605
2606         ND6_RLOCK();
2607         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
2608                 p.prefix = pr->ndpr_prefix;
2609                 if (sa6_recoverscope(&p.prefix)) {
2610                         log(LOG_ERR, "scope error in prefix list (%s)\n",
2611                             ip6_sprintf(ip6buf, &p.prefix.sin6_addr));
2612                         /* XXX: press on... */
2613                 }
2614                 p.raflags = pr->ndpr_raf;
2615                 p.prefixlen = pr->ndpr_plen;
2616                 p.vltime = pr->ndpr_vltime;
2617                 p.pltime = pr->ndpr_pltime;
2618                 p.if_index = pr->ndpr_ifp->if_index;
2619                 if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2620                         p.expire = 0;
2621                 else {
2622                         /* XXX: we assume time_t is signed. */
2623                         maxexpire = (-1) &
2624                             ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
2625                         if (pr->ndpr_vltime < maxexpire - pr->ndpr_lastupdate)
2626                                 p.expire = pr->ndpr_lastupdate +
2627                                     pr->ndpr_vltime +
2628                                     (time_second - time_uptime);
2629                         else
2630                                 p.expire = maxexpire;
2631                 }
2632                 p.refcnt = pr->ndpr_addrcnt;
2633                 p.flags = pr->ndpr_stateflags;
2634                 p.advrtrs = 0;
2635                 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
2636                         p.advrtrs++;
2637                 error = SYSCTL_OUT(req, &p, sizeof(p));
2638                 if (error != 0)
2639                         break;
2640                 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
2641                         s6.sin6_addr = pfr->router->rtaddr;
2642                         if (sa6_recoverscope(&s6))
2643                                 log(LOG_ERR,
2644                                     "scope error in prefix list (%s)\n",
2645                                     ip6_sprintf(ip6buf, &pfr->router->rtaddr));
2646                         error = SYSCTL_OUT(req, &s6, sizeof(s6));
2647                         if (error != 0)
2648                                 goto out;
2649                 }
2650         }
2651 out:
2652         ND6_RUNLOCK();
2653         return (error);
2654 }
2655 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2656         CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2657         NULL, 0, nd6_sysctl_prlist, "S,in6_prefix",
2658         "NDP prefix list");
2659 SYSCTL_INT(_net_inet6_icmp6, ICMPV6CTL_ND6_MAXQLEN, nd6_maxqueuelen,
2660         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_maxqueuelen), 1, "");
2661 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, nd6_gctimer,
2662         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_gctimer), (60 * 60 * 24), "");