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