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