]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/nd6.c
Use lltable calculated header when sending lle holdchain after successful lle resolution.
[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, 1);
229         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
230             nd6_slowtimo, curvnet);
231
232         callout_init(&V_nd6_timer_ch, 1);
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                  * Reschedule 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. Reschedule 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  * Free an nd6 llinfo entry.
1387  * Since the function would cause significant changes in the kernel, DO NOT
1388  * make it global, unless you have a strong reason for the change, and are sure
1389  * that the change is safe.
1390  *
1391  * Set noinline to be dtrace-friendly
1392  */
1393 static __noinline void
1394 nd6_free(struct llentry **lnp, int gc)
1395 {
1396         struct ifnet *ifp;
1397         struct llentry *ln;
1398         struct nd_defrouter *dr;
1399
1400         ln = *lnp;
1401         *lnp = NULL;
1402
1403         LLE_WLOCK_ASSERT(ln);
1404         ND6_RLOCK_ASSERT();
1405
1406         ifp = lltable_get_ifp(ln->lle_tbl);
1407         if ((ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) != 0)
1408                 dr = defrouter_lookup_locked(&ln->r_l3addr.addr6, ifp);
1409         else
1410                 dr = NULL;
1411         ND6_RUNLOCK();
1412
1413         if ((ln->la_flags & LLE_DELETED) == 0)
1414                 EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_EXPIRED);
1415
1416         /*
1417          * we used to have pfctlinput(PRC_HOSTDEAD) here.
1418          * even though it is not harmful, it was not really necessary.
1419          */
1420
1421         /* cancel timer */
1422         nd6_llinfo_settimer_locked(ln, -1);
1423
1424         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1425                 if (dr != NULL && dr->expire &&
1426                     ln->ln_state == ND6_LLINFO_STALE && gc) {
1427                         /*
1428                          * If the reason for the deletion is just garbage
1429                          * collection, and the neighbor is an active default
1430                          * router, do not delete it.  Instead, reset the GC
1431                          * timer using the router's lifetime.
1432                          * Simply deleting the entry would affect default
1433                          * router selection, which is not necessarily a good
1434                          * thing, especially when we're using router preference
1435                          * values.
1436                          * XXX: the check for ln_state would be redundant,
1437                          *      but we intentionally keep it just in case.
1438                          */
1439                         if (dr->expire > time_uptime)
1440                                 nd6_llinfo_settimer_locked(ln,
1441                                     (dr->expire - time_uptime) * hz);
1442                         else
1443                                 nd6_llinfo_settimer_locked(ln,
1444                                     (long)V_nd6_gctimer * hz);
1445
1446                         LLE_REMREF(ln);
1447                         LLE_WUNLOCK(ln);
1448                         defrouter_rele(dr);
1449                         return;
1450                 }
1451
1452                 if (dr) {
1453                         /*
1454                          * Unreachablity of a router might affect the default
1455                          * router selection and on-link detection of advertised
1456                          * prefixes.
1457                          */
1458
1459                         /*
1460                          * Temporarily fake the state to choose a new default
1461                          * router and to perform on-link determination of
1462                          * prefixes correctly.
1463                          * Below the state will be set correctly,
1464                          * or the entry itself will be deleted.
1465                          */
1466                         ln->ln_state = ND6_LLINFO_INCOMPLETE;
1467                 }
1468
1469                 if (ln->ln_router || dr) {
1470                         /*
1471                          * We need to unlock to avoid a LOR with rt6_flush() with the
1472                          * rnh and for the calls to pfxlist_onlink_check() and
1473                          * defrouter_select_fib() in the block further down for calls
1474                          * into nd6_lookup().  We still hold a ref.
1475                          */
1476                         LLE_WUNLOCK(ln);
1477
1478                         /*
1479                          * rt6_flush must be called whether or not the neighbor
1480                          * is in the Default Router List.
1481                          * See a corresponding comment in nd6_na_input().
1482                          */
1483                         rt6_flush(&ln->r_l3addr.addr6, ifp);
1484                 }
1485
1486                 if (dr) {
1487                         /*
1488                          * Since defrouter_select_fib() does not affect the
1489                          * on-link determination and MIP6 needs the check
1490                          * before the default router selection, we perform
1491                          * the check now.
1492                          */
1493                         pfxlist_onlink_check();
1494
1495                         /*
1496                          * Refresh default router list.
1497                          */
1498                         defrouter_select_fib(dr->ifp->if_fib);
1499                 }
1500
1501                 /*
1502                  * If this entry was added by an on-link redirect, remove the
1503                  * corresponding host route.
1504                  */
1505                 if (ln->la_flags & LLE_REDIRECT)
1506                         nd6_free_redirect(ln);
1507
1508                 if (ln->ln_router || dr)
1509                         LLE_WLOCK(ln);
1510         }
1511
1512         /*
1513          * Save to unlock. We still hold an extra reference and will not
1514          * free(9) in llentry_free() if someone else holds one as well.
1515          */
1516         LLE_WUNLOCK(ln);
1517         IF_AFDATA_LOCK(ifp);
1518         LLE_WLOCK(ln);
1519         /* Guard against race with other llentry_free(). */
1520         if (ln->la_flags & LLE_LINKED) {
1521                 /* Remove callout reference */
1522                 LLE_REMREF(ln);
1523                 lltable_unlink_entry(ln->lle_tbl, ln);
1524         }
1525         IF_AFDATA_UNLOCK(ifp);
1526
1527         llentry_free(ln);
1528         if (dr != NULL)
1529                 defrouter_rele(dr);
1530 }
1531
1532 static int
1533 nd6_isdynrte(const struct rtentry *rt, const struct nhop_object *nh, void *xap)
1534 {
1535
1536         if (nh->nh_flags & NHF_REDIRECT)
1537                 return (1);
1538
1539         return (0);
1540 }
1541
1542 /*
1543  * Remove the rtentry for the given llentry,
1544  * both of which were installed by a redirect.
1545  */
1546 static void
1547 nd6_free_redirect(const struct llentry *ln)
1548 {
1549         int fibnum;
1550         struct sockaddr_in6 sin6;
1551         struct rt_addrinfo info;
1552         struct rib_cmd_info rc;
1553         struct epoch_tracker et;
1554
1555         lltable_fill_sa_entry(ln, (struct sockaddr *)&sin6);
1556         memset(&info, 0, sizeof(info));
1557         info.rti_info[RTAX_DST] = (struct sockaddr *)&sin6;
1558         info.rti_filter = nd6_isdynrte;
1559
1560         NET_EPOCH_ENTER(et);
1561         for (fibnum = 0; fibnum < rt_numfibs; fibnum++)
1562                 rib_action(fibnum, RTM_DELETE, &info, &rc);
1563         NET_EPOCH_EXIT(et);
1564 }
1565
1566 /*
1567  * Updates status of the default router route.
1568  */
1569 static void
1570 check_release_defrouter(struct rib_cmd_info *rc, void *_cbdata)
1571 {
1572         struct nd_defrouter *dr;
1573         struct nhop_object *nh;
1574
1575         nh = rc->rc_nh_old;
1576
1577         if ((nh != NULL) && (nh->nh_flags & NHF_DEFAULT)) {
1578                 dr = defrouter_lookup(&nh->gw6_sa.sin6_addr, nh->nh_ifp);
1579                 if (dr != NULL) {
1580                         dr->installed = 0;
1581                         defrouter_rele(dr);
1582                 }
1583         }
1584 }
1585
1586 void
1587 nd6_subscription_cb(struct rib_head *rnh, struct rib_cmd_info *rc, void *arg)
1588 {
1589
1590 #ifdef ROUTE_MPATH
1591         rib_decompose_notification(rc, check_release_defrouter, NULL);
1592 #else
1593         check_release_defrouter(rc, NULL);
1594 #endif
1595 }
1596
1597 int
1598 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1599 {
1600         struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1601         struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1602         struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1603         struct epoch_tracker et;
1604         int error = 0;
1605
1606         if (ifp->if_afdata[AF_INET6] == NULL)
1607                 return (EPFNOSUPPORT);
1608         switch (cmd) {
1609         case OSIOCGIFINFO_IN6:
1610 #define ND      ndi->ndi
1611                 /* XXX: old ndp(8) assumes a positive value for linkmtu. */
1612                 bzero(&ND, sizeof(ND));
1613                 ND.linkmtu = IN6_LINKMTU(ifp);
1614                 ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
1615                 ND.basereachable = ND_IFINFO(ifp)->basereachable;
1616                 ND.reachable = ND_IFINFO(ifp)->reachable;
1617                 ND.retrans = ND_IFINFO(ifp)->retrans;
1618                 ND.flags = ND_IFINFO(ifp)->flags;
1619                 ND.recalctm = ND_IFINFO(ifp)->recalctm;
1620                 ND.chlim = ND_IFINFO(ifp)->chlim;
1621                 break;
1622         case SIOCGIFINFO_IN6:
1623                 ND = *ND_IFINFO(ifp);
1624                 break;
1625         case SIOCSIFINFO_IN6:
1626                 /*
1627                  * used to change host variables from userland.
1628                  * intended for a use on router to reflect RA configurations.
1629                  */
1630                 /* 0 means 'unspecified' */
1631                 if (ND.linkmtu != 0) {
1632                         if (ND.linkmtu < IPV6_MMTU ||
1633                             ND.linkmtu > IN6_LINKMTU(ifp)) {
1634                                 error = EINVAL;
1635                                 break;
1636                         }
1637                         ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
1638                 }
1639
1640                 if (ND.basereachable != 0) {
1641                         int obasereachable = ND_IFINFO(ifp)->basereachable;
1642
1643                         ND_IFINFO(ifp)->basereachable = ND.basereachable;
1644                         if (ND.basereachable != obasereachable)
1645                                 ND_IFINFO(ifp)->reachable =
1646                                     ND_COMPUTE_RTIME(ND.basereachable);
1647                 }
1648                 if (ND.retrans != 0)
1649                         ND_IFINFO(ifp)->retrans = ND.retrans;
1650                 if (ND.chlim != 0)
1651                         ND_IFINFO(ifp)->chlim = ND.chlim;
1652                 /* FALLTHROUGH */
1653         case SIOCSIFINFO_FLAGS:
1654         {
1655                 struct ifaddr *ifa;
1656                 struct in6_ifaddr *ia;
1657
1658                 if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1659                     !(ND.flags & ND6_IFF_IFDISABLED)) {
1660                         /* ifdisabled 1->0 transision */
1661
1662                         /*
1663                          * If the interface is marked as ND6_IFF_IFDISABLED and
1664                          * has an link-local address with IN6_IFF_DUPLICATED,
1665                          * do not clear ND6_IFF_IFDISABLED.
1666                          * See RFC 4862, Section 5.4.5.
1667                          */
1668                         NET_EPOCH_ENTER(et);
1669                         CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1670                                 if (ifa->ifa_addr->sa_family != AF_INET6)
1671                                         continue;
1672                                 ia = (struct in6_ifaddr *)ifa;
1673                                 if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
1674                                     IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1675                                         break;
1676                         }
1677                         NET_EPOCH_EXIT(et);
1678
1679                         if (ifa != NULL) {
1680                                 /* LLA is duplicated. */
1681                                 ND.flags |= ND6_IFF_IFDISABLED;
1682                                 log(LOG_ERR, "Cannot enable an interface"
1683                                     " with a link-local address marked"
1684                                     " duplicate.\n");
1685                         } else {
1686                                 ND_IFINFO(ifp)->flags &= ~ND6_IFF_IFDISABLED;
1687                                 if (ifp->if_flags & IFF_UP)
1688                                         in6_if_up(ifp);
1689                         }
1690                 } else if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1691                             (ND.flags & ND6_IFF_IFDISABLED)) {
1692                         /* ifdisabled 0->1 transision */
1693                         /* Mark all IPv6 address as tentative. */
1694
1695                         ND_IFINFO(ifp)->flags |= ND6_IFF_IFDISABLED;
1696                         if (V_ip6_dad_count > 0 &&
1697                             (ND_IFINFO(ifp)->flags & ND6_IFF_NO_DAD) == 0) {
1698                                 NET_EPOCH_ENTER(et);
1699                                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead,
1700                                     ifa_link) {
1701                                         if (ifa->ifa_addr->sa_family !=
1702                                             AF_INET6)
1703                                                 continue;
1704                                         ia = (struct in6_ifaddr *)ifa;
1705                                         ia->ia6_flags |= IN6_IFF_TENTATIVE;
1706                                 }
1707                                 NET_EPOCH_EXIT(et);
1708                         }
1709                 }
1710
1711                 if (ND.flags & ND6_IFF_AUTO_LINKLOCAL) {
1712                         if (!(ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL)) {
1713                                 /* auto_linklocal 0->1 transision */
1714
1715                                 /* If no link-local address on ifp, configure */
1716                                 ND_IFINFO(ifp)->flags |= ND6_IFF_AUTO_LINKLOCAL;
1717                                 in6_ifattach(ifp, NULL);
1718                         } else if (!(ND.flags & ND6_IFF_IFDISABLED) &&
1719                             ifp->if_flags & IFF_UP) {
1720                                 /*
1721                                  * When the IF already has
1722                                  * ND6_IFF_AUTO_LINKLOCAL, no link-local
1723                                  * address is assigned, and IFF_UP, try to
1724                                  * assign one.
1725                                  */
1726                                 NET_EPOCH_ENTER(et);
1727                                 CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead,
1728                                     ifa_link) {
1729                                         if (ifa->ifa_addr->sa_family !=
1730                                             AF_INET6)
1731                                                 continue;
1732                                         ia = (struct in6_ifaddr *)ifa;
1733                                         if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1734                                                 break;
1735                                 }
1736                                 NET_EPOCH_EXIT(et);
1737                                 if (ifa != NULL)
1738                                         /* No LLA is configured. */
1739                                         in6_ifattach(ifp, NULL);
1740                         }
1741                 }
1742                 ND_IFINFO(ifp)->flags = ND.flags;
1743                 break;
1744         }
1745 #undef ND
1746         case SIOCSNDFLUSH_IN6:  /* XXX: the ioctl name is confusing... */
1747                 /* sync kernel routing table with the default router list */
1748                 defrouter_reset();
1749                 defrouter_select_fib(RT_ALL_FIBS);
1750                 break;
1751         case SIOCSPFXFLUSH_IN6:
1752         {
1753                 /* flush all the prefix advertised by routers */
1754                 struct in6_ifaddr *ia, *ia_next;
1755                 struct nd_prefix *pr, *next;
1756                 struct nd_prhead prl;
1757
1758                 LIST_INIT(&prl);
1759
1760                 ND6_WLOCK();
1761                 LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, next) {
1762                         if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1763                                 continue; /* XXX */
1764                         nd6_prefix_unlink(pr, &prl);
1765                 }
1766                 ND6_WUNLOCK();
1767
1768                 while ((pr = LIST_FIRST(&prl)) != NULL) {
1769                         LIST_REMOVE(pr, ndpr_entry);
1770                         /* XXXRW: in6_ifaddrhead locking. */
1771                         CK_STAILQ_FOREACH_SAFE(ia, &V_in6_ifaddrhead, ia_link,
1772                             ia_next) {
1773                                 if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1774                                         continue;
1775
1776                                 if (ia->ia6_ndpr == pr)
1777                                         in6_purgeaddr(&ia->ia_ifa);
1778                         }
1779                         nd6_prefix_del(pr);
1780                 }
1781                 break;
1782         }
1783         case SIOCSRTRFLUSH_IN6:
1784         {
1785                 /* flush all the default routers */
1786
1787                 defrouter_reset();
1788                 nd6_defrouter_flush_all();
1789                 defrouter_select_fib(RT_ALL_FIBS);
1790                 break;
1791         }
1792         case SIOCGNBRINFO_IN6:
1793         {
1794                 struct llentry *ln;
1795                 struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1796
1797                 if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
1798                         return (error);
1799
1800                 NET_EPOCH_ENTER(et);
1801                 ln = nd6_lookup(&nb_addr, 0, ifp);
1802                 NET_EPOCH_EXIT(et);
1803
1804                 if (ln == NULL) {
1805                         error = EINVAL;
1806                         break;
1807                 }
1808                 nbi->state = ln->ln_state;
1809                 nbi->asked = ln->la_asked;
1810                 nbi->isrouter = ln->ln_router;
1811                 if (ln->la_expire == 0)
1812                         nbi->expire = 0;
1813                 else
1814                         nbi->expire = ln->la_expire + ln->lle_remtime / hz +
1815                             (time_second - time_uptime);
1816                 LLE_RUNLOCK(ln);
1817                 break;
1818         }
1819         case SIOCGDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1820                 ndif->ifindex = V_nd6_defifindex;
1821                 break;
1822         case SIOCSDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1823                 return (nd6_setdefaultiface(ndif->ifindex));
1824         }
1825         return (error);
1826 }
1827
1828 /*
1829  * Calculates new isRouter value based on provided parameters and
1830  * returns it.
1831  */
1832 static int
1833 nd6_is_router(int type, int code, int is_new, int old_addr, int new_addr,
1834     int ln_router)
1835 {
1836
1837         /*
1838          * ICMP6 type dependent behavior.
1839          *
1840          * NS: clear IsRouter if new entry
1841          * RS: clear IsRouter
1842          * RA: set IsRouter if there's lladdr
1843          * redir: clear IsRouter if new entry
1844          *
1845          * RA case, (1):
1846          * The spec says that we must set IsRouter in the following cases:
1847          * - If lladdr exist, set IsRouter.  This means (1-5).
1848          * - If it is old entry (!newentry), set IsRouter.  This means (7).
1849          * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1850          * A quetion arises for (1) case.  (1) case has no lladdr in the
1851          * neighbor cache, this is similar to (6).
1852          * This case is rare but we figured that we MUST NOT set IsRouter.
1853          *
1854          *   is_new  old_addr new_addr      NS  RS  RA  redir
1855          *                                                      D R
1856          *      0       n       n       (1)     c   ?     s
1857          *      0       y       n       (2)     c   s     s
1858          *      0       n       y       (3)     c   s     s
1859          *      0       y       y       (4)     c   s     s
1860          *      0       y       y       (5)     c   s     s
1861          *      1       --      n       (6) c   c       c s
1862          *      1       --      y       (7) c   c   s   c s
1863          *
1864          *                                      (c=clear s=set)
1865          */
1866         switch (type & 0xff) {
1867         case ND_NEIGHBOR_SOLICIT:
1868                 /*
1869                  * New entry must have is_router flag cleared.
1870                  */
1871                 if (is_new)                                     /* (6-7) */
1872                         ln_router = 0;
1873                 break;
1874         case ND_REDIRECT:
1875                 /*
1876                  * If the icmp is a redirect to a better router, always set the
1877                  * is_router flag.  Otherwise, if the entry is newly created,
1878                  * clear the flag.  [RFC 2461, sec 8.3]
1879                  */
1880                 if (code == ND_REDIRECT_ROUTER)
1881                         ln_router = 1;
1882                 else {
1883                         if (is_new)                             /* (6-7) */
1884                                 ln_router = 0;
1885                 }
1886                 break;
1887         case ND_ROUTER_SOLICIT:
1888                 /*
1889                  * is_router flag must always be cleared.
1890                  */
1891                 ln_router = 0;
1892                 break;
1893         case ND_ROUTER_ADVERT:
1894                 /*
1895                  * Mark an entry with lladdr as a router.
1896                  */
1897                 if ((!is_new && (old_addr || new_addr)) ||      /* (2-5) */
1898                     (is_new && new_addr)) {                     /* (7) */
1899                         ln_router = 1;
1900                 }
1901                 break;
1902         }
1903
1904         return (ln_router);
1905 }
1906
1907 /*
1908  * Create neighbor cache entry and cache link-layer address,
1909  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1910  *
1911  * type - ICMP6 type
1912  * code - type dependent information
1913  *
1914  */
1915 void
1916 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1917     int lladdrlen, int type, int code)
1918 {
1919         struct llentry *ln = NULL, *ln_tmp;
1920         int is_newentry;
1921         int do_update;
1922         int olladdr;
1923         int llchange;
1924         int flags;
1925         uint16_t router = 0;
1926         struct mbuf *chain = NULL;
1927         u_char linkhdr[LLE_MAX_LINKHDR];
1928         size_t linkhdrsize;
1929         int lladdr_off;
1930
1931         NET_EPOCH_ASSERT();
1932         IF_AFDATA_UNLOCK_ASSERT(ifp);
1933
1934         KASSERT(ifp != NULL, ("%s: ifp == NULL", __func__));
1935         KASSERT(from != NULL, ("%s: from == NULL", __func__));
1936
1937         /* nothing must be updated for unspecified address */
1938         if (IN6_IS_ADDR_UNSPECIFIED(from))
1939                 return;
1940
1941         /*
1942          * Validation about ifp->if_addrlen and lladdrlen must be done in
1943          * the caller.
1944          *
1945          * XXX If the link does not have link-layer adderss, what should
1946          * we do? (ifp->if_addrlen == 0)
1947          * Spec says nothing in sections for RA, RS and NA.  There's small
1948          * description on it in NS section (RFC 2461 7.2.3).
1949          */
1950         flags = lladdr ? LLE_EXCLUSIVE : 0;
1951         ln = nd6_lookup(from, flags, ifp);
1952         is_newentry = 0;
1953         if (ln == NULL) {
1954                 flags |= LLE_EXCLUSIVE;
1955                 ln = nd6_alloc(from, 0, ifp);
1956                 if (ln == NULL)
1957                         return;
1958
1959                 /*
1960                  * Since we already know all the data for the new entry,
1961                  * fill it before insertion.
1962                  */
1963                 if (lladdr != NULL) {
1964                         linkhdrsize = sizeof(linkhdr);
1965                         if (lltable_calc_llheader(ifp, AF_INET6, lladdr,
1966                             linkhdr, &linkhdrsize, &lladdr_off) != 0)
1967                                 return;
1968                         lltable_set_entry_addr(ifp, ln, linkhdr, linkhdrsize,
1969                             lladdr_off);
1970                 }
1971
1972                 IF_AFDATA_WLOCK(ifp);
1973                 LLE_WLOCK(ln);
1974                 /* Prefer any existing lle over newly-created one */
1975                 ln_tmp = nd6_lookup(from, LLE_EXCLUSIVE, ifp);
1976                 if (ln_tmp == NULL)
1977                         lltable_link_entry(LLTABLE6(ifp), ln);
1978                 IF_AFDATA_WUNLOCK(ifp);
1979                 if (ln_tmp == NULL) {
1980                         /* No existing lle, mark as new entry (6,7) */
1981                         is_newentry = 1;
1982                         if (lladdr != NULL) {   /* (7) */
1983                                 nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
1984                                 EVENTHANDLER_INVOKE(lle_event, ln,
1985                                     LLENTRY_RESOLVED);
1986                         }
1987                 } else {
1988                         lltable_free_entry(LLTABLE6(ifp), ln);
1989                         ln = ln_tmp;
1990                         ln_tmp = NULL;
1991                 }
1992         } 
1993         /* do nothing if static ndp is set */
1994         if ((ln->la_flags & LLE_STATIC)) {
1995                 if (flags & LLE_EXCLUSIVE)
1996                         LLE_WUNLOCK(ln);
1997                 else
1998                         LLE_RUNLOCK(ln);
1999                 return;
2000         }
2001
2002         olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
2003         if (olladdr && lladdr) {
2004                 llchange = bcmp(lladdr, ln->ll_addr,
2005                     ifp->if_addrlen);
2006         } else if (!olladdr && lladdr)
2007                 llchange = 1;
2008         else
2009                 llchange = 0;
2010
2011         /*
2012          * newentry olladdr  lladdr  llchange   (*=record)
2013          *      0       n       n       --      (1)
2014          *      0       y       n       --      (2)
2015          *      0       n       y       y       (3) * STALE
2016          *      0       y       y       n       (4) *
2017          *      0       y       y       y       (5) * STALE
2018          *      1       --      n       --      (6)   NOSTATE(= PASSIVE)
2019          *      1       --      y       --      (7) * STALE
2020          */
2021
2022         do_update = 0;
2023         if (is_newentry == 0 && llchange != 0) {
2024                 do_update = 1;  /* (3,5) */
2025
2026                 /*
2027                  * Record source link-layer address
2028                  * XXX is it dependent to ifp->if_type?
2029                  */
2030                 linkhdrsize = sizeof(linkhdr);
2031                 if (lltable_calc_llheader(ifp, AF_INET6, lladdr,
2032                     linkhdr, &linkhdrsize, &lladdr_off) != 0)
2033                         return;
2034
2035                 if (lltable_try_set_entry_addr(ifp, ln, linkhdr, linkhdrsize,
2036                     lladdr_off) == 0) {
2037                         /* Entry was deleted */
2038                         return;
2039                 }
2040
2041                 nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
2042
2043                 EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
2044
2045                 if (ln->la_hold != NULL)
2046                         chain = nd6_grab_holdchain(ln);
2047         }
2048
2049         /* Calculates new router status */
2050         router = nd6_is_router(type, code, is_newentry, olladdr,
2051             lladdr != NULL ? 1 : 0, ln->ln_router);
2052
2053         ln->ln_router = router;
2054         /* Mark non-router redirects with special flag */
2055         if ((type & 0xFF) == ND_REDIRECT && code != ND_REDIRECT_ROUTER)
2056                 ln->la_flags |= LLE_REDIRECT;
2057
2058         if (flags & LLE_EXCLUSIVE)
2059                 LLE_WUNLOCK(ln);
2060         else
2061                 LLE_RUNLOCK(ln);
2062
2063         if (chain != NULL)
2064                 nd6_flush_holdchain(ifp, ln, chain);
2065
2066         /*
2067          * When the link-layer address of a router changes, select the
2068          * best router again.  In particular, when the neighbor entry is newly
2069          * created, it might affect the selection policy.
2070          * Question: can we restrict the first condition to the "is_newentry"
2071          * case?
2072          * XXX: when we hear an RA from a new router with the link-layer
2073          * address option, defrouter_select_fib() is called twice, since
2074          * defrtrlist_update called the function as well.  However, I believe
2075          * we can compromise the overhead, since it only happens the first
2076          * time.
2077          * XXX: although defrouter_select_fib() should not have a bad effect
2078          * for those are not autoconfigured hosts, we explicitly avoid such
2079          * cases for safety.
2080          */
2081         if ((do_update || is_newentry) && router &&
2082             ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
2083                 /*
2084                  * guaranteed recursion
2085                  */
2086                 defrouter_select_fib(ifp->if_fib);
2087         }
2088 }
2089
2090 static void
2091 nd6_slowtimo(void *arg)
2092 {
2093         struct epoch_tracker et;
2094         CURVNET_SET((struct vnet *) arg);
2095         struct nd_ifinfo *nd6if;
2096         struct ifnet *ifp;
2097
2098         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
2099             nd6_slowtimo, curvnet);
2100         NET_EPOCH_ENTER(et);
2101         CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2102                 if (ifp->if_afdata[AF_INET6] == NULL)
2103                         continue;
2104                 nd6if = ND_IFINFO(ifp);
2105                 if (nd6if->basereachable && /* already initialized */
2106                     (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
2107                         /*
2108                          * Since reachable time rarely changes by router
2109                          * advertisements, we SHOULD insure that a new random
2110                          * value gets recomputed at least once every few hours.
2111                          * (RFC 2461, 6.3.4)
2112                          */
2113                         nd6if->recalctm = V_nd6_recalc_reachtm_interval;
2114                         nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
2115                 }
2116         }
2117         NET_EPOCH_EXIT(et);
2118         CURVNET_RESTORE();
2119 }
2120
2121 struct mbuf *
2122 nd6_grab_holdchain(struct llentry *ln)
2123 {
2124         struct mbuf *chain;
2125
2126         LLE_WLOCK_ASSERT(ln);
2127
2128         chain = ln->la_hold;
2129         ln->la_hold = NULL;
2130
2131         if (ln->ln_state == ND6_LLINFO_STALE) {
2132                 /*
2133                  * The first time we send a packet to a
2134                  * neighbor whose entry is STALE, we have
2135                  * to change the state to DELAY and a sets
2136                  * a timer to expire in DELAY_FIRST_PROBE_TIME
2137                  * seconds to ensure do neighbor unreachability
2138                  * detection on expiration.
2139                  * (RFC 2461 7.3.3)
2140                  */
2141                 nd6_llinfo_setstate(ln, ND6_LLINFO_DELAY);
2142         }
2143
2144         return (chain);
2145 }
2146
2147 int
2148 nd6_output_ifp(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
2149     struct sockaddr_in6 *dst, struct route *ro)
2150 {
2151         int error;
2152         int ip6len;
2153         struct ip6_hdr *ip6;
2154         struct m_tag *mtag;
2155
2156 #ifdef MAC
2157         mac_netinet6_nd6_send(ifp, m);
2158 #endif
2159
2160         /*
2161          * If called from nd6_ns_output() (NS), nd6_na_output() (NA),
2162          * icmp6_redirect_output() (REDIRECT) or from rip6_output() (RS, RA
2163          * as handled by rtsol and rtadvd), mbufs will be tagged for SeND
2164          * to be diverted to user space.  When re-injected into the kernel,
2165          * send_output() will directly dispatch them to the outgoing interface.
2166          */
2167         if (send_sendso_input_hook != NULL) {
2168                 mtag = m_tag_find(m, PACKET_TAG_ND_OUTGOING, NULL);
2169                 if (mtag != NULL) {
2170                         ip6 = mtod(m, struct ip6_hdr *);
2171                         ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
2172                         /* Use the SEND socket */
2173                         error = send_sendso_input_hook(m, ifp, SND_OUT,
2174                             ip6len);
2175                         /* -1 == no app on SEND socket */
2176                         if (error == 0 || error != -1)
2177                             return (error);
2178                 }
2179         }
2180
2181         m_clrprotoflags(m);     /* Avoid confusing lower layers. */
2182         IP_PROBE(send, NULL, NULL, mtod(m, struct ip6_hdr *), ifp, NULL,
2183             mtod(m, struct ip6_hdr *));
2184
2185         if ((ifp->if_flags & IFF_LOOPBACK) == 0)
2186                 origifp = ifp;
2187
2188         error = (*ifp->if_output)(origifp, m, (struct sockaddr *)dst, ro);
2189         return (error);
2190 }
2191
2192 /*
2193  * Lookup link headerfor @sa_dst address. Stores found
2194  * data in @desten buffer. Copy of lle ln_flags can be also
2195  * saved in @pflags if @pflags is non-NULL.
2196  *
2197  * If destination LLE does not exists or lle state modification
2198  * is required, call "slow" version.
2199  *
2200  * Return values:
2201  * - 0 on success (address copied to buffer).
2202  * - EWOULDBLOCK (no local error, but address is still unresolved)
2203  * - other errors (alloc failure, etc)
2204  */
2205 int
2206 nd6_resolve(struct ifnet *ifp, int is_gw, struct mbuf *m,
2207     const struct sockaddr *sa_dst, u_char *desten, uint32_t *pflags,
2208     struct llentry **plle)
2209 {
2210         struct llentry *ln = NULL;
2211         const struct sockaddr_in6 *dst6;
2212
2213         NET_EPOCH_ASSERT();
2214
2215         if (pflags != NULL)
2216                 *pflags = 0;
2217
2218         dst6 = (const struct sockaddr_in6 *)sa_dst;
2219
2220         /* discard the packet if IPv6 operation is disabled on the interface */
2221         if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
2222                 m_freem(m);
2223                 return (ENETDOWN); /* better error? */
2224         }
2225
2226         if (m != NULL && m->m_flags & M_MCAST) {
2227                 switch (ifp->if_type) {
2228                 case IFT_ETHER:
2229                 case IFT_L2VLAN:
2230                 case IFT_BRIDGE:
2231                         ETHER_MAP_IPV6_MULTICAST(&dst6->sin6_addr,
2232                                                  desten);
2233                         return (0);
2234                 default:
2235                         m_freem(m);
2236                         return (EAFNOSUPPORT);
2237                 }
2238         }
2239
2240         ln = nd6_lookup(&dst6->sin6_addr, plle ? LLE_EXCLUSIVE : LLE_UNLOCKED,
2241             ifp);
2242         if (ln != NULL && (ln->r_flags & RLLE_VALID) != 0) {
2243                 /* Entry found, let's copy lle info */
2244                 bcopy(ln->r_linkdata, desten, ln->r_hdrlen);
2245                 if (pflags != NULL)
2246                         *pflags = LLE_VALID | (ln->r_flags & RLLE_IFADDR);
2247                 llentry_provide_feedback(ln);
2248                 if (plle) {
2249                         LLE_ADDREF(ln);
2250                         *plle = ln;
2251                         LLE_WUNLOCK(ln);
2252                 }
2253                 return (0);
2254         } else if (plle && ln)
2255                 LLE_WUNLOCK(ln);
2256
2257         return (nd6_resolve_slow(ifp, 0, m, dst6, desten, pflags, plle));
2258 }
2259
2260 /*
2261  * Do L2 address resolution for @sa_dst address. Stores found
2262  * address in @desten buffer. Copy of lle ln_flags can be also
2263  * saved in @pflags if @pflags is non-NULL.
2264  *
2265  * Heavy version.
2266  * Function assume that destination LLE does not exist,
2267  * is invalid or stale, so LLE_EXCLUSIVE lock needs to be acquired.
2268  *
2269  * Set noinline to be dtrace-friendly
2270  */
2271 static __noinline int
2272 nd6_resolve_slow(struct ifnet *ifp, int flags, struct mbuf *m,
2273     const struct sockaddr_in6 *dst, u_char *desten, uint32_t *pflags,
2274     struct llentry **plle)
2275 {
2276         struct llentry *lle = NULL, *lle_tmp;
2277         struct in6_addr *psrc, src;
2278         int send_ns, ll_len;
2279         char *lladdr;
2280
2281         NET_EPOCH_ASSERT();
2282
2283         /*
2284          * Address resolution or Neighbor Unreachability Detection
2285          * for the next hop.
2286          * At this point, the destination of the packet must be a unicast
2287          * or an anycast address(i.e. not a multicast).
2288          */
2289         if (lle == NULL) {
2290                 lle = nd6_lookup(&dst->sin6_addr, LLE_EXCLUSIVE, ifp);
2291                 if ((lle == NULL) && nd6_is_addr_neighbor(dst, ifp))  {
2292                         /*
2293                          * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
2294                          * the condition below is not very efficient.  But we believe
2295                          * it is tolerable, because this should be a rare case.
2296                          */
2297                         lle = nd6_alloc(&dst->sin6_addr, 0, ifp);
2298                         if (lle == NULL) {
2299                                 char ip6buf[INET6_ADDRSTRLEN];
2300                                 log(LOG_DEBUG,
2301                                     "nd6_output: can't allocate llinfo for %s "
2302                                     "(ln=%p)\n",
2303                                     ip6_sprintf(ip6buf, &dst->sin6_addr), lle);
2304                                 m_freem(m);
2305                                 return (ENOBUFS);
2306                         }
2307
2308                         IF_AFDATA_WLOCK(ifp);
2309                         LLE_WLOCK(lle);
2310                         /* Prefer any existing entry over newly-created one */
2311                         lle_tmp = nd6_lookup(&dst->sin6_addr, LLE_EXCLUSIVE, ifp);
2312                         if (lle_tmp == NULL)
2313                                 lltable_link_entry(LLTABLE6(ifp), lle);
2314                         IF_AFDATA_WUNLOCK(ifp);
2315                         if (lle_tmp != NULL) {
2316                                 lltable_free_entry(LLTABLE6(ifp), lle);
2317                                 lle = lle_tmp;
2318                                 lle_tmp = NULL;
2319                         }
2320                 }
2321         } 
2322         if (lle == NULL) {
2323                 m_freem(m);
2324                 return (ENOBUFS);
2325         }
2326
2327         LLE_WLOCK_ASSERT(lle);
2328
2329         /*
2330          * The first time we send a packet to a neighbor whose entry is
2331          * STALE, we have to change the state to DELAY and a sets a timer to
2332          * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
2333          * neighbor unreachability detection on expiration.
2334          * (RFC 2461 7.3.3)
2335          */
2336         if (lle->ln_state == ND6_LLINFO_STALE)
2337                 nd6_llinfo_setstate(lle, ND6_LLINFO_DELAY);
2338
2339         /*
2340          * If the neighbor cache entry has a state other than INCOMPLETE
2341          * (i.e. its link-layer address is already resolved), just
2342          * send the packet.
2343          */
2344         if (lle->ln_state > ND6_LLINFO_INCOMPLETE) {
2345                 if (flags & LLE_ADDRONLY) {
2346                         lladdr = lle->ll_addr;
2347                         ll_len = ifp->if_addrlen;
2348                 } else {
2349                         lladdr = lle->r_linkdata;
2350                         ll_len = lle->r_hdrlen;
2351                 }
2352                 bcopy(lladdr, desten, ll_len);
2353                 if (pflags != NULL)
2354                         *pflags = lle->la_flags;
2355                 if (plle) {
2356                         LLE_ADDREF(lle);
2357                         *plle = lle;
2358                 }
2359                 LLE_WUNLOCK(lle);
2360                 return (0);
2361         }
2362
2363         /*
2364          * There is a neighbor cache entry, but no ethernet address
2365          * response yet.  Append this latest packet to the end of the
2366          * packet queue in the mbuf.  When it exceeds nd6_maxqueuelen,
2367          * the oldest packet in the queue will be removed.
2368          */
2369
2370         if (lle->la_hold != NULL) {
2371                 struct mbuf *m_hold;
2372                 int i;
2373                 
2374                 i = 0;
2375                 for (m_hold = lle->la_hold; m_hold; m_hold = m_hold->m_nextpkt){
2376                         i++;
2377                         if (m_hold->m_nextpkt == NULL) {
2378                                 m_hold->m_nextpkt = m;
2379                                 break;
2380                         }
2381                 }
2382                 while (i >= V_nd6_maxqueuelen) {
2383                         m_hold = lle->la_hold;
2384                         lle->la_hold = lle->la_hold->m_nextpkt;
2385                         m_freem(m_hold);
2386                         i--;
2387                 }
2388         } else {
2389                 lle->la_hold = m;
2390         }
2391
2392         /*
2393          * If there has been no NS for the neighbor after entering the
2394          * INCOMPLETE state, send the first solicitation.
2395          * Note that for newly-created lle la_asked will be 0,
2396          * so we will transition from ND6_LLINFO_NOSTATE to
2397          * ND6_LLINFO_INCOMPLETE state here.
2398          */
2399         psrc = NULL;
2400         send_ns = 0;
2401         if (lle->la_asked == 0) {
2402                 lle->la_asked++;
2403                 send_ns = 1;
2404                 psrc = nd6_llinfo_get_holdsrc(lle, &src);
2405
2406                 nd6_llinfo_setstate(lle, ND6_LLINFO_INCOMPLETE);
2407         }
2408         LLE_WUNLOCK(lle);
2409         if (send_ns != 0)
2410                 nd6_ns_output(ifp, psrc, NULL, &dst->sin6_addr, NULL);
2411
2412         return (EWOULDBLOCK);
2413 }
2414
2415 /*
2416  * Do L2 address resolution for @sa_dst address. Stores found
2417  * address in @desten buffer. Copy of lle ln_flags can be also
2418  * saved in @pflags if @pflags is non-NULL.
2419  *
2420  * Return values:
2421  * - 0 on success (address copied to buffer).
2422  * - EWOULDBLOCK (no local error, but address is still unresolved)
2423  * - other errors (alloc failure, etc)
2424  */
2425 int
2426 nd6_resolve_addr(struct ifnet *ifp, int flags, const struct sockaddr *dst,
2427     char *desten, uint32_t *pflags)
2428 {
2429         int error;
2430
2431         flags |= LLE_ADDRONLY;
2432         error = nd6_resolve_slow(ifp, flags, NULL,
2433             (const struct sockaddr_in6 *)dst, desten, pflags, NULL);
2434         return (error);
2435 }
2436
2437 int
2438 nd6_flush_holdchain(struct ifnet *ifp, struct llentry *lle, struct mbuf *chain)
2439 {
2440         struct mbuf *m, *m_head;
2441         struct sockaddr_in6 dst6;
2442         int error = 0;
2443
2444         NET_EPOCH_ASSERT();
2445
2446         struct route_in6 ro = {
2447                 .ro_prepend = lle->r_linkdata,
2448                 .ro_plen = lle->r_hdrlen,
2449         };
2450
2451         lltable_fill_sa_entry(lle, (struct sockaddr *)&dst6);
2452         m_head = chain;
2453
2454         while (m_head) {
2455                 m = m_head;
2456                 m_head = m_head->m_nextpkt;
2457                 m->m_nextpkt = NULL;
2458                 error = nd6_output_ifp(ifp, ifp, m, &dst6, (struct route *)&ro);
2459         }
2460
2461         /*
2462          * XXX
2463          * note that intermediate errors are blindly ignored
2464          */
2465         return (error);
2466 }
2467
2468 static int
2469 nd6_need_cache(struct ifnet *ifp)
2470 {
2471         /*
2472          * XXX: we currently do not make neighbor cache on any interface
2473          * other than Ethernet and GIF.
2474          *
2475          * RFC2893 says:
2476          * - unidirectional tunnels needs no ND
2477          */
2478         switch (ifp->if_type) {
2479         case IFT_ETHER:
2480         case IFT_IEEE1394:
2481         case IFT_L2VLAN:
2482         case IFT_INFINIBAND:
2483         case IFT_BRIDGE:
2484         case IFT_PROPVIRTUAL:
2485                 return (1);
2486         default:
2487                 return (0);
2488         }
2489 }
2490
2491 /*
2492  * Add pernament ND6 link-layer record for given
2493  * interface address.
2494  *
2495  * Very similar to IPv4 arp_ifinit(), but:
2496  * 1) IPv6 DAD is performed in different place
2497  * 2) It is called by IPv6 protocol stack in contrast to
2498  * arp_ifinit() which is typically called in SIOCSIFADDR
2499  * driver ioctl handler.
2500  *
2501  */
2502 int
2503 nd6_add_ifa_lle(struct in6_ifaddr *ia)
2504 {
2505         struct ifnet *ifp;
2506         struct llentry *ln, *ln_tmp;
2507         struct sockaddr *dst;
2508
2509         ifp = ia->ia_ifa.ifa_ifp;
2510         if (nd6_need_cache(ifp) == 0)
2511                 return (0);
2512
2513         dst = (struct sockaddr *)&ia->ia_addr;
2514         ln = lltable_alloc_entry(LLTABLE6(ifp), LLE_IFADDR, dst);
2515         if (ln == NULL)
2516                 return (ENOBUFS);
2517
2518         IF_AFDATA_WLOCK(ifp);
2519         LLE_WLOCK(ln);
2520         /* Unlink any entry if exists */
2521         ln_tmp = lla_lookup(LLTABLE6(ifp), LLE_EXCLUSIVE, dst);
2522         if (ln_tmp != NULL)
2523                 lltable_unlink_entry(LLTABLE6(ifp), ln_tmp);
2524         lltable_link_entry(LLTABLE6(ifp), ln);
2525         IF_AFDATA_WUNLOCK(ifp);
2526
2527         if (ln_tmp != NULL)
2528                 EVENTHANDLER_INVOKE(lle_event, ln_tmp, LLENTRY_EXPIRED);
2529         EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
2530
2531         LLE_WUNLOCK(ln);
2532         if (ln_tmp != NULL)
2533                 llentry_free(ln_tmp);
2534
2535         return (0);
2536 }
2537
2538 /*
2539  * Removes either all lle entries for given @ia, or lle
2540  * corresponding to @ia address.
2541  */
2542 void
2543 nd6_rem_ifa_lle(struct in6_ifaddr *ia, int all)
2544 {
2545         struct sockaddr_in6 mask, addr;
2546         struct sockaddr *saddr, *smask;
2547         struct ifnet *ifp;
2548
2549         ifp = ia->ia_ifa.ifa_ifp;
2550         memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
2551         memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
2552         saddr = (struct sockaddr *)&addr;
2553         smask = (struct sockaddr *)&mask;
2554
2555         if (all != 0)
2556                 lltable_prefix_free(AF_INET6, saddr, smask, LLE_STATIC);
2557         else
2558                 lltable_delete_addr(LLTABLE6(ifp), LLE_IFADDR, saddr);
2559 }
2560
2561 static void 
2562 clear_llinfo_pqueue(struct llentry *ln)
2563 {
2564         struct mbuf *m_hold, *m_hold_next;
2565
2566         for (m_hold = ln->la_hold; m_hold; m_hold = m_hold_next) {
2567                 m_hold_next = m_hold->m_nextpkt;
2568                 m_freem(m_hold);
2569         }
2570
2571         ln->la_hold = NULL;
2572 }
2573
2574 static int
2575 nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2576 {
2577         struct in6_prefix p;
2578         struct sockaddr_in6 s6;
2579         struct nd_prefix *pr;
2580         struct nd_pfxrouter *pfr;
2581         time_t maxexpire;
2582         int error;
2583         char ip6buf[INET6_ADDRSTRLEN];
2584
2585         if (req->newptr)
2586                 return (EPERM);
2587
2588         error = sysctl_wire_old_buffer(req, 0);
2589         if (error != 0)
2590                 return (error);
2591
2592         bzero(&p, sizeof(p));
2593         p.origin = PR_ORIG_RA;
2594         bzero(&s6, sizeof(s6));
2595         s6.sin6_family = AF_INET6;
2596         s6.sin6_len = sizeof(s6);
2597
2598         ND6_RLOCK();
2599         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
2600                 p.prefix = pr->ndpr_prefix;
2601                 if (sa6_recoverscope(&p.prefix)) {
2602                         log(LOG_ERR, "scope error in prefix list (%s)\n",
2603                             ip6_sprintf(ip6buf, &p.prefix.sin6_addr));
2604                         /* XXX: press on... */
2605                 }
2606                 p.raflags = pr->ndpr_raf;
2607                 p.prefixlen = pr->ndpr_plen;
2608                 p.vltime = pr->ndpr_vltime;
2609                 p.pltime = pr->ndpr_pltime;
2610                 p.if_index = pr->ndpr_ifp->if_index;
2611                 if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2612                         p.expire = 0;
2613                 else {
2614                         /* XXX: we assume time_t is signed. */
2615                         maxexpire = (-1) &
2616                             ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
2617                         if (pr->ndpr_vltime < maxexpire - pr->ndpr_lastupdate)
2618                                 p.expire = pr->ndpr_lastupdate +
2619                                     pr->ndpr_vltime +
2620                                     (time_second - time_uptime);
2621                         else
2622                                 p.expire = maxexpire;
2623                 }
2624                 p.refcnt = pr->ndpr_addrcnt;
2625                 p.flags = pr->ndpr_stateflags;
2626                 p.advrtrs = 0;
2627                 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
2628                         p.advrtrs++;
2629                 error = SYSCTL_OUT(req, &p, sizeof(p));
2630                 if (error != 0)
2631                         break;
2632                 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
2633                         s6.sin6_addr = pfr->router->rtaddr;
2634                         if (sa6_recoverscope(&s6))
2635                                 log(LOG_ERR,
2636                                     "scope error in prefix list (%s)\n",
2637                                     ip6_sprintf(ip6buf, &pfr->router->rtaddr));
2638                         error = SYSCTL_OUT(req, &s6, sizeof(s6));
2639                         if (error != 0)
2640                                 goto out;
2641                 }
2642         }
2643 out:
2644         ND6_RUNLOCK();
2645         return (error);
2646 }
2647 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2648         CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2649         NULL, 0, nd6_sysctl_prlist, "S,in6_prefix",
2650         "NDP prefix list");
2651 SYSCTL_INT(_net_inet6_icmp6, ICMPV6CTL_ND6_MAXQLEN, nd6_maxqueuelen,
2652         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_maxqueuelen), 1, "");
2653 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, nd6_gctimer,
2654         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_gctimer), (60 * 60 * 24), "");