]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/nd6.c
[lltable] Restructure nd6 code.
[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;
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_hittime = llentry_get_hittime(lle);
629
630         if (lle_hittime == 0) {
631                 /*
632                  * Datapath feedback has been requested upon entering
633                  * STALE state. No packets has been passed using this lle.
634                  * Ask for the timer reschedule and keep STALE state.
635                  */
636                 delay = (long)(MIN(nd_gctimer, nd_delay));
637                 delay *= hz;
638                 if (lle->lle_remtime > delay)
639                         lle->lle_remtime -= delay;
640                 else {
641                         delay = lle->lle_remtime;
642                         lle->lle_remtime = 0;
643                 }
644
645                 if (delay == 0) {
646                         /*
647                          * The original ng6_gctime timeout ended,
648                          * no more rescheduling.
649                          */
650                         return (0);
651                 }
652
653                 *pdelay = delay;
654                 return (1);
655         }
656
657         /*
658          * Packet received. Verify timestamp
659          */
660         delay = (long)(time_uptime - lle_hittime);
661         if (delay < nd_delay) {
662                 /*
663                  * V_nd6_delay still not passed since the first
664                  * hit in STALE state.
665                  * Reshedule timer and return.
666                  */
667                 *pdelay = (long)(nd_delay - delay) * hz;
668                 return (1);
669         }
670
671         /* Request switching to probe */
672         *do_switch = 1;
673         return (0);
674 }
675
676 /*
677  * Switch @lle state to new state optionally arming timers.
678  *
679  * Set noinline to be dtrace-friendly
680  */
681 __noinline void
682 nd6_llinfo_setstate(struct llentry *lle, int newstate)
683 {
684         struct ifnet *ifp;
685         int nd_gctimer, nd_delay;
686         long delay, remtime;
687
688         delay = 0;
689         remtime = 0;
690
691         switch (newstate) {
692         case ND6_LLINFO_INCOMPLETE:
693                 ifp = lle->lle_tbl->llt_ifp;
694                 delay = (long)ND_IFINFO(ifp)->retrans * hz / 1000;
695                 break;
696         case ND6_LLINFO_REACHABLE:
697                 if (!ND6_LLINFO_PERMANENT(lle)) {
698                         ifp = lle->lle_tbl->llt_ifp;
699                         delay = (long)ND_IFINFO(ifp)->reachable * hz;
700                 }
701                 break;
702         case ND6_LLINFO_STALE:
703
704                 llentry_request_feedback(lle);
705                 nd_delay = V_nd6_delay;
706                 nd_gctimer = V_nd6_gctimer;
707
708                 delay = (long)(MIN(nd_gctimer, nd_delay)) * hz;
709                 remtime = (long)nd_gctimer * hz - delay;
710                 break;
711         case ND6_LLINFO_DELAY:
712                 lle->la_asked = 0;
713                 delay = (long)V_nd6_delay * hz;
714                 break;
715         }
716
717         if (delay > 0)
718                 nd6_llinfo_settimer_locked(lle, delay);
719
720         lle->lle_remtime = remtime;
721         lle->ln_state = newstate;
722 }
723
724 /*
725  * Timer-dependent part of nd state machine.
726  *
727  * Set noinline to be dtrace-friendly
728  */
729 static __noinline void
730 nd6_llinfo_timer(void *arg)
731 {
732         struct epoch_tracker et;
733         struct llentry *ln;
734         struct in6_addr *dst, *pdst, *psrc, src;
735         struct ifnet *ifp;
736         struct nd_ifinfo *ndi;
737         int do_switch, send_ns;
738         long delay;
739
740         KASSERT(arg != NULL, ("%s: arg NULL", __func__));
741         ln = (struct llentry *)arg;
742         ifp = lltable_get_ifp(ln->lle_tbl);
743         CURVNET_SET(ifp->if_vnet);
744
745         ND6_RLOCK();
746         LLE_WLOCK(ln);
747         if (callout_pending(&ln->lle_timer)) {
748                 /*
749                  * Here we are a bit odd here in the treatment of 
750                  * active/pending. If the pending bit is set, it got
751                  * rescheduled before I ran. The active
752                  * bit we ignore, since if it was stopped
753                  * in ll_tablefree() and was currently running
754                  * it would have return 0 so the code would
755                  * not have deleted it since the callout could
756                  * not be stopped so we want to go through
757                  * with the delete here now. If the callout
758                  * was restarted, the pending bit will be back on and
759                  * we just want to bail since the callout_reset would
760                  * return 1 and our reference would have been removed
761                  * by nd6_llinfo_settimer_locked above since canceled
762                  * would have been 1.
763                  */
764                 LLE_WUNLOCK(ln);
765                 ND6_RUNLOCK();
766                 CURVNET_RESTORE();
767                 return;
768         }
769         NET_EPOCH_ENTER(et);
770         ndi = ND_IFINFO(ifp);
771         send_ns = 0;
772         dst = &ln->r_l3addr.addr6;
773         pdst = dst;
774
775         if (ln->ln_ntick > 0) {
776                 if (ln->ln_ntick > INT_MAX) {
777                         ln->ln_ntick -= INT_MAX;
778                         nd6_llinfo_settimer_locked(ln, INT_MAX);
779                 } else {
780                         ln->ln_ntick = 0;
781                         nd6_llinfo_settimer_locked(ln, ln->ln_ntick);
782                 }
783                 goto done;
784         }
785
786         if (ln->la_flags & LLE_STATIC) {
787                 goto done;
788         }
789
790         if (ln->la_flags & LLE_DELETED) {
791                 nd6_free(&ln, 0);
792                 goto done;
793         }
794
795         switch (ln->ln_state) {
796         case ND6_LLINFO_INCOMPLETE:
797                 if (ln->la_asked < V_nd6_mmaxtries) {
798                         ln->la_asked++;
799                         send_ns = 1;
800                         /* Send NS to multicast address */
801                         pdst = NULL;
802                 } else {
803                         struct mbuf *m = ln->la_hold;
804                         if (m) {
805                                 struct mbuf *m0;
806
807                                 /*
808                                  * assuming every packet in la_hold has the
809                                  * same IP header.  Send error after unlock.
810                                  */
811                                 m0 = m->m_nextpkt;
812                                 m->m_nextpkt = NULL;
813                                 ln->la_hold = m0;
814                                 clear_llinfo_pqueue(ln);
815                         }
816                         nd6_free(&ln, 0);
817                         if (m != NULL) {
818                                 struct mbuf *n = m;
819
820                                 /*
821                                  * if there are any ummapped mbufs, we
822                                  * must free them, rather than using
823                                  * them for an ICMP, as they cannot be
824                                  * checksummed.
825                                  */
826                                 while ((n = n->m_next) != NULL) {
827                                         if (n->m_flags & M_EXTPG)
828                                                 break;
829                                 }
830                                 if (n != NULL) {
831                                         m_freem(m);
832                                         m = NULL;
833                                 } else {
834                                         icmp6_error2(m, ICMP6_DST_UNREACH,
835                                             ICMP6_DST_UNREACH_ADDR, 0, ifp);
836                                 }
837                         }
838                 }
839                 break;
840         case ND6_LLINFO_REACHABLE:
841                 if (!ND6_LLINFO_PERMANENT(ln))
842                         nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
843                 break;
844
845         case ND6_LLINFO_STALE:
846                 if (nd6_is_stale(ln, &delay, &do_switch) != 0) {
847                         /*
848                          * No packet has used this entry and GC timeout
849                          * has not been passed. Reshedule timer and
850                          * return.
851                          */
852                         nd6_llinfo_settimer_locked(ln, delay);
853                         break;
854                 }
855
856                 if (do_switch == 0) {
857                         /*
858                          * GC timer has ended and entry hasn't been used.
859                          * Run Garbage collector (RFC 4861, 5.3)
860                          */
861                         if (!ND6_LLINFO_PERMANENT(ln))
862                                 nd6_free(&ln, 1);
863                         break;
864                 }
865
866                 /* Entry has been used AND delay timer has ended. */
867
868                 /* FALLTHROUGH */
869
870         case ND6_LLINFO_DELAY:
871                 if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
872                         /* We need NUD */
873                         ln->la_asked = 1;
874                         nd6_llinfo_setstate(ln, ND6_LLINFO_PROBE);
875                         send_ns = 1;
876                 } else
877                         nd6_llinfo_setstate(ln, ND6_LLINFO_STALE); /* XXX */
878                 break;
879         case ND6_LLINFO_PROBE:
880                 if (ln->la_asked < V_nd6_umaxtries) {
881                         ln->la_asked++;
882                         send_ns = 1;
883                 } else {
884                         nd6_free(&ln, 0);
885                 }
886                 break;
887         default:
888                 panic("%s: paths in a dark night can be confusing: %d",
889                     __func__, ln->ln_state);
890         }
891 done:
892         if (ln != NULL)
893                 ND6_RUNLOCK();
894         if (send_ns != 0) {
895                 nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
896                 psrc = nd6_llinfo_get_holdsrc(ln, &src);
897                 LLE_FREE_LOCKED(ln);
898                 ln = NULL;
899                 nd6_ns_output(ifp, psrc, pdst, dst, NULL);
900         }
901
902         if (ln != NULL)
903                 LLE_FREE_LOCKED(ln);
904         NET_EPOCH_EXIT(et);
905         CURVNET_RESTORE();
906 }
907
908 /*
909  * ND6 timer routine to expire default route list and prefix list
910  */
911 void
912 nd6_timer(void *arg)
913 {
914         CURVNET_SET((struct vnet *) arg);
915         struct epoch_tracker et;
916         struct nd_prhead prl;
917         struct nd_prefix *pr, *npr;
918         struct ifnet *ifp;
919         struct in6_ifaddr *ia6, *nia6;
920         uint64_t genid;
921
922         LIST_INIT(&prl);
923
924         NET_EPOCH_ENTER(et);
925         nd6_defrouter_timer();
926
927         /*
928          * expire interface addresses.
929          * in the past the loop was inside prefix expiry processing.
930          * However, from a stricter speci-confrmance standpoint, we should
931          * rather separate address lifetimes and prefix lifetimes.
932          *
933          * XXXRW: in6_ifaddrhead locking.
934          */
935   addrloop:
936         CK_STAILQ_FOREACH_SAFE(ia6, &V_in6_ifaddrhead, ia_link, nia6) {
937                 /* check address lifetime */
938                 if (IFA6_IS_INVALID(ia6)) {
939                         int regen = 0;
940
941                         /*
942                          * If the expiring address is temporary, try
943                          * regenerating a new one.  This would be useful when
944                          * we suspended a laptop PC, then turned it on after a
945                          * period that could invalidate all temporary
946                          * addresses.  Although we may have to restart the
947                          * loop (see below), it must be after purging the
948                          * address.  Otherwise, we'd see an infinite loop of
949                          * regeneration.
950                          */
951                         if (V_ip6_use_tempaddr &&
952                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
953                                 if (regen_tmpaddr(ia6) == 0)
954                                         regen = 1;
955                         }
956
957                         in6_purgeaddr(&ia6->ia_ifa);
958
959                         if (regen)
960                                 goto addrloop; /* XXX: see below */
961                 } else if (IFA6_IS_DEPRECATED(ia6)) {
962                         int oldflags = ia6->ia6_flags;
963
964                         ia6->ia6_flags |= IN6_IFF_DEPRECATED;
965
966                         /*
967                          * If a temporary address has just become deprecated,
968                          * regenerate a new one if possible.
969                          */
970                         if (V_ip6_use_tempaddr &&
971                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
972                             (oldflags & IN6_IFF_DEPRECATED) == 0) {
973                                 if (regen_tmpaddr(ia6) == 0) {
974                                         /*
975                                          * A new temporary address is
976                                          * generated.
977                                          * XXX: this means the address chain
978                                          * has changed while we are still in
979                                          * the loop.  Although the change
980                                          * would not cause disaster (because
981                                          * it's not a deletion, but an
982                                          * addition,) we'd rather restart the
983                                          * loop just for safety.  Or does this
984                                          * significantly reduce performance??
985                                          */
986                                         goto addrloop;
987                                 }
988                         }
989                 } else if ((ia6->ia6_flags & IN6_IFF_TENTATIVE) != 0) {
990                         /*
991                          * Schedule DAD for a tentative address.  This happens
992                          * if the interface was down or not running
993                          * when the address was configured.
994                          */
995                         int delay;
996
997                         delay = arc4random() %
998                             (MAX_RTR_SOLICITATION_DELAY * hz);
999                         nd6_dad_start((struct ifaddr *)ia6, delay);
1000                 } else {
1001                         /*
1002                          * Check status of the interface.  If it is down,
1003                          * mark the address as tentative for future DAD.
1004                          */
1005                         ifp = ia6->ia_ifp;
1006                         if ((ND_IFINFO(ifp)->flags & ND6_IFF_NO_DAD) == 0 &&
1007                             ((ifp->if_flags & IFF_UP) == 0 ||
1008                             (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
1009                             (ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) != 0)){
1010                                 ia6->ia6_flags &= ~IN6_IFF_DUPLICATED;
1011                                 ia6->ia6_flags |= IN6_IFF_TENTATIVE;
1012                         }
1013
1014                         /*
1015                          * A new RA might have made a deprecated address
1016                          * preferred.
1017                          */
1018                         ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
1019                 }
1020         }
1021         NET_EPOCH_EXIT(et);
1022
1023         ND6_WLOCK();
1024 restart:
1025         LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
1026                 /*
1027                  * Expire prefixes. Since the pltime is only used for
1028                  * autoconfigured addresses, pltime processing for prefixes is
1029                  * not necessary.
1030                  *
1031                  * Only unlink after all derived addresses have expired. This
1032                  * may not occur until two hours after the prefix has expired
1033                  * per RFC 4862. If the prefix expires before its derived
1034                  * addresses, mark it off-link. This will be done automatically
1035                  * after unlinking if no address references remain.
1036                  */
1037                 if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME ||
1038                     time_uptime - pr->ndpr_lastupdate <= pr->ndpr_vltime)
1039                         continue;
1040
1041                 if (pr->ndpr_addrcnt == 0) {
1042                         nd6_prefix_unlink(pr, &prl);
1043                         continue;
1044                 }
1045                 if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1046                         genid = V_nd6_list_genid;
1047                         nd6_prefix_ref(pr);
1048                         ND6_WUNLOCK();
1049                         ND6_ONLINK_LOCK();
1050                         (void)nd6_prefix_offlink(pr);
1051                         ND6_ONLINK_UNLOCK();
1052                         ND6_WLOCK();
1053                         nd6_prefix_rele(pr);
1054                         if (genid != V_nd6_list_genid)
1055                                 goto restart;
1056                 }
1057         }
1058         ND6_WUNLOCK();
1059
1060         while ((pr = LIST_FIRST(&prl)) != NULL) {
1061                 LIST_REMOVE(pr, ndpr_entry);
1062                 nd6_prefix_del(pr);
1063         }
1064
1065         callout_reset(&V_nd6_timer_ch, V_nd6_prune * hz,
1066             nd6_timer, curvnet);
1067
1068         CURVNET_RESTORE();
1069 }
1070
1071 /*
1072  * ia6 - deprecated/invalidated temporary address
1073  */
1074 static int
1075 regen_tmpaddr(struct in6_ifaddr *ia6)
1076 {
1077         struct ifaddr *ifa;
1078         struct ifnet *ifp;
1079         struct in6_ifaddr *public_ifa6 = NULL;
1080
1081         NET_EPOCH_ASSERT();
1082
1083         ifp = ia6->ia_ifa.ifa_ifp;
1084         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1085                 struct in6_ifaddr *it6;
1086
1087                 if (ifa->ifa_addr->sa_family != AF_INET6)
1088                         continue;
1089
1090                 it6 = (struct in6_ifaddr *)ifa;
1091
1092                 /* ignore no autoconf addresses. */
1093                 if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1094                         continue;
1095
1096                 /* ignore autoconf addresses with different prefixes. */
1097                 if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
1098                         continue;
1099
1100                 /*
1101                  * Now we are looking at an autoconf address with the same
1102                  * prefix as ours.  If the address is temporary and is still
1103                  * preferred, do not create another one.  It would be rare, but
1104                  * could happen, for example, when we resume a laptop PC after
1105                  * a long period.
1106                  */
1107                 if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1108                     !IFA6_IS_DEPRECATED(it6)) {
1109                         public_ifa6 = NULL;
1110                         break;
1111                 }
1112
1113                 /*
1114                  * This is a public autoconf address that has the same prefix
1115                  * as ours.  If it is preferred, keep it.  We can't break the
1116                  * loop here, because there may be a still-preferred temporary
1117                  * address with the prefix.
1118                  */
1119                 if (!IFA6_IS_DEPRECATED(it6))
1120                         public_ifa6 = it6;
1121         }
1122         if (public_ifa6 != NULL)
1123                 ifa_ref(&public_ifa6->ia_ifa);
1124
1125         if (public_ifa6 != NULL) {
1126                 int e;
1127
1128                 if ((e = in6_tmpifadd(public_ifa6, 0, 0)) != 0) {
1129                         ifa_free(&public_ifa6->ia_ifa);
1130                         log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
1131                             " tmp addr,errno=%d\n", e);
1132                         return (-1);
1133                 }
1134                 ifa_free(&public_ifa6->ia_ifa);
1135                 return (0);
1136         }
1137
1138         return (-1);
1139 }
1140
1141 /*
1142  * Remove prefix and default router list entries corresponding to ifp. Neighbor
1143  * cache entries are freed in in6_domifdetach().
1144  */
1145 void
1146 nd6_purge(struct ifnet *ifp)
1147 {
1148         struct nd_prhead prl;
1149         struct nd_prefix *pr, *npr;
1150
1151         LIST_INIT(&prl);
1152
1153         /* Purge default router list entries toward ifp. */
1154         nd6_defrouter_purge(ifp);
1155
1156         ND6_WLOCK();
1157         /*
1158          * Remove prefixes on ifp. We should have already removed addresses on
1159          * this interface, so no addresses should be referencing these prefixes.
1160          */
1161         LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
1162                 if (pr->ndpr_ifp == ifp)
1163                         nd6_prefix_unlink(pr, &prl);
1164         }
1165         ND6_WUNLOCK();
1166
1167         /* Delete the unlinked prefix objects. */
1168         while ((pr = LIST_FIRST(&prl)) != NULL) {
1169                 LIST_REMOVE(pr, ndpr_entry);
1170                 nd6_prefix_del(pr);
1171         }
1172
1173         /* cancel default outgoing interface setting */
1174         if (V_nd6_defifindex == ifp->if_index)
1175                 nd6_setdefaultiface(0);
1176
1177         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1178                 /* Refresh default router list. */
1179                 defrouter_select_fib(ifp->if_fib);
1180         }
1181 }
1182
1183 /* 
1184  * the caller acquires and releases the lock on the lltbls
1185  * Returns the llentry locked
1186  */
1187 struct llentry *
1188 nd6_lookup(const struct in6_addr *addr6, int flags, struct ifnet *ifp)
1189 {
1190         struct sockaddr_in6 sin6;
1191         struct llentry *ln;
1192
1193         bzero(&sin6, sizeof(sin6));
1194         sin6.sin6_len = sizeof(struct sockaddr_in6);
1195         sin6.sin6_family = AF_INET6;
1196         sin6.sin6_addr = *addr6;
1197
1198         IF_AFDATA_LOCK_ASSERT(ifp);
1199
1200         ln = lla_lookup(LLTABLE6(ifp), flags, (struct sockaddr *)&sin6);
1201
1202         return (ln);
1203 }
1204
1205 static struct llentry *
1206 nd6_alloc(const struct in6_addr *addr6, int flags, struct ifnet *ifp)
1207 {
1208         struct sockaddr_in6 sin6;
1209         struct llentry *ln;
1210
1211         bzero(&sin6, sizeof(sin6));
1212         sin6.sin6_len = sizeof(struct sockaddr_in6);
1213         sin6.sin6_family = AF_INET6;
1214         sin6.sin6_addr = *addr6;
1215
1216         ln = lltable_alloc_entry(LLTABLE6(ifp), 0, (struct sockaddr *)&sin6);
1217         if (ln != NULL)
1218                 ln->ln_state = ND6_LLINFO_NOSTATE;
1219
1220         return (ln);
1221 }
1222
1223 /*
1224  * Test whether a given IPv6 address is a neighbor or not, ignoring
1225  * the actual neighbor cache.  The neighbor cache is ignored in order
1226  * to not reenter the routing code from within itself.
1227  */
1228 static int
1229 nd6_is_new_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
1230 {
1231         struct nd_prefix *pr;
1232         struct ifaddr *ifa;
1233         struct rt_addrinfo info;
1234         struct sockaddr_in6 rt_key;
1235         const struct sockaddr *dst6;
1236         uint64_t genid;
1237         int error, fibnum;
1238
1239         /*
1240          * A link-local address is always a neighbor.
1241          * XXX: a link does not necessarily specify a single interface.
1242          */
1243         if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
1244                 struct sockaddr_in6 sin6_copy;
1245                 u_int32_t zone;
1246
1247                 /*
1248                  * We need sin6_copy since sa6_recoverscope() may modify the
1249                  * content (XXX).
1250                  */
1251                 sin6_copy = *addr;
1252                 if (sa6_recoverscope(&sin6_copy))
1253                         return (0); /* XXX: should be impossible */
1254                 if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
1255                         return (0);
1256                 if (sin6_copy.sin6_scope_id == zone)
1257                         return (1);
1258                 else
1259                         return (0);
1260         }
1261
1262         bzero(&rt_key, sizeof(rt_key));
1263         bzero(&info, sizeof(info));
1264         info.rti_info[RTAX_DST] = (struct sockaddr *)&rt_key;
1265
1266         /*
1267          * If the address matches one of our addresses,
1268          * it should be a neighbor.
1269          * If the address matches one of our on-link prefixes, it should be a
1270          * neighbor.
1271          */
1272         ND6_RLOCK();
1273 restart:
1274         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1275                 if (pr->ndpr_ifp != ifp)
1276                         continue;
1277
1278                 if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1279                         dst6 = (const struct sockaddr *)&pr->ndpr_prefix;
1280
1281                         /*
1282                          * We only need to check all FIBs if add_addr_allfibs
1283                          * is unset. If set, checking any FIB will suffice.
1284                          */
1285                         fibnum = V_rt_add_addr_allfibs ? rt_numfibs - 1 : 0;
1286                         for (; fibnum < rt_numfibs; fibnum++) {
1287                                 genid = V_nd6_list_genid;
1288                                 ND6_RUNLOCK();
1289
1290                                 /*
1291                                  * Restore length field before
1292                                  * retrying lookup
1293                                  */
1294                                 rt_key.sin6_len = sizeof(rt_key);
1295                                 error = rib_lookup_info(fibnum, dst6, 0, 0,
1296                                                         &info);
1297
1298                                 ND6_RLOCK();
1299                                 if (genid != V_nd6_list_genid)
1300                                         goto restart;
1301                                 if (error == 0)
1302                                         break;
1303                         }
1304                         if (error != 0)
1305                                 continue;
1306
1307                         /*
1308                          * This is the case where multiple interfaces
1309                          * have the same prefix, but only one is installed 
1310                          * into the routing table and that prefix entry
1311                          * is not the one being examined here.
1312                          */
1313                         if (!IN6_ARE_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
1314                             &rt_key.sin6_addr))
1315                                 continue;
1316                 }
1317
1318                 if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
1319                     &addr->sin6_addr, &pr->ndpr_mask)) {
1320                         ND6_RUNLOCK();
1321                         return (1);
1322                 }
1323         }
1324         ND6_RUNLOCK();
1325
1326         /*
1327          * If the address is assigned on the node of the other side of
1328          * a p2p interface, the address should be a neighbor.
1329          */
1330         if (ifp->if_flags & IFF_POINTOPOINT) {
1331                 struct epoch_tracker et;
1332
1333                 NET_EPOCH_ENTER(et);
1334                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1335                         if (ifa->ifa_addr->sa_family != addr->sin6_family)
1336                                 continue;
1337                         if (ifa->ifa_dstaddr != NULL &&
1338                             sa_equal(addr, ifa->ifa_dstaddr)) {
1339                                 NET_EPOCH_EXIT(et);
1340                                 return 1;
1341                         }
1342                 }
1343                 NET_EPOCH_EXIT(et);
1344         }
1345
1346         /*
1347          * If the default router list is empty, all addresses are regarded
1348          * as on-link, and thus, as a neighbor.
1349          */
1350         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV &&
1351             nd6_defrouter_list_empty() &&
1352             V_nd6_defifindex == ifp->if_index) {
1353                 return (1);
1354         }
1355
1356         return (0);
1357 }
1358
1359 /*
1360  * Detect if a given IPv6 address identifies a neighbor on a given link.
1361  * XXX: should take care of the destination of a p2p link?
1362  */
1363 int
1364 nd6_is_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
1365 {
1366         struct llentry *lle;
1367         int rc = 0;
1368
1369         NET_EPOCH_ASSERT();
1370         IF_AFDATA_UNLOCK_ASSERT(ifp);
1371         if (nd6_is_new_addr_neighbor(addr, ifp))
1372                 return (1);
1373
1374         /*
1375          * Even if the address matches none of our addresses, it might be
1376          * in the neighbor cache.
1377          */
1378         if ((lle = nd6_lookup(&addr->sin6_addr, 0, ifp)) != NULL) {
1379                 LLE_RUNLOCK(lle);
1380                 rc = 1;
1381         }
1382         return (rc);
1383 }
1384
1385 /*
1386  * Tries to update @lle address/prepend data with new @lladdr.
1387  *
1388  * Returns true on success.
1389  * In any case, @lle is returned wlocked.
1390  */
1391 bool
1392 nd6_try_set_entry_addr(struct ifnet *ifp, struct llentry *lle, char *lladdr)
1393 {
1394         u_char linkhdr[LLE_MAX_LINKHDR];
1395         size_t linkhdrsize;
1396         int lladdr_off;
1397
1398         LLE_WLOCK_ASSERT(lle);
1399
1400         linkhdrsize = sizeof(linkhdr);
1401         if (lltable_calc_llheader(ifp, AF_INET6, lladdr,
1402             linkhdr, &linkhdrsize, &lladdr_off) != 0) {
1403                 return (false);
1404         }
1405
1406         if (!lltable_acquire_wlock(ifp, lle))
1407                 return (false);
1408         lltable_set_entry_addr(ifp, lle, linkhdr, linkhdrsize, lladdr_off);
1409         IF_AFDATA_WUNLOCK(ifp);
1410
1411         return (true);
1412 }
1413
1414 /*
1415  * Free an nd6 llinfo entry.
1416  * Since the function would cause significant changes in the kernel, DO NOT
1417  * make it global, unless you have a strong reason for the change, and are sure
1418  * that the change is safe.
1419  *
1420  * Set noinline to be dtrace-friendly
1421  */
1422 static __noinline void
1423 nd6_free(struct llentry **lnp, int gc)
1424 {
1425         struct ifnet *ifp;
1426         struct llentry *ln;
1427         struct nd_defrouter *dr;
1428
1429         ln = *lnp;
1430         *lnp = NULL;
1431
1432         LLE_WLOCK_ASSERT(ln);
1433         ND6_RLOCK_ASSERT();
1434
1435         ifp = lltable_get_ifp(ln->lle_tbl);
1436         if ((ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) != 0)
1437                 dr = defrouter_lookup_locked(&ln->r_l3addr.addr6, ifp);
1438         else
1439                 dr = NULL;
1440         ND6_RUNLOCK();
1441
1442         if ((ln->la_flags & LLE_DELETED) == 0)
1443                 EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_EXPIRED);
1444
1445         /*
1446          * we used to have pfctlinput(PRC_HOSTDEAD) here.
1447          * even though it is not harmful, it was not really necessary.
1448          */
1449
1450         /* cancel timer */
1451         nd6_llinfo_settimer_locked(ln, -1);
1452
1453         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1454                 if (dr != NULL && dr->expire &&
1455                     ln->ln_state == ND6_LLINFO_STALE && gc) {
1456                         /*
1457                          * If the reason for the deletion is just garbage
1458                          * collection, and the neighbor is an active default
1459                          * router, do not delete it.  Instead, reset the GC
1460                          * timer using the router's lifetime.
1461                          * Simply deleting the entry would affect default
1462                          * router selection, which is not necessarily a good
1463                          * thing, especially when we're using router preference
1464                          * values.
1465                          * XXX: the check for ln_state would be redundant,
1466                          *      but we intentionally keep it just in case.
1467                          */
1468                         if (dr->expire > time_uptime)
1469                                 nd6_llinfo_settimer_locked(ln,
1470                                     (dr->expire - time_uptime) * hz);
1471                         else
1472                                 nd6_llinfo_settimer_locked(ln,
1473                                     (long)V_nd6_gctimer * hz);
1474
1475                         LLE_REMREF(ln);
1476                         LLE_WUNLOCK(ln);
1477                         defrouter_rele(dr);
1478                         return;
1479                 }
1480
1481                 if (dr) {
1482                         /*
1483                          * Unreachablity of a router might affect the default
1484                          * router selection and on-link detection of advertised
1485                          * prefixes.
1486                          */
1487
1488                         /*
1489                          * Temporarily fake the state to choose a new default
1490                          * router and to perform on-link determination of
1491                          * prefixes correctly.
1492                          * Below the state will be set correctly,
1493                          * or the entry itself will be deleted.
1494                          */
1495                         ln->ln_state = ND6_LLINFO_INCOMPLETE;
1496                 }
1497
1498                 if (ln->ln_router || dr) {
1499                         /*
1500                          * We need to unlock to avoid a LOR with rt6_flush() with the
1501                          * rnh and for the calls to pfxlist_onlink_check() and
1502                          * defrouter_select_fib() in the block further down for calls
1503                          * into nd6_lookup().  We still hold a ref.
1504                          */
1505                         LLE_WUNLOCK(ln);
1506
1507                         /*
1508                          * rt6_flush must be called whether or not the neighbor
1509                          * is in the Default Router List.
1510                          * See a corresponding comment in nd6_na_input().
1511                          */
1512                         rt6_flush(&ln->r_l3addr.addr6, ifp);
1513                 }
1514
1515                 if (dr) {
1516                         /*
1517                          * Since defrouter_select_fib() does not affect the
1518                          * on-link determination and MIP6 needs the check
1519                          * before the default router selection, we perform
1520                          * the check now.
1521                          */
1522                         pfxlist_onlink_check();
1523
1524                         /*
1525                          * Refresh default router list.
1526                          */
1527                         defrouter_select_fib(dr->ifp->if_fib);
1528                 }
1529
1530                 /*
1531                  * If this entry was added by an on-link redirect, remove the
1532                  * corresponding host route.
1533                  */
1534                 if (ln->la_flags & LLE_REDIRECT)
1535                         nd6_free_redirect(ln);
1536
1537                 if (ln->ln_router || dr)
1538                         LLE_WLOCK(ln);
1539         }
1540
1541         /*
1542          * Save to unlock. We still hold an extra reference and will not
1543          * free(9) in llentry_free() if someone else holds one as well.
1544          */
1545         LLE_WUNLOCK(ln);
1546         IF_AFDATA_LOCK(ifp);
1547         LLE_WLOCK(ln);
1548         /* Guard against race with other llentry_free(). */
1549         if (ln->la_flags & LLE_LINKED) {
1550                 /* Remove callout reference */
1551                 LLE_REMREF(ln);
1552                 lltable_unlink_entry(ln->lle_tbl, ln);
1553         }
1554         IF_AFDATA_UNLOCK(ifp);
1555
1556         llentry_free(ln);
1557         if (dr != NULL)
1558                 defrouter_rele(dr);
1559 }
1560
1561 static int
1562 nd6_isdynrte(const struct rtentry *rt, const struct nhop_object *nh, void *xap)
1563 {
1564
1565         if (nh->nh_flags & NHF_REDIRECT)
1566                 return (1);
1567
1568         return (0);
1569 }
1570
1571 /*
1572  * Remove the rtentry for the given llentry,
1573  * both of which were installed by a redirect.
1574  */
1575 static void
1576 nd6_free_redirect(const struct llentry *ln)
1577 {
1578         int fibnum;
1579         struct sockaddr_in6 sin6;
1580         struct rt_addrinfo info;
1581         struct rib_cmd_info rc;
1582         struct epoch_tracker et;
1583
1584         lltable_fill_sa_entry(ln, (struct sockaddr *)&sin6);
1585         memset(&info, 0, sizeof(info));
1586         info.rti_info[RTAX_DST] = (struct sockaddr *)&sin6;
1587         info.rti_filter = nd6_isdynrte;
1588
1589         NET_EPOCH_ENTER(et);
1590         for (fibnum = 0; fibnum < rt_numfibs; fibnum++)
1591                 rib_action(fibnum, RTM_DELETE, &info, &rc);
1592         NET_EPOCH_EXIT(et);
1593 }
1594
1595 /*
1596  * Updates status of the default router route.
1597  */
1598 static void
1599 check_release_defrouter(struct rib_cmd_info *rc, void *_cbdata)
1600 {
1601         struct nd_defrouter *dr;
1602         struct nhop_object *nh;
1603
1604         nh = rc->rc_nh_old;
1605
1606         if ((nh != NULL) && (nh->nh_flags & NHF_DEFAULT)) {
1607                 dr = defrouter_lookup(&nh->gw6_sa.sin6_addr, nh->nh_ifp);
1608                 if (dr != NULL) {
1609                         dr->installed = 0;
1610                         defrouter_rele(dr);
1611                 }
1612         }
1613 }
1614
1615 void
1616 nd6_subscription_cb(struct rib_head *rnh, struct rib_cmd_info *rc, void *arg)
1617 {
1618
1619 #ifdef ROUTE_MPATH
1620         rib_decompose_notification(rc, check_release_defrouter, NULL);
1621 #else
1622         check_release_defrouter(rc, NULL);
1623 #endif
1624 }
1625
1626 int
1627 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1628 {
1629         struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1630         struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1631         struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1632         struct epoch_tracker et;
1633         int error = 0;
1634
1635         if (ifp->if_afdata[AF_INET6] == NULL)
1636                 return (EPFNOSUPPORT);
1637         switch (cmd) {
1638         case OSIOCGIFINFO_IN6:
1639 #define ND      ndi->ndi
1640                 /* XXX: old ndp(8) assumes a positive value for linkmtu. */
1641                 bzero(&ND, sizeof(ND));
1642                 ND.linkmtu = IN6_LINKMTU(ifp);
1643                 ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
1644                 ND.basereachable = ND_IFINFO(ifp)->basereachable;
1645                 ND.reachable = ND_IFINFO(ifp)->reachable;
1646                 ND.retrans = ND_IFINFO(ifp)->retrans;
1647                 ND.flags = ND_IFINFO(ifp)->flags;
1648                 ND.recalctm = ND_IFINFO(ifp)->recalctm;
1649                 ND.chlim = ND_IFINFO(ifp)->chlim;
1650                 break;
1651         case SIOCGIFINFO_IN6:
1652                 ND = *ND_IFINFO(ifp);
1653                 break;
1654         case SIOCSIFINFO_IN6:
1655                 /*
1656                  * used to change host variables from userland.
1657                  * intended for a use on router to reflect RA configurations.
1658                  */
1659                 /* 0 means 'unspecified' */
1660                 if (ND.linkmtu != 0) {
1661                         if (ND.linkmtu < IPV6_MMTU ||
1662                             ND.linkmtu > IN6_LINKMTU(ifp)) {
1663                                 error = EINVAL;
1664                                 break;
1665                         }
1666                         ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
1667                 }
1668
1669                 if (ND.basereachable != 0) {
1670                         int obasereachable = ND_IFINFO(ifp)->basereachable;
1671
1672                         ND_IFINFO(ifp)->basereachable = ND.basereachable;
1673                         if (ND.basereachable != obasereachable)
1674                                 ND_IFINFO(ifp)->reachable =
1675                                     ND_COMPUTE_RTIME(ND.basereachable);
1676                 }
1677                 if (ND.retrans != 0)
1678                         ND_IFINFO(ifp)->retrans = ND.retrans;
1679                 if (ND.chlim != 0)
1680                         ND_IFINFO(ifp)->chlim = ND.chlim;
1681                 /* FALLTHROUGH */
1682         case SIOCSIFINFO_FLAGS:
1683         {
1684                 struct ifaddr *ifa;
1685                 struct in6_ifaddr *ia;
1686
1687                 if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1688                     !(ND.flags & ND6_IFF_IFDISABLED)) {
1689                         /* ifdisabled 1->0 transision */
1690
1691                         /*
1692                          * If the interface is marked as ND6_IFF_IFDISABLED and
1693                          * has an link-local address with IN6_IFF_DUPLICATED,
1694                          * do not clear ND6_IFF_IFDISABLED.
1695                          * See RFC 4862, Section 5.4.5.
1696                          */
1697                         NET_EPOCH_ENTER(et);
1698                         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1699                                 if (ifa->ifa_addr->sa_family != AF_INET6)
1700                                         continue;
1701                                 ia = (struct in6_ifaddr *)ifa;
1702                                 if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
1703                                     IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1704                                         break;
1705                         }
1706                         NET_EPOCH_EXIT(et);
1707
1708                         if (ifa != NULL) {
1709                                 /* LLA is duplicated. */
1710                                 ND.flags |= ND6_IFF_IFDISABLED;
1711                                 log(LOG_ERR, "Cannot enable an interface"
1712                                     " with a link-local address marked"
1713                                     " duplicate.\n");
1714                         } else {
1715                                 ND_IFINFO(ifp)->flags &= ~ND6_IFF_IFDISABLED;
1716                                 if (ifp->if_flags & IFF_UP)
1717                                         in6_if_up(ifp);
1718                         }
1719                 } else if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1720                             (ND.flags & ND6_IFF_IFDISABLED)) {
1721                         /* ifdisabled 0->1 transision */
1722                         /* Mark all IPv6 address as tentative. */
1723
1724                         ND_IFINFO(ifp)->flags |= ND6_IFF_IFDISABLED;
1725                         if (V_ip6_dad_count > 0 &&
1726                             (ND_IFINFO(ifp)->flags & ND6_IFF_NO_DAD) == 0) {
1727                                 NET_EPOCH_ENTER(et);
1728                                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead,
1729                                     ifa_link) {
1730                                         if (ifa->ifa_addr->sa_family !=
1731                                             AF_INET6)
1732                                                 continue;
1733                                         ia = (struct in6_ifaddr *)ifa;
1734                                         ia->ia6_flags |= IN6_IFF_TENTATIVE;
1735                                 }
1736                                 NET_EPOCH_EXIT(et);
1737                         }
1738                 }
1739
1740                 if (ND.flags & ND6_IFF_AUTO_LINKLOCAL) {
1741                         if (!(ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL)) {
1742                                 /* auto_linklocal 0->1 transision */
1743
1744                                 /* If no link-local address on ifp, configure */
1745                                 ND_IFINFO(ifp)->flags |= ND6_IFF_AUTO_LINKLOCAL;
1746                                 in6_ifattach(ifp, NULL);
1747                         } else if (!(ND.flags & ND6_IFF_IFDISABLED) &&
1748                             ifp->if_flags & IFF_UP) {
1749                                 /*
1750                                  * When the IF already has
1751                                  * ND6_IFF_AUTO_LINKLOCAL, no link-local
1752                                  * address is assigned, and IFF_UP, try to
1753                                  * assign one.
1754                                  */
1755                                 NET_EPOCH_ENTER(et);
1756                                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead,
1757                                     ifa_link) {
1758                                         if (ifa->ifa_addr->sa_family !=
1759                                             AF_INET6)
1760                                                 continue;
1761                                         ia = (struct in6_ifaddr *)ifa;
1762                                         if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1763                                                 break;
1764                                 }
1765                                 NET_EPOCH_EXIT(et);
1766                                 if (ifa != NULL)
1767                                         /* No LLA is configured. */
1768                                         in6_ifattach(ifp, NULL);
1769                         }
1770                 }
1771                 ND_IFINFO(ifp)->flags = ND.flags;
1772                 break;
1773         }
1774 #undef ND
1775         case SIOCSNDFLUSH_IN6:  /* XXX: the ioctl name is confusing... */
1776                 /* sync kernel routing table with the default router list */
1777                 defrouter_reset();
1778                 defrouter_select_fib(RT_ALL_FIBS);
1779                 break;
1780         case SIOCSPFXFLUSH_IN6:
1781         {
1782                 /* flush all the prefix advertised by routers */
1783                 struct in6_ifaddr *ia, *ia_next;
1784                 struct nd_prefix *pr, *next;
1785                 struct nd_prhead prl;
1786
1787                 LIST_INIT(&prl);
1788
1789                 ND6_WLOCK();
1790                 LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, next) {
1791                         if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1792                                 continue; /* XXX */
1793                         nd6_prefix_unlink(pr, &prl);
1794                 }
1795                 ND6_WUNLOCK();
1796
1797                 while ((pr = LIST_FIRST(&prl)) != NULL) {
1798                         LIST_REMOVE(pr, ndpr_entry);
1799                         /* XXXRW: in6_ifaddrhead locking. */
1800                         CK_STAILQ_FOREACH_SAFE(ia, &V_in6_ifaddrhead, ia_link,
1801                             ia_next) {
1802                                 if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1803                                         continue;
1804
1805                                 if (ia->ia6_ndpr == pr)
1806                                         in6_purgeaddr(&ia->ia_ifa);
1807                         }
1808                         nd6_prefix_del(pr);
1809                 }
1810                 break;
1811         }
1812         case SIOCSRTRFLUSH_IN6:
1813         {
1814                 /* flush all the default routers */
1815
1816                 defrouter_reset();
1817                 nd6_defrouter_flush_all();
1818                 defrouter_select_fib(RT_ALL_FIBS);
1819                 break;
1820         }
1821         case SIOCGNBRINFO_IN6:
1822         {
1823                 struct llentry *ln;
1824                 struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1825
1826                 if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
1827                         return (error);
1828
1829                 NET_EPOCH_ENTER(et);
1830                 ln = nd6_lookup(&nb_addr, 0, ifp);
1831                 NET_EPOCH_EXIT(et);
1832
1833                 if (ln == NULL) {
1834                         error = EINVAL;
1835                         break;
1836                 }
1837                 nbi->state = ln->ln_state;
1838                 nbi->asked = ln->la_asked;
1839                 nbi->isrouter = ln->ln_router;
1840                 if (ln->la_expire == 0)
1841                         nbi->expire = 0;
1842                 else
1843                         nbi->expire = ln->la_expire + ln->lle_remtime / hz +
1844                             (time_second - time_uptime);
1845                 LLE_RUNLOCK(ln);
1846                 break;
1847         }
1848         case SIOCGDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1849                 ndif->ifindex = V_nd6_defifindex;
1850                 break;
1851         case SIOCSDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1852                 return (nd6_setdefaultiface(ndif->ifindex));
1853         }
1854         return (error);
1855 }
1856
1857 /*
1858  * Calculates new isRouter value based on provided parameters and
1859  * returns it.
1860  */
1861 static int
1862 nd6_is_router(int type, int code, int is_new, int old_addr, int new_addr,
1863     int ln_router)
1864 {
1865
1866         /*
1867          * ICMP6 type dependent behavior.
1868          *
1869          * NS: clear IsRouter if new entry
1870          * RS: clear IsRouter
1871          * RA: set IsRouter if there's lladdr
1872          * redir: clear IsRouter if new entry
1873          *
1874          * RA case, (1):
1875          * The spec says that we must set IsRouter in the following cases:
1876          * - If lladdr exist, set IsRouter.  This means (1-5).
1877          * - If it is old entry (!newentry), set IsRouter.  This means (7).
1878          * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1879          * A quetion arises for (1) case.  (1) case has no lladdr in the
1880          * neighbor cache, this is similar to (6).
1881          * This case is rare but we figured that we MUST NOT set IsRouter.
1882          *
1883          *   is_new  old_addr new_addr      NS  RS  RA  redir
1884          *                                                      D R
1885          *      0       n       n       (1)     c   ?     s
1886          *      0       y       n       (2)     c   s     s
1887          *      0       n       y       (3)     c   s     s
1888          *      0       y       y       (4)     c   s     s
1889          *      0       y       y       (5)     c   s     s
1890          *      1       --      n       (6) c   c       c s
1891          *      1       --      y       (7) c   c   s   c s
1892          *
1893          *                                      (c=clear s=set)
1894          */
1895         switch (type & 0xff) {
1896         case ND_NEIGHBOR_SOLICIT:
1897                 /*
1898                  * New entry must have is_router flag cleared.
1899                  */
1900                 if (is_new)                                     /* (6-7) */
1901                         ln_router = 0;
1902                 break;
1903         case ND_REDIRECT:
1904                 /*
1905                  * If the icmp is a redirect to a better router, always set the
1906                  * is_router flag.  Otherwise, if the entry is newly created,
1907                  * clear the flag.  [RFC 2461, sec 8.3]
1908                  */
1909                 if (code == ND_REDIRECT_ROUTER)
1910                         ln_router = 1;
1911                 else {
1912                         if (is_new)                             /* (6-7) */
1913                                 ln_router = 0;
1914                 }
1915                 break;
1916         case ND_ROUTER_SOLICIT:
1917                 /*
1918                  * is_router flag must always be cleared.
1919                  */
1920                 ln_router = 0;
1921                 break;
1922         case ND_ROUTER_ADVERT:
1923                 /*
1924                  * Mark an entry with lladdr as a router.
1925                  */
1926                 if ((!is_new && (old_addr || new_addr)) ||      /* (2-5) */
1927                     (is_new && new_addr)) {                     /* (7) */
1928                         ln_router = 1;
1929                 }
1930                 break;
1931         }
1932
1933         return (ln_router);
1934 }
1935
1936 /*
1937  * Create neighbor cache entry and cache link-layer address,
1938  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1939  *
1940  * type - ICMP6 type
1941  * code - type dependent information
1942  *
1943  */
1944 void
1945 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1946     int lladdrlen, int type, int code)
1947 {
1948         struct llentry *ln = NULL, *ln_tmp;
1949         int is_newentry;
1950         int do_update;
1951         int olladdr;
1952         int llchange;
1953         int flags;
1954         uint16_t router = 0;
1955         struct mbuf *chain = NULL;
1956         u_char linkhdr[LLE_MAX_LINKHDR];
1957         size_t linkhdrsize;
1958         int lladdr_off;
1959
1960         NET_EPOCH_ASSERT();
1961         IF_AFDATA_UNLOCK_ASSERT(ifp);
1962
1963         KASSERT(ifp != NULL, ("%s: ifp == NULL", __func__));
1964         KASSERT(from != NULL, ("%s: from == NULL", __func__));
1965
1966         /* nothing must be updated for unspecified address */
1967         if (IN6_IS_ADDR_UNSPECIFIED(from))
1968                 return;
1969
1970         /*
1971          * Validation about ifp->if_addrlen and lladdrlen must be done in
1972          * the caller.
1973          *
1974          * XXX If the link does not have link-layer adderss, what should
1975          * we do? (ifp->if_addrlen == 0)
1976          * Spec says nothing in sections for RA, RS and NA.  There's small
1977          * description on it in NS section (RFC 2461 7.2.3).
1978          */
1979         flags = lladdr ? LLE_EXCLUSIVE : 0;
1980         ln = nd6_lookup(from, flags, ifp);
1981         is_newentry = 0;
1982         if (ln == NULL) {
1983                 flags |= LLE_EXCLUSIVE;
1984                 ln = nd6_alloc(from, 0, ifp);
1985                 if (ln == NULL)
1986                         return;
1987
1988                 /*
1989                  * Since we already know all the data for the new entry,
1990                  * fill it before insertion.
1991                  */
1992                 if (lladdr != NULL) {
1993                         linkhdrsize = sizeof(linkhdr);
1994                         if (lltable_calc_llheader(ifp, AF_INET6, lladdr,
1995                             linkhdr, &linkhdrsize, &lladdr_off) != 0)
1996                                 return;
1997                         lltable_set_entry_addr(ifp, ln, linkhdr, linkhdrsize,
1998                             lladdr_off);
1999                 }
2000
2001                 IF_AFDATA_WLOCK(ifp);
2002                 LLE_WLOCK(ln);
2003                 /* Prefer any existing lle over newly-created one */
2004                 ln_tmp = nd6_lookup(from, LLE_EXCLUSIVE, ifp);
2005                 if (ln_tmp == NULL)
2006                         lltable_link_entry(LLTABLE6(ifp), ln);
2007                 IF_AFDATA_WUNLOCK(ifp);
2008                 if (ln_tmp == NULL) {
2009                         /* No existing lle, mark as new entry (6,7) */
2010                         is_newentry = 1;
2011                         if (lladdr != NULL) {   /* (7) */
2012                                 nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
2013                                 EVENTHANDLER_INVOKE(lle_event, ln,
2014                                     LLENTRY_RESOLVED);
2015                         }
2016                 } else {
2017                         lltable_free_entry(LLTABLE6(ifp), ln);
2018                         ln = ln_tmp;
2019                         ln_tmp = NULL;
2020                 }
2021         } 
2022         /* do nothing if static ndp is set */
2023         if ((ln->la_flags & LLE_STATIC)) {
2024                 if (flags & LLE_EXCLUSIVE)
2025                         LLE_WUNLOCK(ln);
2026                 else
2027                         LLE_RUNLOCK(ln);
2028                 return;
2029         }
2030
2031         olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
2032         if (olladdr && lladdr) {
2033                 llchange = bcmp(lladdr, ln->ll_addr,
2034                     ifp->if_addrlen);
2035         } else if (!olladdr && lladdr)
2036                 llchange = 1;
2037         else
2038                 llchange = 0;
2039
2040         /*
2041          * newentry olladdr  lladdr  llchange   (*=record)
2042          *      0       n       n       --      (1)
2043          *      0       y       n       --      (2)
2044          *      0       n       y       y       (3) * STALE
2045          *      0       y       y       n       (4) *
2046          *      0       y       y       y       (5) * STALE
2047          *      1       --      n       --      (6)   NOSTATE(= PASSIVE)
2048          *      1       --      y       --      (7) * STALE
2049          */
2050
2051         do_update = 0;
2052         if (is_newentry == 0 && llchange != 0) {
2053                 do_update = 1;  /* (3,5) */
2054
2055                 /*
2056                  * Record source link-layer address
2057                  * XXX is it dependent to ifp->if_type?
2058                  */
2059                 if (!nd6_try_set_entry_addr(ifp, ln, lladdr)) {
2060                         /* Entry was deleted */
2061                         LLE_WUNLOCK(ln);
2062                         return;
2063                 }
2064
2065                 nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
2066
2067                 EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
2068
2069                 if (ln->la_hold != NULL)
2070                         chain = nd6_grab_holdchain(ln);
2071         }
2072
2073         /* Calculates new router status */
2074         router = nd6_is_router(type, code, is_newentry, olladdr,
2075             lladdr != NULL ? 1 : 0, ln->ln_router);
2076
2077         ln->ln_router = router;
2078         /* Mark non-router redirects with special flag */
2079         if ((type & 0xFF) == ND_REDIRECT && code != ND_REDIRECT_ROUTER)
2080                 ln->la_flags |= LLE_REDIRECT;
2081
2082         if (flags & LLE_EXCLUSIVE)
2083                 LLE_WUNLOCK(ln);
2084         else
2085                 LLE_RUNLOCK(ln);
2086
2087         if (chain != NULL)
2088                 nd6_flush_holdchain(ifp, ln, chain);
2089
2090         /*
2091          * When the link-layer address of a router changes, select the
2092          * best router again.  In particular, when the neighbor entry is newly
2093          * created, it might affect the selection policy.
2094          * Question: can we restrict the first condition to the "is_newentry"
2095          * case?
2096          * XXX: when we hear an RA from a new router with the link-layer
2097          * address option, defrouter_select_fib() is called twice, since
2098          * defrtrlist_update called the function as well.  However, I believe
2099          * we can compromise the overhead, since it only happens the first
2100          * time.
2101          * XXX: although defrouter_select_fib() should not have a bad effect
2102          * for those are not autoconfigured hosts, we explicitly avoid such
2103          * cases for safety.
2104          */
2105         if ((do_update || is_newentry) && router &&
2106             ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
2107                 /*
2108                  * guaranteed recursion
2109                  */
2110                 defrouter_select_fib(ifp->if_fib);
2111         }
2112 }
2113
2114 static void
2115 nd6_slowtimo(void *arg)
2116 {
2117         struct epoch_tracker et;
2118         CURVNET_SET((struct vnet *) arg);
2119         struct nd_ifinfo *nd6if;
2120         struct ifnet *ifp;
2121
2122         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
2123             nd6_slowtimo, curvnet);
2124         NET_EPOCH_ENTER(et);
2125         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2126                 if (ifp->if_afdata[AF_INET6] == NULL)
2127                         continue;
2128                 nd6if = ND_IFINFO(ifp);
2129                 if (nd6if->basereachable && /* already initialized */
2130                     (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
2131                         /*
2132                          * Since reachable time rarely changes by router
2133                          * advertisements, we SHOULD insure that a new random
2134                          * value gets recomputed at least once every few hours.
2135                          * (RFC 2461, 6.3.4)
2136                          */
2137                         nd6if->recalctm = V_nd6_recalc_reachtm_interval;
2138                         nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
2139                 }
2140         }
2141         NET_EPOCH_EXIT(et);
2142         CURVNET_RESTORE();
2143 }
2144
2145 struct mbuf *
2146 nd6_grab_holdchain(struct llentry *ln)
2147 {
2148         struct mbuf *chain;
2149
2150         LLE_WLOCK_ASSERT(ln);
2151
2152         chain = ln->la_hold;
2153         ln->la_hold = NULL;
2154
2155         if (ln->ln_state == ND6_LLINFO_STALE) {
2156                 /*
2157                  * The first time we send a packet to a
2158                  * neighbor whose entry is STALE, we have
2159                  * to change the state to DELAY and a sets
2160                  * a timer to expire in DELAY_FIRST_PROBE_TIME
2161                  * seconds to ensure do neighbor unreachability
2162                  * detection on expiration.
2163                  * (RFC 2461 7.3.3)
2164                  */
2165                 nd6_llinfo_setstate(ln, ND6_LLINFO_DELAY);
2166         }
2167
2168         return (chain);
2169 }
2170
2171 int
2172 nd6_output_ifp(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
2173     struct sockaddr_in6 *dst, struct route *ro)
2174 {
2175         int error;
2176         int ip6len;
2177         struct ip6_hdr *ip6;
2178         struct m_tag *mtag;
2179
2180 #ifdef MAC
2181         mac_netinet6_nd6_send(ifp, m);
2182 #endif
2183
2184         /*
2185          * If called from nd6_ns_output() (NS), nd6_na_output() (NA),
2186          * icmp6_redirect_output() (REDIRECT) or from rip6_output() (RS, RA
2187          * as handled by rtsol and rtadvd), mbufs will be tagged for SeND
2188          * to be diverted to user space.  When re-injected into the kernel,
2189          * send_output() will directly dispatch them to the outgoing interface.
2190          */
2191         if (send_sendso_input_hook != NULL) {
2192                 mtag = m_tag_find(m, PACKET_TAG_ND_OUTGOING, NULL);
2193                 if (mtag != NULL) {
2194                         ip6 = mtod(m, struct ip6_hdr *);
2195                         ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
2196                         /* Use the SEND socket */
2197                         error = send_sendso_input_hook(m, ifp, SND_OUT,
2198                             ip6len);
2199                         /* -1 == no app on SEND socket */
2200                         if (error == 0 || error != -1)
2201                             return (error);
2202                 }
2203         }
2204
2205         m_clrprotoflags(m);     /* Avoid confusing lower layers. */
2206         IP_PROBE(send, NULL, NULL, mtod(m, struct ip6_hdr *), ifp, NULL,
2207             mtod(m, struct ip6_hdr *));
2208
2209         if ((ifp->if_flags & IFF_LOOPBACK) == 0)
2210                 origifp = ifp;
2211
2212         error = (*ifp->if_output)(origifp, m, (struct sockaddr *)dst, ro);
2213         return (error);
2214 }
2215
2216 /*
2217  * Lookup link headerfor @sa_dst address. Stores found
2218  * data in @desten buffer. Copy of lle ln_flags can be also
2219  * saved in @pflags if @pflags is non-NULL.
2220  *
2221  * If destination LLE does not exists or lle state modification
2222  * is required, call "slow" version.
2223  *
2224  * Return values:
2225  * - 0 on success (address copied to buffer).
2226  * - EWOULDBLOCK (no local error, but address is still unresolved)
2227  * - other errors (alloc failure, etc)
2228  */
2229 int
2230 nd6_resolve(struct ifnet *ifp, int is_gw, struct mbuf *m,
2231     const struct sockaddr *sa_dst, u_char *desten, uint32_t *pflags,
2232     struct llentry **plle)
2233 {
2234         struct llentry *ln = NULL;
2235         const struct sockaddr_in6 *dst6;
2236
2237         NET_EPOCH_ASSERT();
2238
2239         if (pflags != NULL)
2240                 *pflags = 0;
2241
2242         dst6 = (const struct sockaddr_in6 *)sa_dst;
2243
2244         /* discard the packet if IPv6 operation is disabled on the interface */
2245         if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
2246                 m_freem(m);
2247                 return (ENETDOWN); /* better error? */
2248         }
2249
2250         if (m != NULL && m->m_flags & M_MCAST) {
2251                 switch (ifp->if_type) {
2252                 case IFT_ETHER:
2253                 case IFT_L2VLAN:
2254                 case IFT_BRIDGE:
2255                         ETHER_MAP_IPV6_MULTICAST(&dst6->sin6_addr,
2256                                                  desten);
2257                         return (0);
2258                 default:
2259                         m_freem(m);
2260                         return (EAFNOSUPPORT);
2261                 }
2262         }
2263
2264         ln = nd6_lookup(&dst6->sin6_addr, plle ? LLE_EXCLUSIVE : LLE_UNLOCKED,
2265             ifp);
2266         if (ln != NULL && (ln->r_flags & RLLE_VALID) != 0) {
2267                 /* Entry found, let's copy lle info */
2268                 bcopy(ln->r_linkdata, desten, ln->r_hdrlen);
2269                 if (pflags != NULL)
2270                         *pflags = LLE_VALID | (ln->r_flags & RLLE_IFADDR);
2271                 llentry_provide_feedback(ln);
2272                 if (plle) {
2273                         LLE_ADDREF(ln);
2274                         *plle = ln;
2275                         LLE_WUNLOCK(ln);
2276                 }
2277                 return (0);
2278         } else if (plle && ln)
2279                 LLE_WUNLOCK(ln);
2280
2281         return (nd6_resolve_slow(ifp, 0, m, dst6, desten, pflags, plle));
2282 }
2283
2284 /*
2285  * Finds or creates a new llentry for @addr.
2286  * Returns wlocked llentry or NULL.
2287  */
2288 static __noinline struct llentry *
2289 nd6_get_llentry(struct ifnet *ifp, const struct in6_addr *addr)
2290 {
2291         struct llentry *lle, *lle_tmp;
2292
2293         lle = nd6_alloc(addr, 0, ifp);
2294         if (lle == NULL) {
2295                 char ip6buf[INET6_ADDRSTRLEN];
2296                 log(LOG_DEBUG,
2297                     "nd6_get_llentry: can't allocate llinfo for %s "
2298                     "(ln=%p)\n",
2299                     ip6_sprintf(ip6buf, addr), lle);
2300                 return (NULL);
2301         }
2302
2303         IF_AFDATA_WLOCK(ifp);
2304         LLE_WLOCK(lle);
2305         /* Prefer any existing entry over newly-created one */
2306         lle_tmp = nd6_lookup(addr, LLE_EXCLUSIVE, ifp);
2307         if (lle_tmp == NULL)
2308                 lltable_link_entry(LLTABLE6(ifp), lle);
2309         IF_AFDATA_WUNLOCK(ifp);
2310         if (lle_tmp != NULL) {
2311                 lltable_free_entry(LLTABLE6(ifp), lle);
2312                 return (lle_tmp);
2313         } else
2314                 return (lle);
2315 }
2316
2317 /*
2318  * Do L2 address resolution for @sa_dst address. Stores found
2319  * address in @desten buffer. Copy of lle ln_flags can be also
2320  * saved in @pflags if @pflags is non-NULL.
2321  *
2322  * Heavy version.
2323  * Function assume that destination LLE does not exist,
2324  * is invalid or stale, so LLE_EXCLUSIVE lock needs to be acquired.
2325  *
2326  * Set noinline to be dtrace-friendly
2327  */
2328 static __noinline int
2329 nd6_resolve_slow(struct ifnet *ifp, int flags, struct mbuf *m,
2330     const struct sockaddr_in6 *dst, u_char *desten, uint32_t *pflags,
2331     struct llentry **plle)
2332 {
2333         struct llentry *lle = NULL;
2334         struct in6_addr *psrc, src;
2335         int send_ns, ll_len;
2336         char *lladdr;
2337
2338         NET_EPOCH_ASSERT();
2339
2340         /*
2341          * Address resolution or Neighbor Unreachability Detection
2342          * for the next hop.
2343          * At this point, the destination of the packet must be a unicast
2344          * or an anycast address(i.e. not a multicast).
2345          */
2346         lle = nd6_lookup(&dst->sin6_addr, LLE_EXCLUSIVE, ifp);
2347         if ((lle == NULL) && nd6_is_addr_neighbor(dst, ifp))  {
2348                 /*
2349                  * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
2350                  * the condition below is not very efficient.  But we believe
2351                  * it is tolerable, because this should be a rare case.
2352                  */
2353                 lle = nd6_get_llentry(ifp, &dst->sin6_addr);
2354         }
2355
2356         if (lle == NULL) {
2357                 m_freem(m);
2358                 return (ENOBUFS);
2359         }
2360
2361         LLE_WLOCK_ASSERT(lle);
2362
2363         /*
2364          * The first time we send a packet to a neighbor whose entry is
2365          * STALE, we have to change the state to DELAY and a sets a timer to
2366          * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
2367          * neighbor unreachability detection on expiration.
2368          * (RFC 2461 7.3.3)
2369          */
2370         if (lle->ln_state == ND6_LLINFO_STALE)
2371                 nd6_llinfo_setstate(lle, ND6_LLINFO_DELAY);
2372
2373         /*
2374          * If the neighbor cache entry has a state other than INCOMPLETE
2375          * (i.e. its link-layer address is already resolved), just
2376          * send the packet.
2377          */
2378         if (lle->ln_state > ND6_LLINFO_INCOMPLETE) {
2379                 if (flags & LLE_ADDRONLY) {
2380                         lladdr = lle->ll_addr;
2381                         ll_len = ifp->if_addrlen;
2382                 } else {
2383                         lladdr = lle->r_linkdata;
2384                         ll_len = lle->r_hdrlen;
2385                 }
2386                 bcopy(lladdr, desten, ll_len);
2387                 if (pflags != NULL)
2388                         *pflags = lle->la_flags;
2389                 if (plle) {
2390                         LLE_ADDREF(lle);
2391                         *plle = lle;
2392                 }
2393                 LLE_WUNLOCK(lle);
2394                 return (0);
2395         }
2396
2397         /*
2398          * There is a neighbor cache entry, but no ethernet address
2399          * response yet.  Append this latest packet to the end of the
2400          * packet queue in the mbuf.  When it exceeds nd6_maxqueuelen,
2401          * the oldest packet in the queue will be removed.
2402          */
2403
2404         if (lle->la_hold != NULL) {
2405                 struct mbuf *m_hold;
2406                 int i;
2407                 
2408                 i = 0;
2409                 for (m_hold = lle->la_hold; m_hold; m_hold = m_hold->m_nextpkt){
2410                         i++;
2411                         if (m_hold->m_nextpkt == NULL) {
2412                                 m_hold->m_nextpkt = m;
2413                                 break;
2414                         }
2415                 }
2416                 while (i >= V_nd6_maxqueuelen) {
2417                         m_hold = lle->la_hold;
2418                         lle->la_hold = lle->la_hold->m_nextpkt;
2419                         m_freem(m_hold);
2420                         i--;
2421                 }
2422         } else {
2423                 lle->la_hold = m;
2424         }
2425
2426         /*
2427          * If there has been no NS for the neighbor after entering the
2428          * INCOMPLETE state, send the first solicitation.
2429          * Note that for newly-created lle la_asked will be 0,
2430          * so we will transition from ND6_LLINFO_NOSTATE to
2431          * ND6_LLINFO_INCOMPLETE state here.
2432          */
2433         psrc = NULL;
2434         send_ns = 0;
2435         if (lle->la_asked == 0) {
2436                 lle->la_asked++;
2437                 send_ns = 1;
2438                 psrc = nd6_llinfo_get_holdsrc(lle, &src);
2439
2440                 nd6_llinfo_setstate(lle, ND6_LLINFO_INCOMPLETE);
2441         }
2442         LLE_WUNLOCK(lle);
2443         if (send_ns != 0)
2444                 nd6_ns_output(ifp, psrc, NULL, &dst->sin6_addr, NULL);
2445
2446         return (EWOULDBLOCK);
2447 }
2448
2449 /*
2450  * Do L2 address resolution for @sa_dst address. Stores found
2451  * address in @desten buffer. Copy of lle ln_flags can be also
2452  * saved in @pflags if @pflags is non-NULL.
2453  *
2454  * Return values:
2455  * - 0 on success (address copied to buffer).
2456  * - EWOULDBLOCK (no local error, but address is still unresolved)
2457  * - other errors (alloc failure, etc)
2458  */
2459 int
2460 nd6_resolve_addr(struct ifnet *ifp, int flags, const struct sockaddr *dst,
2461     char *desten, uint32_t *pflags)
2462 {
2463         int error;
2464
2465         flags |= LLE_ADDRONLY;
2466         error = nd6_resolve_slow(ifp, flags, NULL,
2467             (const struct sockaddr_in6 *)dst, desten, pflags, NULL);
2468         return (error);
2469 }
2470
2471 int
2472 nd6_flush_holdchain(struct ifnet *ifp, struct llentry *lle, struct mbuf *chain)
2473 {
2474         struct mbuf *m, *m_head;
2475         struct sockaddr_in6 dst6;
2476         int error = 0;
2477
2478         NET_EPOCH_ASSERT();
2479
2480         struct route_in6 ro = {
2481                 .ro_prepend = lle->r_linkdata,
2482                 .ro_plen = lle->r_hdrlen,
2483         };
2484
2485         lltable_fill_sa_entry(lle, (struct sockaddr *)&dst6);
2486         m_head = chain;
2487
2488         while (m_head) {
2489                 m = m_head;
2490                 m_head = m_head->m_nextpkt;
2491                 m->m_nextpkt = NULL;
2492                 error = nd6_output_ifp(ifp, ifp, m, &dst6, (struct route *)&ro);
2493         }
2494
2495         /*
2496          * XXX
2497          * note that intermediate errors are blindly ignored
2498          */
2499         return (error);
2500 }
2501
2502 static int
2503 nd6_need_cache(struct ifnet *ifp)
2504 {
2505         /*
2506          * XXX: we currently do not make neighbor cache on any interface
2507          * other than Ethernet and GIF.
2508          *
2509          * RFC2893 says:
2510          * - unidirectional tunnels needs no ND
2511          */
2512         switch (ifp->if_type) {
2513         case IFT_ETHER:
2514         case IFT_IEEE1394:
2515         case IFT_L2VLAN:
2516         case IFT_INFINIBAND:
2517         case IFT_BRIDGE:
2518         case IFT_PROPVIRTUAL:
2519                 return (1);
2520         default:
2521                 return (0);
2522         }
2523 }
2524
2525 /*
2526  * Add pernament ND6 link-layer record for given
2527  * interface address.
2528  *
2529  * Very similar to IPv4 arp_ifinit(), but:
2530  * 1) IPv6 DAD is performed in different place
2531  * 2) It is called by IPv6 protocol stack in contrast to
2532  * arp_ifinit() which is typically called in SIOCSIFADDR
2533  * driver ioctl handler.
2534  *
2535  */
2536 int
2537 nd6_add_ifa_lle(struct in6_ifaddr *ia)
2538 {
2539         struct ifnet *ifp;
2540         struct llentry *ln, *ln_tmp;
2541         struct sockaddr *dst;
2542
2543         ifp = ia->ia_ifa.ifa_ifp;
2544         if (nd6_need_cache(ifp) == 0)
2545                 return (0);
2546
2547         dst = (struct sockaddr *)&ia->ia_addr;
2548         ln = lltable_alloc_entry(LLTABLE6(ifp), LLE_IFADDR, dst);
2549         if (ln == NULL)
2550                 return (ENOBUFS);
2551
2552         IF_AFDATA_WLOCK(ifp);
2553         LLE_WLOCK(ln);
2554         /* Unlink any entry if exists */
2555         ln_tmp = lla_lookup(LLTABLE6(ifp), LLE_EXCLUSIVE, dst);
2556         if (ln_tmp != NULL)
2557                 lltable_unlink_entry(LLTABLE6(ifp), ln_tmp);
2558         lltable_link_entry(LLTABLE6(ifp), ln);
2559         IF_AFDATA_WUNLOCK(ifp);
2560
2561         if (ln_tmp != NULL)
2562                 EVENTHANDLER_INVOKE(lle_event, ln_tmp, LLENTRY_EXPIRED);
2563         EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
2564
2565         LLE_WUNLOCK(ln);
2566         if (ln_tmp != NULL)
2567                 llentry_free(ln_tmp);
2568
2569         return (0);
2570 }
2571
2572 /*
2573  * Removes either all lle entries for given @ia, or lle
2574  * corresponding to @ia address.
2575  */
2576 void
2577 nd6_rem_ifa_lle(struct in6_ifaddr *ia, int all)
2578 {
2579         struct sockaddr_in6 mask, addr;
2580         struct sockaddr *saddr, *smask;
2581         struct ifnet *ifp;
2582
2583         ifp = ia->ia_ifa.ifa_ifp;
2584         memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
2585         memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
2586         saddr = (struct sockaddr *)&addr;
2587         smask = (struct sockaddr *)&mask;
2588
2589         if (all != 0)
2590                 lltable_prefix_free(AF_INET6, saddr, smask, LLE_STATIC);
2591         else
2592                 lltable_delete_addr(LLTABLE6(ifp), LLE_IFADDR, saddr);
2593 }
2594
2595 static void 
2596 clear_llinfo_pqueue(struct llentry *ln)
2597 {
2598         struct mbuf *m_hold, *m_hold_next;
2599
2600         for (m_hold = ln->la_hold; m_hold; m_hold = m_hold_next) {
2601                 m_hold_next = m_hold->m_nextpkt;
2602                 m_freem(m_hold);
2603         }
2604
2605         ln->la_hold = NULL;
2606 }
2607
2608 static int
2609 nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2610 {
2611         struct in6_prefix p;
2612         struct sockaddr_in6 s6;
2613         struct nd_prefix *pr;
2614         struct nd_pfxrouter *pfr;
2615         time_t maxexpire;
2616         int error;
2617         char ip6buf[INET6_ADDRSTRLEN];
2618
2619         if (req->newptr)
2620                 return (EPERM);
2621
2622         error = sysctl_wire_old_buffer(req, 0);
2623         if (error != 0)
2624                 return (error);
2625
2626         bzero(&p, sizeof(p));
2627         p.origin = PR_ORIG_RA;
2628         bzero(&s6, sizeof(s6));
2629         s6.sin6_family = AF_INET6;
2630         s6.sin6_len = sizeof(s6);
2631
2632         ND6_RLOCK();
2633         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
2634                 p.prefix = pr->ndpr_prefix;
2635                 if (sa6_recoverscope(&p.prefix)) {
2636                         log(LOG_ERR, "scope error in prefix list (%s)\n",
2637                             ip6_sprintf(ip6buf, &p.prefix.sin6_addr));
2638                         /* XXX: press on... */
2639                 }
2640                 p.raflags = pr->ndpr_raf;
2641                 p.prefixlen = pr->ndpr_plen;
2642                 p.vltime = pr->ndpr_vltime;
2643                 p.pltime = pr->ndpr_pltime;
2644                 p.if_index = pr->ndpr_ifp->if_index;
2645                 if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2646                         p.expire = 0;
2647                 else {
2648                         /* XXX: we assume time_t is signed. */
2649                         maxexpire = (-1) &
2650                             ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
2651                         if (pr->ndpr_vltime < maxexpire - pr->ndpr_lastupdate)
2652                                 p.expire = pr->ndpr_lastupdate +
2653                                     pr->ndpr_vltime +
2654                                     (time_second - time_uptime);
2655                         else
2656                                 p.expire = maxexpire;
2657                 }
2658                 p.refcnt = pr->ndpr_addrcnt;
2659                 p.flags = pr->ndpr_stateflags;
2660                 p.advrtrs = 0;
2661                 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
2662                         p.advrtrs++;
2663                 error = SYSCTL_OUT(req, &p, sizeof(p));
2664                 if (error != 0)
2665                         break;
2666                 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
2667                         s6.sin6_addr = pfr->router->rtaddr;
2668                         if (sa6_recoverscope(&s6))
2669                                 log(LOG_ERR,
2670                                     "scope error in prefix list (%s)\n",
2671                                     ip6_sprintf(ip6buf, &pfr->router->rtaddr));
2672                         error = SYSCTL_OUT(req, &s6, sizeof(s6));
2673                         if (error != 0)
2674                                 goto out;
2675                 }
2676         }
2677 out:
2678         ND6_RUNLOCK();
2679         return (error);
2680 }
2681 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2682         CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2683         NULL, 0, nd6_sysctl_prlist, "S,in6_prefix",
2684         "NDP prefix list");
2685 SYSCTL_INT(_net_inet6_icmp6, ICMPV6CTL_ND6_MAXQLEN, nd6_maxqueuelen,
2686         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_maxqueuelen), 1, "");
2687 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, nd6_gctimer,
2688         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_gctimer), (60 * 60 * 24), "");