]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/nd6.c
MF head @ r283796
[FreeBSD/FreeBSD.git] / sys / netinet6 / nd6.c
1 /*-
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the project nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      $KAME: nd6.c,v 1.144 2001/05/24 07:44:00 itojun Exp $
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/callout.h>
41 #include <sys/malloc.h>
42 #include <sys/mbuf.h>
43 #include <sys/socket.h>
44 #include <sys/sockio.h>
45 #include <sys/time.h>
46 #include <sys/kernel.h>
47 #include <sys/protosw.h>
48 #include <sys/errno.h>
49 #include <sys/syslog.h>
50 #include <sys/lock.h>
51 #include <sys/rwlock.h>
52 #include <sys/queue.h>
53 #include <sys/sdt.h>
54 #include <sys/sysctl.h>
55
56 #include <net/if.h>
57 #include <net/if_var.h>
58 #include <net/if_arc.h>
59 #include <net/if_dl.h>
60 #include <net/if_types.h>
61 #include <net/iso88025.h>
62 #include <net/fddi.h>
63 #include <net/route.h>
64 #include <net/vnet.h>
65
66 #include <netinet/in.h>
67 #include <netinet/in_kdtrace.h>
68 #include <net/if_llatbl.h>
69 #define L3_ADDR_SIN6(le)        ((struct sockaddr_in6 *) L3_ADDR(le))
70 #include <netinet/if_ether.h>
71 #include <netinet6/in6_var.h>
72 #include <netinet/ip6.h>
73 #include <netinet6/ip6_var.h>
74 #include <netinet6/scope6_var.h>
75 #include <netinet6/nd6.h>
76 #include <netinet6/in6_ifattach.h>
77 #include <netinet/icmp6.h>
78 #include <netinet6/send.h>
79
80 #include <sys/limits.h>
81
82 #include <security/mac/mac_framework.h>
83
84 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
85 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
86
87 #define SIN6(s) ((const struct sockaddr_in6 *)(s))
88
89 /* timer values */
90 VNET_DEFINE(int, nd6_prune)     = 1;    /* walk list every 1 seconds */
91 VNET_DEFINE(int, nd6_delay)     = 5;    /* delay first probe time 5 second */
92 VNET_DEFINE(int, nd6_umaxtries) = 3;    /* maximum unicast query */
93 VNET_DEFINE(int, nd6_mmaxtries) = 3;    /* maximum multicast query */
94 VNET_DEFINE(int, nd6_useloopback) = 1;  /* use loopback interface for
95                                          * local traffic */
96 VNET_DEFINE(int, nd6_gctimer)   = (60 * 60 * 24); /* 1 day: garbage
97                                          * collection timer */
98
99 /* preventing too many loops in ND option parsing */
100 static VNET_DEFINE(int, nd6_maxndopt) = 10; /* max # of ND options allowed */
101
102 VNET_DEFINE(int, nd6_maxnudhint) = 0;   /* max # of subsequent upper
103                                          * layer hints */
104 static VNET_DEFINE(int, nd6_maxqueuelen) = 1; /* max pkts cached in unresolved
105                                          * ND entries */
106 #define V_nd6_maxndopt                  VNET(nd6_maxndopt)
107 #define V_nd6_maxqueuelen               VNET(nd6_maxqueuelen)
108
109 #ifdef ND6_DEBUG
110 VNET_DEFINE(int, nd6_debug) = 1;
111 #else
112 VNET_DEFINE(int, nd6_debug) = 0;
113 #endif
114
115 /* for debugging? */
116 #if 0
117 static int nd6_inuse, nd6_allocated;
118 #endif
119
120 VNET_DEFINE(struct nd_drhead, nd_defrouter);
121 VNET_DEFINE(struct nd_prhead, nd_prefix);
122
123 VNET_DEFINE(int, nd6_recalc_reachtm_interval) = ND6_RECALC_REACHTM_INTERVAL;
124 #define V_nd6_recalc_reachtm_interval   VNET(nd6_recalc_reachtm_interval)
125
126 int     (*send_sendso_input_hook)(struct mbuf *, struct ifnet *, int, int);
127
128 static int nd6_is_new_addr_neighbor(struct sockaddr_in6 *,
129         struct ifnet *);
130 static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
131 static void nd6_slowtimo(void *);
132 static int regen_tmpaddr(struct in6_ifaddr *);
133 static struct llentry *nd6_free(struct llentry *, int);
134 static void nd6_llinfo_timer(void *);
135 static void clear_llinfo_pqueue(struct llentry *);
136 static void nd6_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
137 static int nd6_output_lle(struct ifnet *, struct ifnet *, struct mbuf *,
138         struct sockaddr_in6 *);
139 static int nd6_output_ifp(struct ifnet *, struct ifnet *, struct mbuf *,
140     struct sockaddr_in6 *);
141
142 static VNET_DEFINE(struct callout, nd6_slowtimo_ch);
143 #define V_nd6_slowtimo_ch               VNET(nd6_slowtimo_ch)
144
145 VNET_DEFINE(struct callout, nd6_timer_ch);
146
147 void
148 nd6_init(void)
149 {
150
151         LIST_INIT(&V_nd_prefix);
152
153         /* initialization of the default router list */
154         TAILQ_INIT(&V_nd_defrouter);
155
156         /* start timer */
157         callout_init(&V_nd6_slowtimo_ch, 0);
158         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
159             nd6_slowtimo, curvnet);
160
161         nd6_dad_init();
162 }
163
164 #ifdef VIMAGE
165 void
166 nd6_destroy()
167 {
168
169         callout_drain(&V_nd6_slowtimo_ch);
170         callout_drain(&V_nd6_timer_ch);
171 }
172 #endif
173
174 struct nd_ifinfo *
175 nd6_ifattach(struct ifnet *ifp)
176 {
177         struct nd_ifinfo *nd;
178
179         nd = (struct nd_ifinfo *)malloc(sizeof(*nd), M_IP6NDP, M_WAITOK|M_ZERO);
180         nd->initialized = 1;
181
182         nd->chlim = IPV6_DEFHLIM;
183         nd->basereachable = REACHABLE_TIME;
184         nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
185         nd->retrans = RETRANS_TIMER;
186
187         nd->flags = ND6_IFF_PERFORMNUD;
188
189         /* A loopback interface always has ND6_IFF_AUTO_LINKLOCAL.
190          * XXXHRS: Clear ND6_IFF_AUTO_LINKLOCAL on an IFT_BRIDGE interface by
191          * default regardless of the V_ip6_auto_linklocal configuration to
192          * give a reasonable default behavior.
193          */
194         if ((V_ip6_auto_linklocal && ifp->if_type != IFT_BRIDGE) ||
195             (ifp->if_flags & IFF_LOOPBACK))
196                 nd->flags |= ND6_IFF_AUTO_LINKLOCAL;
197         /*
198          * A loopback interface does not need to accept RTADV.
199          * XXXHRS: Clear ND6_IFF_ACCEPT_RTADV on an IFT_BRIDGE interface by
200          * default regardless of the V_ip6_accept_rtadv configuration to
201          * prevent the interface from accepting RA messages arrived
202          * on one of the member interfaces with ND6_IFF_ACCEPT_RTADV.
203          */
204         if (V_ip6_accept_rtadv &&
205             !(ifp->if_flags & IFF_LOOPBACK) &&
206             (ifp->if_type != IFT_BRIDGE))
207                         nd->flags |= ND6_IFF_ACCEPT_RTADV;
208         if (V_ip6_no_radr && !(ifp->if_flags & IFF_LOOPBACK))
209                 nd->flags |= ND6_IFF_NO_RADR;
210
211         /* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
212         nd6_setmtu0(ifp, nd);
213
214         return nd;
215 }
216
217 void
218 nd6_ifdetach(struct nd_ifinfo *nd)
219 {
220
221         free(nd, M_IP6NDP);
222 }
223
224 /*
225  * Reset ND level link MTU. This function is called when the physical MTU
226  * changes, which means we might have to adjust the ND level MTU.
227  */
228 void
229 nd6_setmtu(struct ifnet *ifp)
230 {
231
232         nd6_setmtu0(ifp, ND_IFINFO(ifp));
233 }
234
235 /* XXX todo: do not maintain copy of ifp->if_mtu in ndi->maxmtu */
236 void
237 nd6_setmtu0(struct ifnet *ifp, struct nd_ifinfo *ndi)
238 {
239         u_int32_t omaxmtu;
240
241         omaxmtu = ndi->maxmtu;
242
243         switch (ifp->if_type) {
244         case IFT_ARCNET:
245                 ndi->maxmtu = MIN(ARC_PHDS_MAXMTU, ifp->if_mtu); /* RFC2497 */
246                 break;
247         case IFT_FDDI:
248                 ndi->maxmtu = MIN(FDDIIPMTU, ifp->if_mtu); /* RFC2467 */
249                 break;
250         case IFT_ISO88025:
251                  ndi->maxmtu = MIN(ISO88025_MAX_MTU, ifp->if_mtu);
252                  break;
253         default:
254                 ndi->maxmtu = ifp->if_mtu;
255                 break;
256         }
257
258         /*
259          * Decreasing the interface MTU under IPV6 minimum MTU may cause
260          * undesirable situation.  We thus notify the operator of the change
261          * explicitly.  The check for omaxmtu is necessary to restrict the
262          * log to the case of changing the MTU, not initializing it.
263          */
264         if (omaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
265                 log(LOG_NOTICE, "nd6_setmtu0: "
266                     "new link MTU on %s (%lu) is too small for IPv6\n",
267                     if_name(ifp), (unsigned long)ndi->maxmtu);
268         }
269
270         if (ndi->maxmtu > V_in6_maxmtu)
271                 in6_setmaxmtu(); /* check all interfaces just in case */
272
273 }
274
275 void
276 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
277 {
278
279         bzero(ndopts, sizeof(*ndopts));
280         ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
281         ndopts->nd_opts_last
282                 = (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
283
284         if (icmp6len == 0) {
285                 ndopts->nd_opts_done = 1;
286                 ndopts->nd_opts_search = NULL;
287         }
288 }
289
290 /*
291  * Take one ND option.
292  */
293 struct nd_opt_hdr *
294 nd6_option(union nd_opts *ndopts)
295 {
296         struct nd_opt_hdr *nd_opt;
297         int olen;
298
299         KASSERT(ndopts != NULL, ("%s: ndopts == NULL", __func__));
300         KASSERT(ndopts->nd_opts_last != NULL, ("%s: uninitialized ndopts",
301             __func__));
302         if (ndopts->nd_opts_search == NULL)
303                 return NULL;
304         if (ndopts->nd_opts_done)
305                 return NULL;
306
307         nd_opt = ndopts->nd_opts_search;
308
309         /* make sure nd_opt_len is inside the buffer */
310         if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
311                 bzero(ndopts, sizeof(*ndopts));
312                 return NULL;
313         }
314
315         olen = nd_opt->nd_opt_len << 3;
316         if (olen == 0) {
317                 /*
318                  * Message validation requires that all included
319                  * options have a length that is greater than zero.
320                  */
321                 bzero(ndopts, sizeof(*ndopts));
322                 return NULL;
323         }
324
325         ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
326         if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
327                 /* option overruns the end of buffer, invalid */
328                 bzero(ndopts, sizeof(*ndopts));
329                 return NULL;
330         } else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
331                 /* reached the end of options chain */
332                 ndopts->nd_opts_done = 1;
333                 ndopts->nd_opts_search = NULL;
334         }
335         return nd_opt;
336 }
337
338 /*
339  * Parse multiple ND options.
340  * This function is much easier to use, for ND routines that do not need
341  * multiple options of the same type.
342  */
343 int
344 nd6_options(union nd_opts *ndopts)
345 {
346         struct nd_opt_hdr *nd_opt;
347         int i = 0;
348
349         KASSERT(ndopts != NULL, ("%s: ndopts == NULL", __func__));
350         KASSERT(ndopts->nd_opts_last != NULL, ("%s: uninitialized ndopts",
351             __func__));
352         if (ndopts->nd_opts_search == NULL)
353                 return 0;
354
355         while (1) {
356                 nd_opt = nd6_option(ndopts);
357                 if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
358                         /*
359                          * Message validation requires that all included
360                          * options have a length that is greater than zero.
361                          */
362                         ICMP6STAT_INC(icp6s_nd_badopt);
363                         bzero(ndopts, sizeof(*ndopts));
364                         return -1;
365                 }
366
367                 if (nd_opt == NULL)
368                         goto skip1;
369
370                 switch (nd_opt->nd_opt_type) {
371                 case ND_OPT_SOURCE_LINKADDR:
372                 case ND_OPT_TARGET_LINKADDR:
373                 case ND_OPT_MTU:
374                 case ND_OPT_REDIRECTED_HEADER:
375                 case ND_OPT_NONCE:
376                         if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
377                                 nd6log((LOG_INFO,
378                                     "duplicated ND6 option found (type=%d)\n",
379                                     nd_opt->nd_opt_type));
380                                 /* XXX bark? */
381                         } else {
382                                 ndopts->nd_opt_array[nd_opt->nd_opt_type]
383                                         = nd_opt;
384                         }
385                         break;
386                 case ND_OPT_PREFIX_INFORMATION:
387                         if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
388                                 ndopts->nd_opt_array[nd_opt->nd_opt_type]
389                                         = nd_opt;
390                         }
391                         ndopts->nd_opts_pi_end =
392                                 (struct nd_opt_prefix_info *)nd_opt;
393                         break;
394                 /* What about ND_OPT_ROUTE_INFO? RFC 4191 */
395                 case ND_OPT_RDNSS:      /* RFC 6106 */
396                 case ND_OPT_DNSSL:      /* RFC 6106 */
397                         /*
398                          * Silently ignore options we know and do not care about
399                          * in the kernel.
400                          */
401                         break;
402                 default:
403                         /*
404                          * Unknown options must be silently ignored,
405                          * to accomodate future extension to the protocol.
406                          */
407                         nd6log((LOG_DEBUG,
408                             "nd6_options: unsupported option %d - "
409                             "option ignored\n", nd_opt->nd_opt_type));
410                 }
411
412 skip1:
413                 i++;
414                 if (i > V_nd6_maxndopt) {
415                         ICMP6STAT_INC(icp6s_nd_toomanyopt);
416                         nd6log((LOG_INFO, "too many loop in nd opt\n"));
417                         break;
418                 }
419
420                 if (ndopts->nd_opts_done)
421                         break;
422         }
423
424         return 0;
425 }
426
427 /*
428  * ND6 timer routine to handle ND6 entries
429  */
430 void
431 nd6_llinfo_settimer_locked(struct llentry *ln, long tick)
432 {
433         int canceled;
434
435         LLE_WLOCK_ASSERT(ln);
436
437         if (tick < 0) {
438                 ln->la_expire = 0;
439                 ln->ln_ntick = 0;
440                 canceled = callout_stop(&ln->ln_timer_ch);
441         } else {
442                 ln->la_expire = time_uptime + tick / hz;
443                 LLE_ADDREF(ln);
444                 if (tick > INT_MAX) {
445                         ln->ln_ntick = tick - INT_MAX;
446                         canceled = callout_reset(&ln->ln_timer_ch, INT_MAX,
447                             nd6_llinfo_timer, ln);
448                 } else {
449                         ln->ln_ntick = 0;
450                         canceled = callout_reset(&ln->ln_timer_ch, tick,
451                             nd6_llinfo_timer, ln);
452                 }
453         }
454         if (canceled)
455                 LLE_REMREF(ln);
456 }
457
458 void
459 nd6_llinfo_settimer(struct llentry *ln, long tick)
460 {
461
462         LLE_WLOCK(ln);
463         nd6_llinfo_settimer_locked(ln, tick);
464         LLE_WUNLOCK(ln);
465 }
466
467 static void
468 nd6_llinfo_timer(void *arg)
469 {
470         struct llentry *ln;
471         struct in6_addr *dst;
472         struct ifnet *ifp;
473         struct nd_ifinfo *ndi = NULL;
474
475         KASSERT(arg != NULL, ("%s: arg NULL", __func__));
476         ln = (struct llentry *)arg;
477         LLE_WLOCK(ln);
478         if (callout_pending(&ln->la_timer)) {
479                 /*
480                  * Here we are a bit odd here in the treatment of 
481                  * active/pending. If the pending bit is set, it got
482                  * rescheduled before I ran. The active
483                  * bit we ignore, since if it was stopped
484                  * in ll_tablefree() and was currently running
485                  * it would have return 0 so the code would
486                  * not have deleted it since the callout could
487                  * not be stopped so we want to go through
488                  * with the delete here now. If the callout
489                  * was restarted, the pending bit will be back on and
490                  * we just want to bail since the callout_reset would
491                  * return 1 and our reference would have been removed
492                  * by nd6_llinfo_settimer_locked above since canceled
493                  * would have been 1.
494                  */
495                 LLE_WUNLOCK(ln);
496                 return;
497         }
498         ifp = ln->lle_tbl->llt_ifp;
499         CURVNET_SET(ifp->if_vnet);
500
501         if (ln->ln_ntick > 0) {
502                 if (ln->ln_ntick > INT_MAX) {
503                         ln->ln_ntick -= INT_MAX;
504                         nd6_llinfo_settimer_locked(ln, INT_MAX);
505                 } else {
506                         ln->ln_ntick = 0;
507                         nd6_llinfo_settimer_locked(ln, ln->ln_ntick);
508                 }
509                 goto done;
510         }
511
512         ndi = ND_IFINFO(ifp);
513         dst = &L3_ADDR_SIN6(ln)->sin6_addr;
514         if (ln->la_flags & LLE_STATIC) {
515                 goto done;
516         }
517
518         if (ln->la_flags & LLE_DELETED) {
519                 (void)nd6_free(ln, 0);
520                 ln = NULL;
521                 goto done;
522         }
523
524         switch (ln->ln_state) {
525         case ND6_LLINFO_INCOMPLETE:
526                 if (ln->la_asked < V_nd6_mmaxtries) {
527                         ln->la_asked++;
528                         nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
529                         LLE_WUNLOCK(ln);
530                         nd6_ns_output(ifp, NULL, dst, ln, NULL);
531                         LLE_WLOCK(ln);
532                 } else {
533                         struct mbuf *m = ln->la_hold;
534                         if (m) {
535                                 struct mbuf *m0;
536
537                                 /*
538                                  * assuming every packet in la_hold has the
539                                  * same IP header.  Send error after unlock.
540                                  */
541                                 m0 = m->m_nextpkt;
542                                 m->m_nextpkt = NULL;
543                                 ln->la_hold = m0;
544                                 clear_llinfo_pqueue(ln);
545                         }
546                         EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_TIMEDOUT);
547                         (void)nd6_free(ln, 0);
548                         ln = NULL;
549                         if (m != NULL)
550                                 icmp6_error2(m, ICMP6_DST_UNREACH,
551                                     ICMP6_DST_UNREACH_ADDR, 0, ifp);
552                 }
553                 break;
554         case ND6_LLINFO_REACHABLE:
555                 if (!ND6_LLINFO_PERMANENT(ln)) {
556                         ln->ln_state = ND6_LLINFO_STALE;
557                         nd6_llinfo_settimer_locked(ln, (long)V_nd6_gctimer * hz);
558                 }
559                 break;
560
561         case ND6_LLINFO_STALE:
562                 /* Garbage Collection(RFC 2461 5.3) */
563                 if (!ND6_LLINFO_PERMANENT(ln)) {
564                         EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_EXPIRED);
565                         (void)nd6_free(ln, 1);
566                         ln = NULL;
567                 }
568                 break;
569
570         case ND6_LLINFO_DELAY:
571                 if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
572                         /* We need NUD */
573                         ln->la_asked = 1;
574                         ln->ln_state = ND6_LLINFO_PROBE;
575                         nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
576                         LLE_WUNLOCK(ln);
577                         nd6_ns_output(ifp, dst, dst, ln, NULL);
578                         LLE_WLOCK(ln);
579                 } else {
580                         ln->ln_state = ND6_LLINFO_STALE; /* XXX */
581                         nd6_llinfo_settimer_locked(ln, (long)V_nd6_gctimer * hz);
582                 }
583                 break;
584         case ND6_LLINFO_PROBE:
585                 if (ln->la_asked < V_nd6_umaxtries) {
586                         ln->la_asked++;
587                         nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
588                         LLE_WUNLOCK(ln);
589                         nd6_ns_output(ifp, dst, dst, ln, NULL);
590                         LLE_WLOCK(ln);
591                 } else {
592                         EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_EXPIRED);
593                         (void)nd6_free(ln, 0);
594                         ln = NULL;
595                 }
596                 break;
597         default:
598                 panic("%s: paths in a dark night can be confusing: %d",
599                     __func__, ln->ln_state);
600         }
601 done:
602         if (ln != NULL)
603                 LLE_FREE_LOCKED(ln);
604         CURVNET_RESTORE();
605 }
606
607
608 /*
609  * ND6 timer routine to expire default route list and prefix list
610  */
611 void
612 nd6_timer(void *arg)
613 {
614         CURVNET_SET((struct vnet *) arg);
615         struct nd_defrouter *dr, *ndr;
616         struct nd_prefix *pr, *npr;
617         struct in6_ifaddr *ia6, *nia6;
618
619         callout_reset(&V_nd6_timer_ch, V_nd6_prune * hz,
620             nd6_timer, curvnet);
621
622         /* expire default router list */
623         TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr) {
624                 if (dr->expire && dr->expire < time_uptime)
625                         defrtrlist_del(dr);
626         }
627
628         /*
629          * expire interface addresses.
630          * in the past the loop was inside prefix expiry processing.
631          * However, from a stricter speci-confrmance standpoint, we should
632          * rather separate address lifetimes and prefix lifetimes.
633          *
634          * XXXRW: in6_ifaddrhead locking.
635          */
636   addrloop:
637         TAILQ_FOREACH_SAFE(ia6, &V_in6_ifaddrhead, ia_link, nia6) {
638                 /* check address lifetime */
639                 if (IFA6_IS_INVALID(ia6)) {
640                         int regen = 0;
641
642                         /*
643                          * If the expiring address is temporary, try
644                          * regenerating a new one.  This would be useful when
645                          * we suspended a laptop PC, then turned it on after a
646                          * period that could invalidate all temporary
647                          * addresses.  Although we may have to restart the
648                          * loop (see below), it must be after purging the
649                          * address.  Otherwise, we'd see an infinite loop of
650                          * regeneration.
651                          */
652                         if (V_ip6_use_tempaddr &&
653                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
654                                 if (regen_tmpaddr(ia6) == 0)
655                                         regen = 1;
656                         }
657
658                         in6_purgeaddr(&ia6->ia_ifa);
659
660                         if (regen)
661                                 goto addrloop; /* XXX: see below */
662                 } else if (IFA6_IS_DEPRECATED(ia6)) {
663                         int oldflags = ia6->ia6_flags;
664
665                         ia6->ia6_flags |= IN6_IFF_DEPRECATED;
666
667                         /*
668                          * If a temporary address has just become deprecated,
669                          * regenerate a new one if possible.
670                          */
671                         if (V_ip6_use_tempaddr &&
672                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
673                             (oldflags & IN6_IFF_DEPRECATED) == 0) {
674
675                                 if (regen_tmpaddr(ia6) == 0) {
676                                         /*
677                                          * A new temporary address is
678                                          * generated.
679                                          * XXX: this means the address chain
680                                          * has changed while we are still in
681                                          * the loop.  Although the change
682                                          * would not cause disaster (because
683                                          * it's not a deletion, but an
684                                          * addition,) we'd rather restart the
685                                          * loop just for safety.  Or does this
686                                          * significantly reduce performance??
687                                          */
688                                         goto addrloop;
689                                 }
690                         }
691                 } else {
692                         /*
693                          * A new RA might have made a deprecated address
694                          * preferred.
695                          */
696                         ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
697                 }
698         }
699
700         /* expire prefix list */
701         LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
702                 /*
703                  * check prefix lifetime.
704                  * since pltime is just for autoconf, pltime processing for
705                  * prefix is not necessary.
706                  */
707                 if (pr->ndpr_vltime != ND6_INFINITE_LIFETIME &&
708                     time_uptime - pr->ndpr_lastupdate > pr->ndpr_vltime) {
709
710                         /*
711                          * address expiration and prefix expiration are
712                          * separate.  NEVER perform in6_purgeaddr here.
713                          */
714                         prelist_remove(pr);
715                 }
716         }
717         CURVNET_RESTORE();
718 }
719
720 /*
721  * ia6 - deprecated/invalidated temporary address
722  */
723 static int
724 regen_tmpaddr(struct in6_ifaddr *ia6)
725 {
726         struct ifaddr *ifa;
727         struct ifnet *ifp;
728         struct in6_ifaddr *public_ifa6 = NULL;
729
730         ifp = ia6->ia_ifa.ifa_ifp;
731         IF_ADDR_RLOCK(ifp);
732         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
733                 struct in6_ifaddr *it6;
734
735                 if (ifa->ifa_addr->sa_family != AF_INET6)
736                         continue;
737
738                 it6 = (struct in6_ifaddr *)ifa;
739
740                 /* ignore no autoconf addresses. */
741                 if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
742                         continue;
743
744                 /* ignore autoconf addresses with different prefixes. */
745                 if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
746                         continue;
747
748                 /*
749                  * Now we are looking at an autoconf address with the same
750                  * prefix as ours.  If the address is temporary and is still
751                  * preferred, do not create another one.  It would be rare, but
752                  * could happen, for example, when we resume a laptop PC after
753                  * a long period.
754                  */
755                 if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
756                     !IFA6_IS_DEPRECATED(it6)) {
757                         public_ifa6 = NULL;
758                         break;
759                 }
760
761                 /*
762                  * This is a public autoconf address that has the same prefix
763                  * as ours.  If it is preferred, keep it.  We can't break the
764                  * loop here, because there may be a still-preferred temporary
765                  * address with the prefix.
766                  */
767                 if (!IFA6_IS_DEPRECATED(it6))
768                         public_ifa6 = it6;
769         }
770         if (public_ifa6 != NULL)
771                 ifa_ref(&public_ifa6->ia_ifa);
772         IF_ADDR_RUNLOCK(ifp);
773
774         if (public_ifa6 != NULL) {
775                 int e;
776
777                 if ((e = in6_tmpifadd(public_ifa6, 0, 0)) != 0) {
778                         ifa_free(&public_ifa6->ia_ifa);
779                         log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
780                             " tmp addr,errno=%d\n", e);
781                         return (-1);
782                 }
783                 ifa_free(&public_ifa6->ia_ifa);
784                 return (0);
785         }
786
787         return (-1);
788 }
789
790 /*
791  * Nuke neighbor cache/prefix/default router management table, right before
792  * ifp goes away.
793  */
794 void
795 nd6_purge(struct ifnet *ifp)
796 {
797         struct nd_defrouter *dr, *ndr;
798         struct nd_prefix *pr, *npr;
799
800         /*
801          * Nuke default router list entries toward ifp.
802          * We defer removal of default router list entries that is installed
803          * in the routing table, in order to keep additional side effects as
804          * small as possible.
805          */
806         TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr) {
807                 if (dr->installed)
808                         continue;
809
810                 if (dr->ifp == ifp)
811                         defrtrlist_del(dr);
812         }
813
814         TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr) {
815                 if (!dr->installed)
816                         continue;
817
818                 if (dr->ifp == ifp)
819                         defrtrlist_del(dr);
820         }
821
822         /* Nuke prefix list entries toward ifp */
823         LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
824                 if (pr->ndpr_ifp == ifp) {
825                         /*
826                          * Because if_detach() does *not* release prefixes
827                          * while purging addresses the reference count will
828                          * still be above zero. We therefore reset it to
829                          * make sure that the prefix really gets purged.
830                          */
831                         pr->ndpr_refcnt = 0;
832
833                         /*
834                          * Previously, pr->ndpr_addr is removed as well,
835                          * but I strongly believe we don't have to do it.
836                          * nd6_purge() is only called from in6_ifdetach(),
837                          * which removes all the associated interface addresses
838                          * by itself.
839                          * (jinmei@kame.net 20010129)
840                          */
841                         prelist_remove(pr);
842                 }
843         }
844
845         /* cancel default outgoing interface setting */
846         if (V_nd6_defifindex == ifp->if_index)
847                 nd6_setdefaultiface(0);
848
849         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
850                 /* Refresh default router list. */
851                 defrouter_select();
852         }
853
854         /* XXXXX
855          * We do not nuke the neighbor cache entries here any more
856          * because the neighbor cache is kept in if_afdata[AF_INET6].
857          * nd6_purge() is invoked by in6_ifdetach() which is called
858          * from if_detach() where everything gets purged. So let
859          * in6_domifdetach() do the actual L2 table purging work.
860          */
861 }
862
863 /* 
864  * the caller acquires and releases the lock on the lltbls
865  * Returns the llentry locked
866  */
867 struct llentry *
868 nd6_lookup(struct in6_addr *addr6, int flags, struct ifnet *ifp)
869 {
870         struct sockaddr_in6 sin6;
871         struct llentry *ln;
872         int llflags;
873         
874         bzero(&sin6, sizeof(sin6));
875         sin6.sin6_len = sizeof(struct sockaddr_in6);
876         sin6.sin6_family = AF_INET6;
877         sin6.sin6_addr = *addr6;
878
879         IF_AFDATA_LOCK_ASSERT(ifp);
880
881         llflags = 0;
882         if (flags & ND6_CREATE)
883             llflags |= LLE_CREATE;
884         if (flags & ND6_EXCLUSIVE)
885             llflags |= LLE_EXCLUSIVE;   
886         
887         ln = lla_lookup(LLTABLE6(ifp), llflags, (struct sockaddr *)&sin6);
888         if ((ln != NULL) && (llflags & LLE_CREATE))
889                 ln->ln_state = ND6_LLINFO_NOSTATE;
890         
891         return (ln);
892 }
893
894 /*
895  * Test whether a given IPv6 address is a neighbor or not, ignoring
896  * the actual neighbor cache.  The neighbor cache is ignored in order
897  * to not reenter the routing code from within itself.
898  */
899 static int
900 nd6_is_new_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
901 {
902         struct nd_prefix *pr;
903         struct ifaddr *dstaddr;
904
905         /*
906          * A link-local address is always a neighbor.
907          * XXX: a link does not necessarily specify a single interface.
908          */
909         if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
910                 struct sockaddr_in6 sin6_copy;
911                 u_int32_t zone;
912
913                 /*
914                  * We need sin6_copy since sa6_recoverscope() may modify the
915                  * content (XXX).
916                  */
917                 sin6_copy = *addr;
918                 if (sa6_recoverscope(&sin6_copy))
919                         return (0); /* XXX: should be impossible */
920                 if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
921                         return (0);
922                 if (sin6_copy.sin6_scope_id == zone)
923                         return (1);
924                 else
925                         return (0);
926         }
927
928         /*
929          * If the address matches one of our addresses,
930          * it should be a neighbor.
931          * If the address matches one of our on-link prefixes, it should be a
932          * neighbor.
933          */
934         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
935                 if (pr->ndpr_ifp != ifp)
936                         continue;
937
938                 if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
939                         struct rtentry *rt;
940
941                         /* Always use the default FIB here. */
942                         rt = in6_rtalloc1((struct sockaddr *)&pr->ndpr_prefix,
943                             0, 0, RT_DEFAULT_FIB);
944                         if (rt == NULL)
945                                 continue;
946                         /*
947                          * This is the case where multiple interfaces
948                          * have the same prefix, but only one is installed 
949                          * into the routing table and that prefix entry
950                          * is not the one being examined here. In the case
951                          * where RADIX_MPATH is enabled, multiple route
952                          * entries (of the same rt_key value) will be 
953                          * installed because the interface addresses all
954                          * differ.
955                          */
956                         if (!IN6_ARE_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
957                                &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr)) {
958                                 RTFREE_LOCKED(rt);
959                                 continue;
960                         }
961                         RTFREE_LOCKED(rt);
962                 }
963
964                 if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
965                     &addr->sin6_addr, &pr->ndpr_mask))
966                         return (1);
967         }
968
969         /*
970          * If the address is assigned on the node of the other side of
971          * a p2p interface, the address should be a neighbor.
972          */
973         dstaddr = ifa_ifwithdstaddr((struct sockaddr *)addr, RT_ALL_FIBS);
974         if (dstaddr != NULL) {
975                 if (dstaddr->ifa_ifp == ifp) {
976                         ifa_free(dstaddr);
977                         return (1);
978                 }
979                 ifa_free(dstaddr);
980         }
981
982         /*
983          * If the default router list is empty, all addresses are regarded
984          * as on-link, and thus, as a neighbor.
985          */
986         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV &&
987             TAILQ_EMPTY(&V_nd_defrouter) &&
988             V_nd6_defifindex == ifp->if_index) {
989                 return (1);
990         }
991
992         return (0);
993 }
994
995
996 /*
997  * Detect if a given IPv6 address identifies a neighbor on a given link.
998  * XXX: should take care of the destination of a p2p link?
999  */
1000 int
1001 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
1002 {
1003         struct llentry *lle;
1004         int rc = 0;
1005
1006         IF_AFDATA_UNLOCK_ASSERT(ifp);
1007         if (nd6_is_new_addr_neighbor(addr, ifp))
1008                 return (1);
1009
1010         /*
1011          * Even if the address matches none of our addresses, it might be
1012          * in the neighbor cache.
1013          */
1014         IF_AFDATA_RLOCK(ifp);
1015         if ((lle = nd6_lookup(&addr->sin6_addr, 0, ifp)) != NULL) {
1016                 LLE_RUNLOCK(lle);
1017                 rc = 1;
1018         }
1019         IF_AFDATA_RUNLOCK(ifp);
1020         return (rc);
1021 }
1022
1023 /*
1024  * Free an nd6 llinfo entry.
1025  * Since the function would cause significant changes in the kernel, DO NOT
1026  * make it global, unless you have a strong reason for the change, and are sure
1027  * that the change is safe.
1028  */
1029 static struct llentry *
1030 nd6_free(struct llentry *ln, int gc)
1031 {
1032         struct llentry *next;
1033         struct nd_defrouter *dr;
1034         struct ifnet *ifp;
1035
1036         LLE_WLOCK_ASSERT(ln);
1037
1038         /*
1039          * we used to have pfctlinput(PRC_HOSTDEAD) here.
1040          * even though it is not harmful, it was not really necessary.
1041          */
1042
1043         /* cancel timer */
1044         nd6_llinfo_settimer_locked(ln, -1);
1045
1046         ifp = ln->lle_tbl->llt_ifp;
1047
1048         if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1049                 dr = defrouter_lookup(&L3_ADDR_SIN6(ln)->sin6_addr, ifp);
1050
1051                 if (dr != NULL && dr->expire &&
1052                     ln->ln_state == ND6_LLINFO_STALE && gc) {
1053                         /*
1054                          * If the reason for the deletion is just garbage
1055                          * collection, and the neighbor is an active default
1056                          * router, do not delete it.  Instead, reset the GC
1057                          * timer using the router's lifetime.
1058                          * Simply deleting the entry would affect default
1059                          * router selection, which is not necessarily a good
1060                          * thing, especially when we're using router preference
1061                          * values.
1062                          * XXX: the check for ln_state would be redundant,
1063                          *      but we intentionally keep it just in case.
1064                          */
1065                         if (dr->expire > time_uptime)
1066                                 nd6_llinfo_settimer_locked(ln,
1067                                     (dr->expire - time_uptime) * hz);
1068                         else
1069                                 nd6_llinfo_settimer_locked(ln,
1070                                     (long)V_nd6_gctimer * hz);
1071
1072                         next = LIST_NEXT(ln, lle_next);
1073                         LLE_REMREF(ln);
1074                         LLE_WUNLOCK(ln);
1075                         return (next);
1076                 }
1077
1078                 if (dr) {
1079                         /*
1080                          * Unreachablity of a router might affect the default
1081                          * router selection and on-link detection of advertised
1082                          * prefixes.
1083                          */
1084
1085                         /*
1086                          * Temporarily fake the state to choose a new default
1087                          * router and to perform on-link determination of
1088                          * prefixes correctly.
1089                          * Below the state will be set correctly,
1090                          * or the entry itself will be deleted.
1091                          */
1092                         ln->ln_state = ND6_LLINFO_INCOMPLETE;
1093                 }
1094
1095                 if (ln->ln_router || dr) {
1096
1097                         /*
1098                          * We need to unlock to avoid a LOR with rt6_flush() with the
1099                          * rnh and for the calls to pfxlist_onlink_check() and
1100                          * defrouter_select() in the block further down for calls
1101                          * into nd6_lookup().  We still hold a ref.
1102                          */
1103                         LLE_WUNLOCK(ln);
1104
1105                         /*
1106                          * rt6_flush must be called whether or not the neighbor
1107                          * is in the Default Router List.
1108                          * See a corresponding comment in nd6_na_input().
1109                          */
1110                         rt6_flush(&L3_ADDR_SIN6(ln)->sin6_addr, ifp);
1111                 }
1112
1113                 if (dr) {
1114                         /*
1115                          * Since defrouter_select() does not affect the
1116                          * on-link determination and MIP6 needs the check
1117                          * before the default router selection, we perform
1118                          * the check now.
1119                          */
1120                         pfxlist_onlink_check();
1121
1122                         /*
1123                          * Refresh default router list.
1124                          */
1125                         defrouter_select();
1126                 }
1127
1128                 if (ln->ln_router || dr)
1129                         LLE_WLOCK(ln);
1130         }
1131
1132         /*
1133          * Before deleting the entry, remember the next entry as the
1134          * return value.  We need this because pfxlist_onlink_check() above
1135          * might have freed other entries (particularly the old next entry) as
1136          * a side effect (XXX).
1137          */
1138         next = LIST_NEXT(ln, lle_next);
1139
1140         /*
1141          * Save to unlock. We still hold an extra reference and will not
1142          * free(9) in llentry_free() if someone else holds one as well.
1143          */
1144         LLE_WUNLOCK(ln);
1145         IF_AFDATA_LOCK(ifp);
1146         LLE_WLOCK(ln);
1147
1148         /* Guard against race with other llentry_free(). */
1149         if (ln->la_flags & LLE_LINKED) {
1150                 LLE_REMREF(ln);
1151                 llentry_free(ln);
1152         } else
1153                 LLE_FREE_LOCKED(ln);
1154
1155         IF_AFDATA_UNLOCK(ifp);
1156
1157         return (next);
1158 }
1159
1160 /*
1161  * Upper-layer reachability hint for Neighbor Unreachability Detection.
1162  *
1163  * XXX cost-effective methods?
1164  */
1165 void
1166 nd6_nud_hint(struct rtentry *rt, struct in6_addr *dst6, int force)
1167 {
1168         struct llentry *ln;
1169         struct ifnet *ifp;
1170
1171         if ((dst6 == NULL) || (rt == NULL))
1172                 return;
1173
1174         ifp = rt->rt_ifp;
1175         IF_AFDATA_RLOCK(ifp);
1176         ln = nd6_lookup(dst6, ND6_EXCLUSIVE, NULL);
1177         IF_AFDATA_RUNLOCK(ifp);
1178         if (ln == NULL)
1179                 return;
1180
1181         if (ln->ln_state < ND6_LLINFO_REACHABLE)
1182                 goto done;
1183
1184         /*
1185          * if we get upper-layer reachability confirmation many times,
1186          * it is possible we have false information.
1187          */
1188         if (!force) {
1189                 ln->ln_byhint++;
1190                 if (ln->ln_byhint > V_nd6_maxnudhint) {
1191                         goto done;
1192                 }
1193         }
1194
1195         ln->ln_state = ND6_LLINFO_REACHABLE;
1196         if (!ND6_LLINFO_PERMANENT(ln)) {
1197                 nd6_llinfo_settimer_locked(ln,
1198                     (long)ND_IFINFO(rt->rt_ifp)->reachable * hz);
1199         }
1200 done:
1201         LLE_WUNLOCK(ln);
1202 }
1203
1204
1205 /*
1206  * Rejuvenate this function for routing operations related
1207  * processing.
1208  */
1209 void
1210 nd6_rtrequest(int req, struct rtentry *rt, struct rt_addrinfo *info)
1211 {
1212         struct sockaddr_in6 *gateway;
1213         struct nd_defrouter *dr;
1214         struct ifnet *ifp;
1215
1216         gateway = (struct sockaddr_in6 *)rt->rt_gateway;
1217         ifp = rt->rt_ifp;
1218
1219         switch (req) {
1220         case RTM_ADD:
1221                 break;
1222
1223         case RTM_DELETE:
1224                 if (!ifp)
1225                         return;
1226                 /*
1227                  * Only indirect routes are interesting.
1228                  */
1229                 if ((rt->rt_flags & RTF_GATEWAY) == 0)
1230                         return;
1231                 /*
1232                  * check for default route
1233                  */
1234                 if (IN6_ARE_ADDR_EQUAL(&in6addr_any, 
1235                                        &SIN6(rt_key(rt))->sin6_addr)) {
1236
1237                         dr = defrouter_lookup(&gateway->sin6_addr, ifp);
1238                         if (dr != NULL)
1239                                 dr->installed = 0;
1240                 }
1241                 break;
1242         }
1243 }
1244
1245
1246 int
1247 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1248 {
1249         struct in6_drlist *drl = (struct in6_drlist *)data;
1250         struct in6_oprlist *oprl = (struct in6_oprlist *)data;
1251         struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1252         struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1253         struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1254         struct nd_defrouter *dr;
1255         struct nd_prefix *pr;
1256         int i = 0, error = 0;
1257
1258         if (ifp->if_afdata[AF_INET6] == NULL)
1259                 return (EPFNOSUPPORT);
1260         switch (cmd) {
1261         case SIOCGDRLST_IN6:
1262                 /*
1263                  * obsolete API, use sysctl under net.inet6.icmp6
1264                  */
1265                 bzero(drl, sizeof(*drl));
1266                 TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry) {
1267                         if (i >= DRLSTSIZ)
1268                                 break;
1269                         drl->defrouter[i].rtaddr = dr->rtaddr;
1270                         in6_clearscope(&drl->defrouter[i].rtaddr);
1271
1272                         drl->defrouter[i].flags = dr->flags;
1273                         drl->defrouter[i].rtlifetime = dr->rtlifetime;
1274                         drl->defrouter[i].expire = dr->expire +
1275                             (time_second - time_uptime);
1276                         drl->defrouter[i].if_index = dr->ifp->if_index;
1277                         i++;
1278                 }
1279                 break;
1280         case SIOCGPRLST_IN6:
1281                 /*
1282                  * obsolete API, use sysctl under net.inet6.icmp6
1283                  *
1284                  * XXX the structure in6_prlist was changed in backward-
1285                  * incompatible manner.  in6_oprlist is used for SIOCGPRLST_IN6,
1286                  * in6_prlist is used for nd6_sysctl() - fill_prlist().
1287                  */
1288                 /*
1289                  * XXX meaning of fields, especialy "raflags", is very
1290                  * differnet between RA prefix list and RR/static prefix list.
1291                  * how about separating ioctls into two?
1292                  */
1293                 bzero(oprl, sizeof(*oprl));
1294                 LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1295                         struct nd_pfxrouter *pfr;
1296                         int j;
1297
1298                         if (i >= PRLSTSIZ)
1299                                 break;
1300                         oprl->prefix[i].prefix = pr->ndpr_prefix.sin6_addr;
1301                         oprl->prefix[i].raflags = pr->ndpr_raf;
1302                         oprl->prefix[i].prefixlen = pr->ndpr_plen;
1303                         oprl->prefix[i].vltime = pr->ndpr_vltime;
1304                         oprl->prefix[i].pltime = pr->ndpr_pltime;
1305                         oprl->prefix[i].if_index = pr->ndpr_ifp->if_index;
1306                         if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
1307                                 oprl->prefix[i].expire = 0;
1308                         else {
1309                                 time_t maxexpire;
1310
1311                                 /* XXX: we assume time_t is signed. */
1312                                 maxexpire = (-1) &
1313                                     ~((time_t)1 <<
1314                                     ((sizeof(maxexpire) * 8) - 1));
1315                                 if (pr->ndpr_vltime <
1316                                     maxexpire - pr->ndpr_lastupdate) {
1317                                         oprl->prefix[i].expire =
1318                                             pr->ndpr_lastupdate +
1319                                             pr->ndpr_vltime +
1320                                             (time_second - time_uptime);
1321                                 } else
1322                                         oprl->prefix[i].expire = maxexpire;
1323                         }
1324
1325                         j = 0;
1326                         LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
1327                                 if (j < DRLSTSIZ) {
1328 #define RTRADDR oprl->prefix[i].advrtr[j]
1329                                         RTRADDR = pfr->router->rtaddr;
1330                                         in6_clearscope(&RTRADDR);
1331 #undef RTRADDR
1332                                 }
1333                                 j++;
1334                         }
1335                         oprl->prefix[i].advrtrs = j;
1336                         oprl->prefix[i].origin = PR_ORIG_RA;
1337
1338                         i++;
1339                 }
1340
1341                 break;
1342         case OSIOCGIFINFO_IN6:
1343 #define ND      ndi->ndi
1344                 /* XXX: old ndp(8) assumes a positive value for linkmtu. */
1345                 bzero(&ND, sizeof(ND));
1346                 ND.linkmtu = IN6_LINKMTU(ifp);
1347                 ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
1348                 ND.basereachable = ND_IFINFO(ifp)->basereachable;
1349                 ND.reachable = ND_IFINFO(ifp)->reachable;
1350                 ND.retrans = ND_IFINFO(ifp)->retrans;
1351                 ND.flags = ND_IFINFO(ifp)->flags;
1352                 ND.recalctm = ND_IFINFO(ifp)->recalctm;
1353                 ND.chlim = ND_IFINFO(ifp)->chlim;
1354                 break;
1355         case SIOCGIFINFO_IN6:
1356                 ND = *ND_IFINFO(ifp);
1357                 break;
1358         case SIOCSIFINFO_IN6:
1359                 /*
1360                  * used to change host variables from userland.
1361                  * intented for a use on router to reflect RA configurations.
1362                  */
1363                 /* 0 means 'unspecified' */
1364                 if (ND.linkmtu != 0) {
1365                         if (ND.linkmtu < IPV6_MMTU ||
1366                             ND.linkmtu > IN6_LINKMTU(ifp)) {
1367                                 error = EINVAL;
1368                                 break;
1369                         }
1370                         ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
1371                 }
1372
1373                 if (ND.basereachable != 0) {
1374                         int obasereachable = ND_IFINFO(ifp)->basereachable;
1375
1376                         ND_IFINFO(ifp)->basereachable = ND.basereachable;
1377                         if (ND.basereachable != obasereachable)
1378                                 ND_IFINFO(ifp)->reachable =
1379                                     ND_COMPUTE_RTIME(ND.basereachable);
1380                 }
1381                 if (ND.retrans != 0)
1382                         ND_IFINFO(ifp)->retrans = ND.retrans;
1383                 if (ND.chlim != 0)
1384                         ND_IFINFO(ifp)->chlim = ND.chlim;
1385                 /* FALLTHROUGH */
1386         case SIOCSIFINFO_FLAGS:
1387         {
1388                 struct ifaddr *ifa;
1389                 struct in6_ifaddr *ia;
1390
1391                 if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1392                     !(ND.flags & ND6_IFF_IFDISABLED)) {
1393                         /* ifdisabled 1->0 transision */
1394
1395                         /*
1396                          * If the interface is marked as ND6_IFF_IFDISABLED and
1397                          * has an link-local address with IN6_IFF_DUPLICATED,
1398                          * do not clear ND6_IFF_IFDISABLED.
1399                          * See RFC 4862, Section 5.4.5.
1400                          */
1401                         int duplicated_linklocal = 0;
1402
1403                         IF_ADDR_RLOCK(ifp);
1404                         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1405                                 if (ifa->ifa_addr->sa_family != AF_INET6)
1406                                         continue;
1407                                 ia = (struct in6_ifaddr *)ifa;
1408                                 if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
1409                                     IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia))) {
1410                                         duplicated_linklocal = 1;
1411                                         break;
1412                                 }
1413                         }
1414                         IF_ADDR_RUNLOCK(ifp);
1415
1416                         if (duplicated_linklocal) {
1417                                 ND.flags |= ND6_IFF_IFDISABLED;
1418                                 log(LOG_ERR, "Cannot enable an interface"
1419                                     " with a link-local address marked"
1420                                     " duplicate.\n");
1421                         } else {
1422                                 ND_IFINFO(ifp)->flags &= ~ND6_IFF_IFDISABLED;
1423                                 if (ifp->if_flags & IFF_UP)
1424                                         in6_if_up(ifp);
1425                         }
1426                 } else if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1427                             (ND.flags & ND6_IFF_IFDISABLED)) {
1428                         /* ifdisabled 0->1 transision */
1429                         /* Mark all IPv6 address as tentative. */
1430
1431                         ND_IFINFO(ifp)->flags |= ND6_IFF_IFDISABLED;
1432                         IF_ADDR_RLOCK(ifp);
1433                         TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1434                                 if (ifa->ifa_addr->sa_family != AF_INET6)
1435                                         continue;
1436                                 ia = (struct in6_ifaddr *)ifa;
1437                                 ia->ia6_flags |= IN6_IFF_TENTATIVE;
1438                         }
1439                         IF_ADDR_RUNLOCK(ifp);
1440                 }
1441
1442                 if (ND.flags & ND6_IFF_AUTO_LINKLOCAL) {
1443                         if (!(ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL)) {
1444                                 /* auto_linklocal 0->1 transision */
1445
1446                                 /* If no link-local address on ifp, configure */
1447                                 ND_IFINFO(ifp)->flags |= ND6_IFF_AUTO_LINKLOCAL;
1448                                 in6_ifattach(ifp, NULL);
1449                         } else if (!(ND.flags & ND6_IFF_IFDISABLED) &&
1450                             ifp->if_flags & IFF_UP) {
1451                                 /*
1452                                  * When the IF already has
1453                                  * ND6_IFF_AUTO_LINKLOCAL, no link-local
1454                                  * address is assigned, and IFF_UP, try to
1455                                  * assign one.
1456                                  */
1457                                 int haslinklocal = 0;
1458                         
1459                                 IF_ADDR_RLOCK(ifp);
1460                                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1461                                         if (ifa->ifa_addr->sa_family != AF_INET6)
1462                                                 continue;
1463                                         ia = (struct in6_ifaddr *)ifa;
1464                                         if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia))) {
1465                                                 haslinklocal = 1;
1466                                                 break;
1467                                         }
1468                                 }
1469                                 IF_ADDR_RUNLOCK(ifp);
1470                                 if (!haslinklocal)
1471                                         in6_ifattach(ifp, NULL);
1472                         }
1473                 }
1474         }
1475                 ND_IFINFO(ifp)->flags = ND.flags;
1476                 break;
1477 #undef ND
1478         case SIOCSNDFLUSH_IN6:  /* XXX: the ioctl name is confusing... */
1479                 /* sync kernel routing table with the default router list */
1480                 defrouter_reset();
1481                 defrouter_select();
1482                 break;
1483         case SIOCSPFXFLUSH_IN6:
1484         {
1485                 /* flush all the prefix advertised by routers */
1486                 struct nd_prefix *pr, *next;
1487
1488                 LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, next) {
1489                         struct in6_ifaddr *ia, *ia_next;
1490
1491                         if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1492                                 continue; /* XXX */
1493
1494                         /* do we really have to remove addresses as well? */
1495                         /* XXXRW: in6_ifaddrhead locking. */
1496                         TAILQ_FOREACH_SAFE(ia, &V_in6_ifaddrhead, ia_link,
1497                             ia_next) {
1498                                 if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1499                                         continue;
1500
1501                                 if (ia->ia6_ndpr == pr)
1502                                         in6_purgeaddr(&ia->ia_ifa);
1503                         }
1504                         prelist_remove(pr);
1505                 }
1506                 break;
1507         }
1508         case SIOCSRTRFLUSH_IN6:
1509         {
1510                 /* flush all the default routers */
1511                 struct nd_defrouter *dr, *next;
1512
1513                 defrouter_reset();
1514                 TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, next) {
1515                         defrtrlist_del(dr);
1516                 }
1517                 defrouter_select();
1518                 break;
1519         }
1520         case SIOCGNBRINFO_IN6:
1521         {
1522                 struct llentry *ln;
1523                 struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1524
1525                 if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
1526                         return (error);
1527
1528                 IF_AFDATA_RLOCK(ifp);
1529                 ln = nd6_lookup(&nb_addr, 0, ifp);
1530                 IF_AFDATA_RUNLOCK(ifp);
1531
1532                 if (ln == NULL) {
1533                         error = EINVAL;
1534                         break;
1535                 }
1536                 nbi->state = ln->ln_state;
1537                 nbi->asked = ln->la_asked;
1538                 nbi->isrouter = ln->ln_router;
1539                 if (ln->la_expire == 0)
1540                         nbi->expire = 0;
1541                 else
1542                         nbi->expire = ln->la_expire +
1543                             (time_second - time_uptime);
1544                 LLE_RUNLOCK(ln);
1545                 break;
1546         }
1547         case SIOCGDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1548                 ndif->ifindex = V_nd6_defifindex;
1549                 break;
1550         case SIOCSDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1551                 return (nd6_setdefaultiface(ndif->ifindex));
1552         }
1553         return (error);
1554 }
1555
1556 /*
1557  * Create neighbor cache entry and cache link-layer address,
1558  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1559  *
1560  * type - ICMP6 type
1561  * code - type dependent information
1562  *
1563  * XXXXX
1564  *  The caller of this function already acquired the ndp 
1565  *  cache table lock because the cache entry is returned.
1566  */
1567 struct llentry *
1568 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1569     int lladdrlen, int type, int code)
1570 {
1571         struct llentry *ln = NULL;
1572         int is_newentry;
1573         int do_update;
1574         int olladdr;
1575         int llchange;
1576         int flags;
1577         int newstate = 0;
1578         uint16_t router = 0;
1579         struct sockaddr_in6 sin6;
1580         struct mbuf *chain = NULL;
1581         int static_route = 0;
1582
1583         IF_AFDATA_UNLOCK_ASSERT(ifp);
1584
1585         KASSERT(ifp != NULL, ("%s: ifp == NULL", __func__));
1586         KASSERT(from != NULL, ("%s: from == NULL", __func__));
1587
1588         /* nothing must be updated for unspecified address */
1589         if (IN6_IS_ADDR_UNSPECIFIED(from))
1590                 return NULL;
1591
1592         /*
1593          * Validation about ifp->if_addrlen and lladdrlen must be done in
1594          * the caller.
1595          *
1596          * XXX If the link does not have link-layer adderss, what should
1597          * we do? (ifp->if_addrlen == 0)
1598          * Spec says nothing in sections for RA, RS and NA.  There's small
1599          * description on it in NS section (RFC 2461 7.2.3).
1600          */
1601         flags = lladdr ? ND6_EXCLUSIVE : 0;
1602         IF_AFDATA_RLOCK(ifp);
1603         ln = nd6_lookup(from, flags, ifp);
1604         IF_AFDATA_RUNLOCK(ifp);
1605         if (ln == NULL) {
1606                 flags |= ND6_EXCLUSIVE;
1607                 IF_AFDATA_LOCK(ifp);
1608                 ln = nd6_lookup(from, flags | ND6_CREATE, ifp);
1609                 IF_AFDATA_UNLOCK(ifp);
1610                 is_newentry = 1;
1611         } else {
1612                 /* do nothing if static ndp is set */
1613                 if (ln->la_flags & LLE_STATIC) {
1614                         static_route = 1;
1615                         goto done;
1616                 }
1617                 is_newentry = 0;
1618         }
1619         if (ln == NULL)
1620                 return (NULL);
1621
1622         olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
1623         if (olladdr && lladdr) {
1624                 llchange = bcmp(lladdr, &ln->ll_addr,
1625                     ifp->if_addrlen);
1626         } else
1627                 llchange = 0;
1628
1629         /*
1630          * newentry olladdr  lladdr  llchange   (*=record)
1631          *      0       n       n       --      (1)
1632          *      0       y       n       --      (2)
1633          *      0       n       y       --      (3) * STALE
1634          *      0       y       y       n       (4) *
1635          *      0       y       y       y       (5) * STALE
1636          *      1       --      n       --      (6)   NOSTATE(= PASSIVE)
1637          *      1       --      y       --      (7) * STALE
1638          */
1639
1640         if (lladdr) {           /* (3-5) and (7) */
1641                 /*
1642                  * Record source link-layer address
1643                  * XXX is it dependent to ifp->if_type?
1644                  */
1645                 bcopy(lladdr, &ln->ll_addr, ifp->if_addrlen);
1646                 ln->la_flags |= LLE_VALID;
1647                 EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
1648         }
1649
1650         if (!is_newentry) {
1651                 if ((!olladdr && lladdr != NULL) ||     /* (3) */
1652                     (olladdr && lladdr != NULL && llchange)) {  /* (5) */
1653                         do_update = 1;
1654                         newstate = ND6_LLINFO_STALE;
1655                 } else                                  /* (1-2,4) */
1656                         do_update = 0;
1657         } else {
1658                 do_update = 1;
1659                 if (lladdr == NULL)                     /* (6) */
1660                         newstate = ND6_LLINFO_NOSTATE;
1661                 else                                    /* (7) */
1662                         newstate = ND6_LLINFO_STALE;
1663         }
1664
1665         if (do_update) {
1666                 /*
1667                  * Update the state of the neighbor cache.
1668                  */
1669                 ln->ln_state = newstate;
1670
1671                 if (ln->ln_state == ND6_LLINFO_STALE) {
1672                         if (ln->la_hold != NULL)
1673                                 nd6_grab_holdchain(ln, &chain, &sin6);
1674                 } else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1675                         /* probe right away */
1676                         nd6_llinfo_settimer_locked((void *)ln, 0);
1677                 }
1678         }
1679
1680         /*
1681          * ICMP6 type dependent behavior.
1682          *
1683          * NS: clear IsRouter if new entry
1684          * RS: clear IsRouter
1685          * RA: set IsRouter if there's lladdr
1686          * redir: clear IsRouter if new entry
1687          *
1688          * RA case, (1):
1689          * The spec says that we must set IsRouter in the following cases:
1690          * - If lladdr exist, set IsRouter.  This means (1-5).
1691          * - If it is old entry (!newentry), set IsRouter.  This means (7).
1692          * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1693          * A quetion arises for (1) case.  (1) case has no lladdr in the
1694          * neighbor cache, this is similar to (6).
1695          * This case is rare but we figured that we MUST NOT set IsRouter.
1696          *
1697          * newentry olladdr  lladdr  llchange       NS  RS  RA  redir
1698          *                                                      D R
1699          *      0       n       n       --      (1)     c   ?     s
1700          *      0       y       n       --      (2)     c   s     s
1701          *      0       n       y       --      (3)     c   s     s
1702          *      0       y       y       n       (4)     c   s     s
1703          *      0       y       y       y       (5)     c   s     s
1704          *      1       --      n       --      (6) c   c       c s
1705          *      1       --      y       --      (7) c   c   s   c s
1706          *
1707          *                                      (c=clear s=set)
1708          */
1709         switch (type & 0xff) {
1710         case ND_NEIGHBOR_SOLICIT:
1711                 /*
1712                  * New entry must have is_router flag cleared.
1713                  */
1714                 if (is_newentry)        /* (6-7) */
1715                         ln->ln_router = 0;
1716                 break;
1717         case ND_REDIRECT:
1718                 /*
1719                  * If the icmp is a redirect to a better router, always set the
1720                  * is_router flag.  Otherwise, if the entry is newly created,
1721                  * clear the flag.  [RFC 2461, sec 8.3]
1722                  */
1723                 if (code == ND_REDIRECT_ROUTER)
1724                         ln->ln_router = 1;
1725                 else if (is_newentry) /* (6-7) */
1726                         ln->ln_router = 0;
1727                 break;
1728         case ND_ROUTER_SOLICIT:
1729                 /*
1730                  * is_router flag must always be cleared.
1731                  */
1732                 ln->ln_router = 0;
1733                 break;
1734         case ND_ROUTER_ADVERT:
1735                 /*
1736                  * Mark an entry with lladdr as a router.
1737                  */
1738                 if ((!is_newentry && (olladdr || lladdr)) ||    /* (2-5) */
1739                     (is_newentry && lladdr)) {                  /* (7) */
1740                         ln->ln_router = 1;
1741                 }
1742                 break;
1743         }
1744
1745         if (ln != NULL) {
1746                 static_route = (ln->la_flags & LLE_STATIC);
1747                 router = ln->ln_router;
1748
1749                 if (flags & ND6_EXCLUSIVE)
1750                         LLE_WUNLOCK(ln);
1751                 else
1752                         LLE_RUNLOCK(ln);
1753                 if (static_route)
1754                         ln = NULL;
1755         }
1756         if (chain != NULL)
1757                 nd6_flush_holdchain(ifp, ifp, chain, &sin6);
1758         
1759         /*
1760          * When the link-layer address of a router changes, select the
1761          * best router again.  In particular, when the neighbor entry is newly
1762          * created, it might affect the selection policy.
1763          * Question: can we restrict the first condition to the "is_newentry"
1764          * case?
1765          * XXX: when we hear an RA from a new router with the link-layer
1766          * address option, defrouter_select() is called twice, since
1767          * defrtrlist_update called the function as well.  However, I believe
1768          * we can compromise the overhead, since it only happens the first
1769          * time.
1770          * XXX: although defrouter_select() should not have a bad effect
1771          * for those are not autoconfigured hosts, we explicitly avoid such
1772          * cases for safety.
1773          */
1774         if (do_update && router &&
1775             ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1776                 /*
1777                  * guaranteed recursion
1778                  */
1779                 defrouter_select();
1780         }
1781         
1782         return (ln);
1783 done:   
1784         if (ln != NULL) {
1785                 if (flags & ND6_EXCLUSIVE)
1786                         LLE_WUNLOCK(ln);
1787                 else
1788                         LLE_RUNLOCK(ln);
1789                 if (static_route)
1790                         ln = NULL;
1791         }
1792         return (ln);
1793 }
1794
1795 static void
1796 nd6_slowtimo(void *arg)
1797 {
1798         CURVNET_SET((struct vnet *) arg);
1799         struct nd_ifinfo *nd6if;
1800         struct ifnet *ifp;
1801
1802         callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
1803             nd6_slowtimo, curvnet);
1804         IFNET_RLOCK_NOSLEEP();
1805         TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1806                 if (ifp->if_afdata[AF_INET6] == NULL)
1807                         continue;
1808                 nd6if = ND_IFINFO(ifp);
1809                 if (nd6if->basereachable && /* already initialized */
1810                     (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1811                         /*
1812                          * Since reachable time rarely changes by router
1813                          * advertisements, we SHOULD insure that a new random
1814                          * value gets recomputed at least once every few hours.
1815                          * (RFC 2461, 6.3.4)
1816                          */
1817                         nd6if->recalctm = V_nd6_recalc_reachtm_interval;
1818                         nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1819                 }
1820         }
1821         IFNET_RUNLOCK_NOSLEEP();
1822         CURVNET_RESTORE();
1823 }
1824
1825 void
1826 nd6_grab_holdchain(struct llentry *ln, struct mbuf **chain,
1827     struct sockaddr_in6 *sin6)
1828 {
1829
1830         LLE_WLOCK_ASSERT(ln);
1831
1832         *chain = ln->la_hold;
1833         ln->la_hold = NULL;
1834         memcpy(sin6, L3_ADDR_SIN6(ln), sizeof(*sin6));
1835
1836         if (ln->ln_state == ND6_LLINFO_STALE) {
1837
1838                 /*
1839                  * The first time we send a packet to a
1840                  * neighbor whose entry is STALE, we have
1841                  * to change the state to DELAY and a sets
1842                  * a timer to expire in DELAY_FIRST_PROBE_TIME
1843                  * seconds to ensure do neighbor unreachability
1844                  * detection on expiration.
1845                  * (RFC 2461 7.3.3)
1846                  */
1847                 ln->la_asked = 0;
1848                 ln->ln_state = ND6_LLINFO_DELAY;
1849                 nd6_llinfo_settimer_locked(ln, (long)V_nd6_delay * hz);
1850         }
1851 }
1852
1853 static int
1854 nd6_output_ifp(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
1855     struct sockaddr_in6 *dst)
1856 {
1857         int error;
1858         int ip6len;
1859         struct ip6_hdr *ip6;
1860         struct m_tag *mtag;
1861
1862 #ifdef MAC
1863         mac_netinet6_nd6_send(ifp, m);
1864 #endif
1865
1866         /*
1867          * If called from nd6_ns_output() (NS), nd6_na_output() (NA),
1868          * icmp6_redirect_output() (REDIRECT) or from rip6_output() (RS, RA
1869          * as handled by rtsol and rtadvd), mbufs will be tagged for SeND
1870          * to be diverted to user space.  When re-injected into the kernel,
1871          * send_output() will directly dispatch them to the outgoing interface.
1872          */
1873         if (send_sendso_input_hook != NULL) {
1874                 mtag = m_tag_find(m, PACKET_TAG_ND_OUTGOING, NULL);
1875                 if (mtag != NULL) {
1876                         ip6 = mtod(m, struct ip6_hdr *);
1877                         ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
1878                         /* Use the SEND socket */
1879                         error = send_sendso_input_hook(m, ifp, SND_OUT,
1880                             ip6len);
1881                         /* -1 == no app on SEND socket */
1882                         if (error == 0 || error != -1)
1883                             return (error);
1884                 }
1885         }
1886
1887         m_clrprotoflags(m);     /* Avoid confusing lower layers. */
1888         IP_PROBE(send, NULL, NULL, mtod(m, struct ip6_hdr *), ifp, NULL,
1889             mtod(m, struct ip6_hdr *));
1890
1891         if ((ifp->if_flags & IFF_LOOPBACK) == 0)
1892                 origifp = ifp;
1893
1894         error = (*ifp->if_output)(origifp, m, (struct sockaddr *)dst, NULL);
1895         return (error);
1896 }
1897
1898 /*
1899  * IPv6 packet output - light version.
1900  * Checks if destination LLE exists and is in proper state
1901  * (e.g no modification required). If not true, fall back to
1902  * "heavy" version.
1903  */
1904 int
1905 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
1906     struct sockaddr_in6 *dst, struct rtentry *rt0)
1907 {
1908         struct llentry *ln = NULL;
1909
1910         /* discard the packet if IPv6 operation is disabled on the interface */
1911         if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
1912                 m_freem(m);
1913                 return (ENETDOWN); /* better error? */
1914         }
1915
1916         if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1917                 goto sendpkt;
1918
1919         if (nd6_need_cache(ifp) == 0)
1920                 goto sendpkt;
1921
1922         IF_AFDATA_RLOCK(ifp);
1923         ln = nd6_lookup(&dst->sin6_addr, 0, ifp);
1924         IF_AFDATA_RUNLOCK(ifp);
1925
1926         /*
1927          * Perform fast path for the following cases:
1928          * 1) lle state is REACHABLE
1929          * 2) lle state is DELAY (NS message sentNS message sent)
1930          *
1931          * Every other case involves lle modification, so we handle
1932          * them separately.
1933          */
1934         if (ln == NULL || (ln->ln_state != ND6_LLINFO_REACHABLE &&
1935             ln->ln_state != ND6_LLINFO_DELAY)) {
1936                 /* Fall back to slow processing path */
1937                 if (ln != NULL)
1938                         LLE_RUNLOCK(ln);
1939                 return (nd6_output_lle(ifp, origifp, m, dst));
1940         }
1941
1942 sendpkt:
1943         if (ln != NULL)
1944                 LLE_RUNLOCK(ln);
1945
1946         return (nd6_output_ifp(ifp, origifp, m, dst));
1947 }
1948
1949
1950 /*
1951  * Output IPv6 packet - heavy version.
1952  * Function assume that either
1953  * 1) destination LLE does not exist, is invalid or stale, so
1954  *   ND6_EXCLUSIVE lock needs to be acquired
1955  * 2) destination lle is provided (with ND6_EXCLUSIVE lock),
1956  *   in that case packets are queued in &chain.
1957  *
1958  */
1959 static int
1960 nd6_output_lle(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
1961     struct sockaddr_in6 *dst)
1962 {
1963         struct llentry *lle = NULL;
1964         int flags = 0;
1965
1966         KASSERT(m != NULL, ("NULL mbuf, nothing to send"));
1967         /* discard the packet if IPv6 operation is disabled on the interface */
1968         if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
1969                 m_freem(m);
1970                 return (ENETDOWN); /* better error? */
1971         }
1972
1973         if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1974                 goto sendpkt;
1975
1976         if (nd6_need_cache(ifp) == 0)
1977                 goto sendpkt;
1978
1979         /*
1980          * Address resolution or Neighbor Unreachability Detection
1981          * for the next hop.
1982          * At this point, the destination of the packet must be a unicast
1983          * or an anycast address(i.e. not a multicast).
1984          */
1985         if (lle == NULL) {
1986                 IF_AFDATA_RLOCK(ifp);
1987                 lle = nd6_lookup(&dst->sin6_addr, ND6_EXCLUSIVE, ifp);
1988                 IF_AFDATA_RUNLOCK(ifp);
1989                 if ((lle == NULL) && nd6_is_addr_neighbor(dst, ifp))  {
1990                         /*
1991                          * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
1992                          * the condition below is not very efficient.  But we believe
1993                          * it is tolerable, because this should be a rare case.
1994                          */
1995                         flags = ND6_CREATE | ND6_EXCLUSIVE;
1996                         IF_AFDATA_LOCK(ifp);
1997                         lle = nd6_lookup(&dst->sin6_addr, flags, ifp);
1998                         IF_AFDATA_UNLOCK(ifp);
1999                 }
2000         } 
2001         if (lle == NULL) {
2002                 if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
2003                     !(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
2004                         char ip6buf[INET6_ADDRSTRLEN];
2005                         log(LOG_DEBUG,
2006                             "nd6_output: can't allocate llinfo for %s "
2007                             "(ln=%p)\n",
2008                             ip6_sprintf(ip6buf, &dst->sin6_addr), lle);
2009                         m_freem(m);
2010                         return (ENOBUFS);
2011                 }
2012                 goto sendpkt;   /* send anyway */
2013         }
2014
2015         LLE_WLOCK_ASSERT(lle);
2016
2017         /* We don't have to do link-layer address resolution on a p2p link. */
2018         if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
2019             lle->ln_state < ND6_LLINFO_REACHABLE) {
2020                 lle->ln_state = ND6_LLINFO_STALE;
2021                 nd6_llinfo_settimer_locked(lle, (long)V_nd6_gctimer * hz);
2022         }
2023
2024         /*
2025          * The first time we send a packet to a neighbor whose entry is
2026          * STALE, we have to change the state to DELAY and a sets a timer to
2027          * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
2028          * neighbor unreachability detection on expiration.
2029          * (RFC 2461 7.3.3)
2030          */
2031         if (lle->ln_state == ND6_LLINFO_STALE) {
2032                 lle->la_asked = 0;
2033                 lle->ln_state = ND6_LLINFO_DELAY;
2034                 nd6_llinfo_settimer_locked(lle, (long)V_nd6_delay * hz);
2035         }
2036
2037         /*
2038          * If the neighbor cache entry has a state other than INCOMPLETE
2039          * (i.e. its link-layer address is already resolved), just
2040          * send the packet.
2041          */
2042         if (lle->ln_state > ND6_LLINFO_INCOMPLETE)
2043                 goto sendpkt;
2044
2045         /*
2046          * There is a neighbor cache entry, but no ethernet address
2047          * response yet.  Append this latest packet to the end of the
2048          * packet queue in the mbuf, unless the number of the packet
2049          * does not exceed nd6_maxqueuelen.  When it exceeds nd6_maxqueuelen,
2050          * the oldest packet in the queue will be removed.
2051          */
2052         if (lle->ln_state == ND6_LLINFO_NOSTATE)
2053                 lle->ln_state = ND6_LLINFO_INCOMPLETE;
2054
2055         if (lle->la_hold != NULL) {
2056                 struct mbuf *m_hold;
2057                 int i;
2058                 
2059                 i = 0;
2060                 for (m_hold = lle->la_hold; m_hold; m_hold = m_hold->m_nextpkt){
2061                         i++;
2062                         if (m_hold->m_nextpkt == NULL) {
2063                                 m_hold->m_nextpkt = m;
2064                                 break;
2065                         }
2066                 }
2067                 while (i >= V_nd6_maxqueuelen) {
2068                         m_hold = lle->la_hold;
2069                         lle->la_hold = lle->la_hold->m_nextpkt;
2070                         m_freem(m_hold);
2071                         i--;
2072                 }
2073         } else {
2074                 lle->la_hold = m;
2075         }
2076
2077         /*
2078          * If there has been no NS for the neighbor after entering the
2079          * INCOMPLETE state, send the first solicitation.
2080          */
2081         if (!ND6_LLINFO_PERMANENT(lle) && lle->la_asked == 0) {
2082                 lle->la_asked++;
2083                 
2084                 nd6_llinfo_settimer_locked(lle,
2085                     (long)ND_IFINFO(ifp)->retrans * hz / 1000);
2086                 LLE_WUNLOCK(lle);
2087                 nd6_ns_output(ifp, NULL, &dst->sin6_addr, lle, NULL);
2088         } else {
2089                 /* We did the lookup so we need to do the unlock here. */
2090                 LLE_WUNLOCK(lle);
2091         }
2092
2093         return (0);
2094
2095   sendpkt:
2096         if (lle != NULL)
2097                 LLE_WUNLOCK(lle);
2098
2099         return (nd6_output_ifp(ifp, origifp, m, dst));
2100 }
2101
2102
2103 int
2104 nd6_flush_holdchain(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *chain,
2105     struct sockaddr_in6 *dst)
2106 {
2107         struct mbuf *m, *m_head;
2108         struct ifnet *outifp;
2109         int error = 0;
2110
2111         m_head = chain;
2112         if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2113                 outifp = origifp;
2114         else
2115                 outifp = ifp;
2116         
2117         while (m_head) {
2118                 m = m_head;
2119                 m_head = m_head->m_nextpkt;
2120                 error = nd6_output_ifp(ifp, origifp, m, dst);
2121         }
2122
2123         /*
2124          * XXX
2125          * note that intermediate errors are blindly ignored - but this is 
2126          * the same convention as used with nd6_output when called by
2127          * nd6_cache_lladdr
2128          */
2129         return (error);
2130 }       
2131
2132
2133 int
2134 nd6_need_cache(struct ifnet *ifp)
2135 {
2136         /*
2137          * XXX: we currently do not make neighbor cache on any interface
2138          * other than ARCnet, Ethernet, FDDI and GIF.
2139          *
2140          * RFC2893 says:
2141          * - unidirectional tunnels needs no ND
2142          */
2143         switch (ifp->if_type) {
2144         case IFT_ARCNET:
2145         case IFT_ETHER:
2146         case IFT_FDDI:
2147         case IFT_IEEE1394:
2148         case IFT_L2VLAN:
2149         case IFT_IEEE80211:
2150         case IFT_INFINIBAND:
2151         case IFT_BRIDGE:
2152         case IFT_PROPVIRTUAL:
2153                 return (1);
2154         default:
2155                 return (0);
2156         }
2157 }
2158
2159 /*
2160  * Add pernament ND6 link-layer record for given
2161  * interface address.
2162  *
2163  * Very similar to IPv4 arp_ifinit(), but:
2164  * 1) IPv6 DAD is performed in different place
2165  * 2) It is called by IPv6 protocol stack in contrast to
2166  * arp_ifinit() which is typically called in SIOCSIFADDR
2167  * driver ioctl handler.
2168  *
2169  */
2170 int
2171 nd6_add_ifa_lle(struct in6_ifaddr *ia)
2172 {
2173         struct ifnet *ifp;
2174         struct llentry *ln;
2175
2176         ifp = ia->ia_ifa.ifa_ifp;
2177         if (nd6_need_cache(ifp) == 0)
2178                 return (0);
2179         IF_AFDATA_LOCK(ifp);
2180         ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
2181         ln = lla_lookup(LLTABLE6(ifp), (LLE_CREATE | LLE_IFADDR |
2182             LLE_EXCLUSIVE), (struct sockaddr *)&ia->ia_addr);
2183         IF_AFDATA_UNLOCK(ifp);
2184         if (ln != NULL) {
2185                 ln->la_expire = 0;  /* for IPv6 this means permanent */
2186                 ln->ln_state = ND6_LLINFO_REACHABLE;
2187                 LLE_WUNLOCK(ln);
2188                 return (0);
2189         }
2190
2191         return (ENOBUFS);
2192 }
2193
2194 /*
2195  * Removes ALL lle records for interface address prefix.
2196  * XXXME: That's probably not we really want to do, we need
2197  * to remove address record only and keep other records
2198  * until we determine if given prefix is really going 
2199  * to be removed.
2200  */
2201 void
2202 nd6_rem_ifa_lle(struct in6_ifaddr *ia)
2203 {
2204         struct sockaddr_in6 mask, addr;
2205         struct ifnet *ifp;
2206
2207         ifp = ia->ia_ifa.ifa_ifp;
2208         memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
2209         memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
2210         lltable_prefix_free(AF_INET6, (struct sockaddr *)&addr,
2211                     (struct sockaddr *)&mask, LLE_STATIC);
2212 }
2213
2214 /*
2215  * the callers of this function need to be re-worked to drop
2216  * the lle lock, drop here for now
2217  */
2218 int
2219 nd6_storelladdr(struct ifnet *ifp, struct mbuf *m,
2220     const struct sockaddr *dst, u_char *desten, uint32_t *pflags)
2221 {
2222         struct llentry *ln;
2223
2224         if (pflags != NULL)
2225                 *pflags = 0;
2226         IF_AFDATA_UNLOCK_ASSERT(ifp);
2227         if (m != NULL && m->m_flags & M_MCAST) {
2228                 switch (ifp->if_type) {
2229                 case IFT_ETHER:
2230                 case IFT_FDDI:
2231                 case IFT_L2VLAN:
2232                 case IFT_IEEE80211:
2233                 case IFT_BRIDGE:
2234                 case IFT_ISO88025:
2235                         ETHER_MAP_IPV6_MULTICAST(&SIN6(dst)->sin6_addr,
2236                                                  desten);
2237                         return (0);
2238                 default:
2239                         m_freem(m);
2240                         return (EAFNOSUPPORT);
2241                 }
2242         }
2243
2244
2245         /*
2246          * the entry should have been created in nd6_store_lladdr
2247          */
2248         IF_AFDATA_RLOCK(ifp);
2249         ln = lla_lookup(LLTABLE6(ifp), 0, dst);
2250         IF_AFDATA_RUNLOCK(ifp);
2251         if ((ln == NULL) || !(ln->la_flags & LLE_VALID)) {
2252                 if (ln != NULL)
2253                         LLE_RUNLOCK(ln);
2254                 /* this could happen, if we could not allocate memory */
2255                 m_freem(m);
2256                 return (1);
2257         }
2258
2259         bcopy(&ln->ll_addr, desten, ifp->if_addrlen);
2260         if (pflags != NULL)
2261                 *pflags = ln->la_flags;
2262         LLE_RUNLOCK(ln);
2263         /*
2264          * A *small* use after free race exists here
2265          */
2266         return (0);
2267 }
2268
2269 static void 
2270 clear_llinfo_pqueue(struct llentry *ln)
2271 {
2272         struct mbuf *m_hold, *m_hold_next;
2273
2274         for (m_hold = ln->la_hold; m_hold; m_hold = m_hold_next) {
2275                 m_hold_next = m_hold->m_nextpkt;
2276                 m_freem(m_hold);
2277         }
2278
2279         ln->la_hold = NULL;
2280         return;
2281 }
2282
2283 static int nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS);
2284 static int nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS);
2285 #ifdef SYSCTL_DECL
2286 SYSCTL_DECL(_net_inet6_icmp6);
2287 #endif
2288 SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2289         CTLFLAG_RD, nd6_sysctl_drlist, "");
2290 SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2291         CTLFLAG_RD, nd6_sysctl_prlist, "");
2292 SYSCTL_INT(_net_inet6_icmp6, ICMPV6CTL_ND6_MAXQLEN, nd6_maxqueuelen,
2293         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_maxqueuelen), 1, "");
2294 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, nd6_gctimer,
2295         CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_gctimer), (60 * 60 * 24), "");
2296
2297 static int
2298 nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2299 {
2300         struct in6_defrouter d;
2301         struct nd_defrouter *dr;
2302         int error;
2303
2304         if (req->newptr)
2305                 return (EPERM);
2306
2307         bzero(&d, sizeof(d));
2308         d.rtaddr.sin6_family = AF_INET6;
2309         d.rtaddr.sin6_len = sizeof(d.rtaddr);
2310
2311         /*
2312          * XXX locking
2313          */
2314         TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry) {
2315                 d.rtaddr.sin6_addr = dr->rtaddr;
2316                 error = sa6_recoverscope(&d.rtaddr);
2317                 if (error != 0)
2318                         return (error);
2319                 d.flags = dr->flags;
2320                 d.rtlifetime = dr->rtlifetime;
2321                 d.expire = dr->expire + (time_second - time_uptime);
2322                 d.if_index = dr->ifp->if_index;
2323                 error = SYSCTL_OUT(req, &d, sizeof(d));
2324                 if (error != 0)
2325                         return (error);
2326         }
2327         return (0);
2328 }
2329
2330 static int
2331 nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2332 {
2333         struct in6_prefix p;
2334         struct sockaddr_in6 s6;
2335         struct nd_prefix *pr;
2336         struct nd_pfxrouter *pfr;
2337         time_t maxexpire;
2338         int error;
2339         char ip6buf[INET6_ADDRSTRLEN];
2340
2341         if (req->newptr)
2342                 return (EPERM);
2343
2344         bzero(&p, sizeof(p));
2345         p.origin = PR_ORIG_RA;
2346         bzero(&s6, sizeof(s6));
2347         s6.sin6_family = AF_INET6;
2348         s6.sin6_len = sizeof(s6);
2349
2350         /*
2351          * XXX locking
2352          */
2353         LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
2354                 p.prefix = pr->ndpr_prefix;
2355                 if (sa6_recoverscope(&p.prefix)) {
2356                         log(LOG_ERR, "scope error in prefix list (%s)\n",
2357                             ip6_sprintf(ip6buf, &p.prefix.sin6_addr));
2358                         /* XXX: press on... */
2359                 }
2360                 p.raflags = pr->ndpr_raf;
2361                 p.prefixlen = pr->ndpr_plen;
2362                 p.vltime = pr->ndpr_vltime;
2363                 p.pltime = pr->ndpr_pltime;
2364                 p.if_index = pr->ndpr_ifp->if_index;
2365                 if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2366                         p.expire = 0;
2367                 else {
2368                         /* XXX: we assume time_t is signed. */
2369                         maxexpire = (-1) &
2370                             ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
2371                         if (pr->ndpr_vltime < maxexpire - pr->ndpr_lastupdate)
2372                                 p.expire = pr->ndpr_lastupdate +
2373                                     pr->ndpr_vltime +
2374                                     (time_second - time_uptime);
2375                         else
2376                                 p.expire = maxexpire;
2377                 }
2378                 p.refcnt = pr->ndpr_refcnt;
2379                 p.flags = pr->ndpr_stateflags;
2380                 p.advrtrs = 0;
2381                 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
2382                         p.advrtrs++;
2383                 error = SYSCTL_OUT(req, &p, sizeof(p));
2384                 if (error != 0)
2385                         return (error);
2386                 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
2387                         s6.sin6_addr = pfr->router->rtaddr;
2388                         if (sa6_recoverscope(&s6))
2389                                 log(LOG_ERR,
2390                                     "scope error in prefix list (%s)\n",
2391                                     ip6_sprintf(ip6buf, &pfr->router->rtaddr));
2392                         error = SYSCTL_OUT(req, &s6, sizeof(s6));
2393                         if (error != 0)
2394                                 return (error);
2395                 }
2396         }
2397         return (0);
2398 }