inet6: Dispatch in6_tmpaddrtimer to netisr0 to run
[dragonfly.git] / sys / netinet6 / nd6.c
1 /*      $FreeBSD: src/sys/netinet6/nd6.c,v 1.2.2.15 2003/05/06 06:46:58 suz Exp $       */
2 /*      $KAME: nd6.c,v 1.144 2001/05/24 07:44:00 itojun Exp $   */
3
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 /*
34  * XXX
35  * KAME 970409 note:
36  * BSD/OS version heavily modifies this code, related to llinfo.
37  * Since we don't have BSD/OS version of net/route.c in our hand,
38  * I left the code mostly as it was in 970310.  -- itojun
39  */
40
41 #include "opt_inet.h"
42 #include "opt_inet6.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/callout.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/socket.h>
50 #include <sys/sockio.h>
51 #include <sys/time.h>
52 #include <sys/kernel.h>
53 #include <sys/protosw.h>
54 #include <sys/errno.h>
55 #include <sys/syslog.h>
56 #include <sys/queue.h>
57 #include <sys/sysctl.h>
58 #include <sys/mutex.h>
59
60 #include <sys/thread2.h>
61 #include <sys/mutex2.h>
62
63 #include <net/if.h>
64 #include <net/if_dl.h>
65 #include <net/if_types.h>
66 #include <net/route.h>
67 #include <net/netisr2.h>
68 #include <net/netmsg2.h>
69
70 #include <netinet/in.h>
71 #include <netinet/if_ether.h>
72 #include <netinet6/in6_var.h>
73 #include <netinet/ip6.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/nd6.h>
76 #include <netinet/icmp6.h>
77
78 #include <net/net_osdep.h>
79
80 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
81 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
82
83 #define SIN6(s) ((struct sockaddr_in6 *)s)
84 #define SDL(s) ((struct sockaddr_dl *)s)
85
86 /* timer values */
87 int     nd6_prune       = 1;    /* walk list every 1 seconds */
88 int     nd6_delay       = 5;    /* delay first probe time 5 second */
89 int     nd6_umaxtries   = 3;    /* maximum unicast query */
90 int     nd6_mmaxtries   = 3;    /* maximum multicast query */
91 int     nd6_useloopback = 1;    /* use loopback interface for local traffic */
92 int     nd6_gctimer     = (60 * 60 * 24); /* 1 day: garbage collection timer */
93
94 /* preventing too many loops in ND option parsing */
95 int nd6_maxndopt = 10;  /* max # of ND options allowed */
96
97 int nd6_maxnudhint = 0; /* max # of subsequent upper layer hints */
98
99 #ifdef ND6_DEBUG
100 int nd6_debug = 1;
101 #else
102 int nd6_debug = 0;
103 #endif
104
105 /* for debugging? */
106 static int nd6_inuse, nd6_allocated;
107
108 struct llinfo_nd6 llinfo_nd6 = {&llinfo_nd6, &llinfo_nd6};
109 struct nd_drhead nd_defrouter;
110 struct nd_prhead nd_prefix = { 0 };
111 struct mtx nd6_mtx = MTX_INITIALIZER;
112
113 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
114 static struct sockaddr_in6 all1_sa;
115
116 static void nd6_setmtu0 (struct ifnet *, struct nd_ifinfo *);
117 static void nd6_slowtimo (void *);
118 static int regen_tmpaddr (struct in6_ifaddr *);
119
120 struct callout nd6_slowtimo_ch;
121 struct callout nd6_timer_ch;
122
123 void
124 nd6_init(void)
125 {
126         static int nd6_init_done = 0;
127         int i;
128
129         if (nd6_init_done) {
130                 log(LOG_NOTICE, "nd6_init called more than once(ignored)\n");
131                 return;
132         }
133
134         all1_sa.sin6_family = AF_INET6;
135         all1_sa.sin6_len = sizeof(struct sockaddr_in6);
136         for (i = 0; i < sizeof(all1_sa.sin6_addr); i++)
137                 all1_sa.sin6_addr.s6_addr[i] = 0xff;
138
139         /* initialization of the default router list */
140         TAILQ_INIT(&nd_defrouter);
141
142         nd6_init_done = 1;
143
144         /* start timer */
145         callout_init(&nd6_slowtimo_ch);
146         callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
147             nd6_slowtimo, NULL);
148 }
149
150 struct nd_ifinfo *
151 nd6_ifattach(struct ifnet *ifp)
152 {
153         struct nd_ifinfo *nd;
154
155         nd = (struct nd_ifinfo *)kmalloc(sizeof(*nd), M_IP6NDP,
156             M_WAITOK | M_ZERO);
157
158         nd->initialized = 1;
159
160         nd->linkmtu = ifp->if_mtu;
161         nd->chlim = IPV6_DEFHLIM;
162         nd->basereachable = REACHABLE_TIME;
163         nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
164         nd->retrans = RETRANS_TIMER;
165         nd->receivedra = 0;
166
167         /*
168          * Note that the default value of ip6_accept_rtadv is 0, which means
169          * we won't accept RAs by default even if we set ND6_IFF_ACCEPT_RTADV
170          * here.
171          */
172         nd->flags = (ND6_IFF_PERFORMNUD | ND6_IFF_ACCEPT_RTADV);
173
174         /* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
175         nd6_setmtu0(ifp, nd);
176         return nd;
177 }
178
179 void
180 nd6_ifdetach(struct nd_ifinfo *nd)
181 {
182         kfree(nd, M_IP6NDP);
183 }
184
185 /*
186  * Reset ND level link MTU. This function is called when the physical MTU
187  * changes, which means we might have to adjust the ND level MTU.
188  */
189 void
190 nd6_setmtu(struct ifnet *ifp)
191 {
192         nd6_setmtu0(ifp, ND_IFINFO(ifp));
193 }
194
195 struct netmsg_nd6setmtu {
196         struct netmsg_base      nmsg;
197         struct ifnet            *ifp;
198         struct nd_ifinfo        *ndi;
199 };
200
201 /* XXX todo: do not maintain copy of ifp->if_mtu in ndi->maxmtu */
202 static void
203 nd6_setmtu0_dispatch(netmsg_t msg)
204 {
205         struct netmsg_nd6setmtu *nmsg = (struct netmsg_nd6setmtu *)msg;
206         struct ifnet *ifp = nmsg->ifp;
207         struct nd_ifinfo *ndi = nmsg->ndi;
208         u_long oldmaxmtu;
209         u_long oldlinkmtu;
210
211         oldmaxmtu = ndi->maxmtu;
212         oldlinkmtu = ndi->linkmtu;
213
214         switch (ifp->if_type) {
215         case IFT_ETHER:
216                 ndi->maxmtu = MIN(ETHERMTU, ifp->if_mtu);
217                 break;
218         case IFT_IEEE1394:      /* XXX should be IEEE1394MTU(1500) */
219                 ndi->maxmtu = MIN(ETHERMTU, ifp->if_mtu);
220                 break;
221 #ifdef IFT_IEEE80211
222         case IFT_IEEE80211:     /* XXX should be IEEE80211MTU(1500) */
223                 ndi->maxmtu = MIN(ETHERMTU, ifp->if_mtu);
224                 break;
225 #endif
226         default:
227                 ndi->maxmtu = ifp->if_mtu;
228                 break;
229         }
230
231         if (oldmaxmtu != ndi->maxmtu) {
232                 /*
233                  * If the ND level MTU is not set yet, or if the maxmtu
234                  * is reset to a smaller value than the ND level MTU,
235                  * also reset the ND level MTU.
236                  */
237                 if (ndi->linkmtu == 0 ||
238                     ndi->maxmtu < ndi->linkmtu) {
239                         ndi->linkmtu = ndi->maxmtu;
240                         /* also adjust in6_maxmtu if necessary. */
241                         if (oldlinkmtu == 0) {
242                                 /*
243                                  * XXX: the case analysis is grotty, but
244                                  * it is not efficient to call in6_setmaxmtu()
245                                  * here when we are during the initialization
246                                  * procedure.
247                                  */
248                                 if (in6_maxmtu < ndi->linkmtu)
249                                         in6_maxmtu = ndi->linkmtu;
250                         } else
251                                 in6_setmaxmtu();
252                 }
253         }
254 #undef MIN
255
256         lwkt_replymsg(&nmsg->nmsg.lmsg, 0);
257 }
258
259 void
260 nd6_setmtu0(struct ifnet *ifp, struct nd_ifinfo *ndi)
261 {
262         struct netmsg_nd6setmtu nmsg;
263
264         netmsg_init(&nmsg.nmsg, NULL, &curthread->td_msgport, 0,
265             nd6_setmtu0_dispatch);
266         nmsg.ifp = ifp;
267         nmsg.ndi = ndi;
268         lwkt_domsg(netisr_cpuport(0), &nmsg.nmsg.lmsg, 0);
269 }
270
271 void
272 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
273 {
274         bzero(ndopts, sizeof(*ndopts));
275         ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
276         ndopts->nd_opts_last
277                 = (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
278
279         if (icmp6len == 0) {
280                 ndopts->nd_opts_done = 1;
281                 ndopts->nd_opts_search = NULL;
282         }
283 }
284
285 /*
286  * Take one ND option.
287  */
288 struct nd_opt_hdr *
289 nd6_option(union nd_opts *ndopts)
290 {
291         struct nd_opt_hdr *nd_opt;
292         int olen;
293
294         if (!ndopts)
295                 panic("ndopts == NULL in nd6_option");
296         if (!ndopts->nd_opts_last)
297                 panic("uninitialized ndopts in nd6_option");
298         if (!ndopts->nd_opts_search)
299                 return NULL;
300         if (ndopts->nd_opts_done)
301                 return NULL;
302
303         nd_opt = ndopts->nd_opts_search;
304
305         /* make sure nd_opt_len is inside the buffer */
306         if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
307                 bzero(ndopts, sizeof(*ndopts));
308                 return NULL;
309         }
310
311         olen = nd_opt->nd_opt_len << 3;
312         if (olen == 0) {
313                 /*
314                  * Message validation requires that all included
315                  * options have a length that is greater than zero.
316                  */
317                 bzero(ndopts, sizeof(*ndopts));
318                 return NULL;
319         }
320
321         ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
322         if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
323                 /* option overruns the end of buffer, invalid */
324                 bzero(ndopts, sizeof(*ndopts));
325                 return NULL;
326         } else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
327                 /* reached the end of options chain */
328                 ndopts->nd_opts_done = 1;
329                 ndopts->nd_opts_search = NULL;
330         }
331         return nd_opt;
332 }
333
334 /*
335  * Parse multiple ND options.
336  * This function is much easier to use, for ND routines that do not need
337  * multiple options of the same type.
338  */
339 int
340 nd6_options(union nd_opts *ndopts)
341 {
342         struct nd_opt_hdr *nd_opt;
343         int i = 0;
344
345         if (!ndopts)
346                 panic("ndopts == NULL in nd6_options");
347         if (!ndopts->nd_opts_last)
348                 panic("uninitialized ndopts in nd6_options");
349         if (!ndopts->nd_opts_search)
350                 return 0;
351
352         while (1) {
353                 nd_opt = nd6_option(ndopts);
354                 if (!nd_opt && !ndopts->nd_opts_last) {
355                         /*
356                          * Message validation requires that all included
357                          * options have a length that is greater than zero.
358                          */
359                         icmp6stat.icp6s_nd_badopt++;
360                         bzero(ndopts, sizeof(*ndopts));
361                         return -1;
362                 }
363
364                 if (!nd_opt)
365                         goto skip1;
366
367                 switch (nd_opt->nd_opt_type) {
368                 case ND_OPT_SOURCE_LINKADDR:
369                 case ND_OPT_TARGET_LINKADDR:
370                 case ND_OPT_MTU:
371                 case ND_OPT_REDIRECTED_HEADER:
372                         if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
373                                 nd6log((LOG_INFO,
374                                     "duplicated ND6 option found (type=%d)\n",
375                                     nd_opt->nd_opt_type));
376                                 /* XXX bark? */
377                         } else {
378                                 ndopts->nd_opt_array[nd_opt->nd_opt_type]
379                                         = nd_opt;
380                         }
381                         break;
382                 case ND_OPT_PREFIX_INFORMATION:
383                         if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
384                                 ndopts->nd_opt_array[nd_opt->nd_opt_type]
385                                         = nd_opt;
386                         }
387                         ndopts->nd_opts_pi_end =
388                                 (struct nd_opt_prefix_info *)nd_opt;
389                         break;
390                 default:
391                         /*
392                          * Unknown options must be silently ignored,
393                          * to accomodate future extension to the protocol.
394                          */
395                         nd6log((LOG_DEBUG,
396                             "nd6_options: unsupported option %d - "
397                             "option ignored\n", nd_opt->nd_opt_type));
398                 }
399
400 skip1:
401                 i++;
402                 if (i > nd6_maxndopt) {
403                         icmp6stat.icp6s_nd_toomanyopt++;
404                         nd6log((LOG_INFO, "too many loop in nd opt\n"));
405                         break;
406                 }
407
408                 if (ndopts->nd_opts_done)
409                         break;
410         }
411
412         return 0;
413 }
414
415 /*
416  * ND6 timer routine to expire default route list and prefix list
417  */
418 void
419 nd6_timer(void *ignored_arg)
420 {
421         struct llinfo_nd6 *ln;
422         struct nd_defrouter *dr;
423         struct nd_prefix *pr;
424         struct ifnet *ifp;
425         struct in6_ifaddr *ia6, *nia6;
426
427         mtx_lock(&nd6_mtx);
428         callout_reset(&nd6_timer_ch, nd6_prune * hz,
429                       nd6_timer, NULL);
430
431         ln = llinfo_nd6.ln_next;
432         while (ln && ln != &llinfo_nd6) {
433                 struct rtentry *rt;
434                 struct sockaddr_in6 *dst;
435                 struct llinfo_nd6 *next = ln->ln_next;
436                 /* XXX: used for the DELAY case only: */
437                 struct nd_ifinfo *ndi = NULL;
438
439                 if ((rt = ln->ln_rt) == NULL) {
440                         ln = next;
441                         continue;
442                 }
443                 if ((ifp = rt->rt_ifp) == NULL) {
444                         ln = next;
445                         continue;
446                 }
447                 ndi = ND_IFINFO(ifp);
448                 dst = (struct sockaddr_in6 *)rt_key(rt);
449
450                 if (ln->ln_expire > time_uptime) {
451                         ln = next;
452                         continue;
453                 }
454
455                 /* sanity check */
456                 if (!rt)
457                         panic("rt=0 in nd6_timer(ln=%p)", ln);
458                 if (rt->rt_llinfo && (struct llinfo_nd6 *)rt->rt_llinfo != ln)
459                         panic("rt_llinfo(%p) is not equal to ln(%p)",
460                               rt->rt_llinfo, ln);
461                 if (!dst)
462                         panic("dst=0 in nd6_timer(ln=%p)", ln);
463
464                 switch (ln->ln_state) {
465                 case ND6_LLINFO_INCOMPLETE:
466                         if (ln->ln_asked < nd6_mmaxtries) {
467                                 ln->ln_asked++;
468                                 ln->ln_expire = time_uptime +
469                                         ND_IFINFO(ifp)->retrans / 1000;
470                                 nd6_ns_output(ifp, NULL, &dst->sin6_addr,
471                                         ln, 0);
472                         } else {
473                                 struct mbuf *m = ln->ln_hold;
474                                 if (m) {
475                                         if (rt->rt_ifp) {
476                                                 /*
477                                                  * Fake rcvif to make ICMP error
478                                                  * more helpful in diagnosing
479                                                  * for the receiver.
480                                                  * XXX: should we consider
481                                                  * older rcvif?
482                                                  */
483                                                 m->m_pkthdr.rcvif = rt->rt_ifp;
484                                         }
485                                         icmp6_error(m, ICMP6_DST_UNREACH,
486                                                     ICMP6_DST_UNREACH_ADDR, 0);
487                                         ln->ln_hold = NULL;
488                                 }
489                                 next = nd6_free(rt);
490                         }
491                         break;
492                 case ND6_LLINFO_REACHABLE:
493                         if (ln->ln_expire) {
494                                 ln->ln_state = ND6_LLINFO_STALE;
495                                 ln->ln_expire = time_uptime + nd6_gctimer;
496                         }
497                         break;
498
499                 case ND6_LLINFO_STALE:
500                         /* Garbage Collection(RFC 2461 5.3) */
501                         if (ln->ln_expire)
502                                 next = nd6_free(rt);
503                         break;
504
505                 case ND6_LLINFO_DELAY:
506                         if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD)) {
507                                 /* We need NUD */
508                                 ln->ln_asked = 1;
509                                 ln->ln_state = ND6_LLINFO_PROBE;
510                                 ln->ln_expire = time_uptime +
511                                         ndi->retrans / 1000;
512                                 nd6_ns_output(ifp, &dst->sin6_addr,
513                                               &dst->sin6_addr,
514                                               ln, 0);
515                         } else {
516                                 ln->ln_state = ND6_LLINFO_STALE; /* XXX */
517                                 ln->ln_expire = time_uptime + nd6_gctimer;
518                         }
519                         break;
520                 case ND6_LLINFO_PROBE:
521                         if (ln->ln_asked < nd6_umaxtries) {
522                                 ln->ln_asked++;
523                                 ln->ln_expire = time_uptime +
524                                         ND_IFINFO(ifp)->retrans / 1000;
525                                 nd6_ns_output(ifp, &dst->sin6_addr,
526                                                &dst->sin6_addr, ln, 0);
527                         } else {
528                                 next = nd6_free(rt);
529                         }
530                         break;
531                 }
532                 ln = next;
533         }
534
535         /* expire default router list */
536         dr = TAILQ_FIRST(&nd_defrouter);
537         while (dr) {
538                 if (dr->expire && dr->expire < time_uptime) {
539                         struct nd_defrouter *t;
540                         t = TAILQ_NEXT(dr, dr_entry);
541                         defrtrlist_del(dr);
542                         dr = t;
543                 } else {
544                         dr = TAILQ_NEXT(dr, dr_entry);
545                 }
546         }
547
548         /*
549          * expire interface addresses.
550          * in the past the loop was inside prefix expiry processing.
551          * However, from a stricter speci-confrmance standpoint, we should
552          * rather separate address lifetimes and prefix lifetimes.
553          */
554 addrloop:
555         for (ia6 = in6_ifaddr; ia6; ia6 = nia6) {
556                 nia6 = ia6->ia_next;
557                 /* check address lifetime */
558                 if (IFA6_IS_INVALID(ia6)) {
559                         int regen = 0;
560
561                         /*
562                          * If the expiring address is temporary, try
563                          * regenerating a new one.  This would be useful when
564                          * we suspended a laptop PC, then turned it on after a
565                          * period that could invalidate all temporary
566                          * addresses.  Although we may have to restart the
567                          * loop (see below), it must be after purging the
568                          * address.  Otherwise, we'd see an infinite loop of
569                          * regeneration.
570                          */
571                         if (ip6_use_tempaddr &&
572                             (ia6->ia6_flags & IN6_IFF_TEMPORARY)) {
573                                 if (regen_tmpaddr(ia6) == 0)
574                                         regen = 1;
575                         }
576
577                         in6_purgeaddr(&ia6->ia_ifa);
578
579                         if (regen)
580                                 goto addrloop; /* XXX: see below */
581                 }
582                 if (IFA6_IS_DEPRECATED(ia6)) {
583                         int oldflags = ia6->ia6_flags;
584
585                         ia6->ia6_flags |= IN6_IFF_DEPRECATED;
586
587                         /*
588                          * If a temporary address has just become deprecated,
589                          * regenerate a new one if possible.
590                          */
591                         if (ip6_use_tempaddr &&
592                             (ia6->ia6_flags & IN6_IFF_TEMPORARY) &&
593                             !(oldflags & IN6_IFF_DEPRECATED)) {
594
595                                 if (regen_tmpaddr(ia6) == 0) {
596                                         /*
597                                          * A new temporary address is
598                                          * generated.
599                                          * XXX: this means the address chain
600                                          * has changed while we are still in
601                                          * the loop.  Although the change
602                                          * would not cause disaster (because
603                                          * it's not a deletion, but an
604                                          * addition,) we'd rather restart the
605                                          * loop just for safety.  Or does this
606                                          * significantly reduce performance??
607                                          */
608                                         goto addrloop;
609                                 }
610                         }
611                 } else {
612                         /*
613                          * A new RA might have made a deprecated address
614                          * preferred.
615                          */
616                         ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
617                 }
618         }
619
620         /* expire prefix list */
621         pr = nd_prefix.lh_first;
622         while (pr) {
623                 /*
624                  * check prefix lifetime.
625                  * since pltime is just for autoconf, pltime processing for
626                  * prefix is not necessary.
627                  */
628                 if (pr->ndpr_expire && pr->ndpr_expire < time_uptime) {
629                         struct nd_prefix *t;
630                         t = pr->ndpr_next;
631
632                         /*
633                          * address expiration and prefix expiration are
634                          * separate.  NEVER perform in6_purgeaddr here.
635                          */
636
637                         prelist_remove(pr);
638                         pr = t;
639                 } else
640                         pr = pr->ndpr_next;
641         }
642         mtx_unlock(&nd6_mtx);
643 }
644
645 static int
646 regen_tmpaddr(struct in6_ifaddr *ia6) /* deprecated/invalidated temporary
647                                          address */
648 {
649         struct ifaddr_container *ifac;
650         struct ifnet *ifp;
651         struct in6_ifaddr *public_ifa6 = NULL;
652
653         ifp = ia6->ia_ifa.ifa_ifp;
654         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
655                 struct ifaddr *ifa = ifac->ifa;
656                 struct in6_ifaddr *it6;
657
658                 if (ifa->ifa_addr->sa_family != AF_INET6)
659                         continue;
660
661                 it6 = (struct in6_ifaddr *)ifa;
662
663                 /* ignore no autoconf addresses. */
664                 if (!(it6->ia6_flags & IN6_IFF_AUTOCONF))
665                         continue;
666
667                 /* ignore autoconf addresses with different prefixes. */
668                 if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
669                         continue;
670
671                 /*
672                  * Now we are looking at an autoconf address with the same
673                  * prefix as ours.  If the address is temporary and is still
674                  * preferred, do not create another one.  It would be rare, but
675                  * could happen, for example, when we resume a laptop PC after
676                  * a long period.
677                  */
678                 if ((it6->ia6_flags & IN6_IFF_TEMPORARY) &&
679                     !IFA6_IS_DEPRECATED(it6)) {
680                         public_ifa6 = NULL;
681                         break;
682                 }
683
684                 /*
685                  * This is a public autoconf address that has the same prefix
686                  * as ours.  If it is preferred, keep it.  We can't break the
687                  * loop here, because there may be a still-preferred temporary
688                  * address with the prefix.
689                  */
690                 if (!IFA6_IS_DEPRECATED(it6))
691                     public_ifa6 = it6;
692         }
693
694         if (public_ifa6 != NULL) {
695                 int e;
696
697                 if ((e = in6_tmpifadd(public_ifa6, 0)) != 0) {
698                         log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
699                             " tmp addr,errno=%d\n", e);
700                         return (-1);
701                 }
702                 return (0);
703         }
704
705         return (-1);
706 }
707
708 /*
709  * Nuke neighbor cache/prefix/default router management table, right before
710  * ifp goes away.
711  */
712 void
713 nd6_purge(struct ifnet *ifp)
714 {
715         struct llinfo_nd6 *ln, *nln;
716         struct nd_defrouter *dr, *ndr, drany;
717         struct nd_prefix *pr, *npr;
718
719         /* Nuke default router list entries toward ifp */
720         if ((dr = TAILQ_FIRST(&nd_defrouter)) != NULL) {
721                 /*
722                  * The first entry of the list may be stored in
723                  * the routing table, so we'll delete it later.
724                  */
725                 for (dr = TAILQ_NEXT(dr, dr_entry); dr; dr = ndr) {
726                         ndr = TAILQ_NEXT(dr, dr_entry);
727                         if (dr->ifp == ifp)
728                                 defrtrlist_del(dr);
729                 }
730                 dr = TAILQ_FIRST(&nd_defrouter);
731                 if (dr->ifp == ifp)
732                         defrtrlist_del(dr);
733         }
734
735         /* Nuke prefix list entries toward ifp */
736         for (pr = nd_prefix.lh_first; pr; pr = npr) {
737                 npr = pr->ndpr_next;
738                 if (pr->ndpr_ifp == ifp) {
739                         /*
740                          * Previously, pr->ndpr_addr is removed as well,
741                          * but I strongly believe we don't have to do it.
742                          * nd6_purge() is only called from in6_ifdetach(),
743                          * which removes all the associated interface addresses
744                          * by itself.
745                          * (jinmei@kame.net 20010129)
746                          */
747                         prelist_remove(pr);
748                 }
749         }
750
751         /* cancel default outgoing interface setting */
752         if (nd6_defifindex == ifp->if_index)
753                 nd6_setdefaultiface(0);
754
755         if (!ip6_forwarding && ip6_accept_rtadv) { /* XXX: too restrictive? */
756                 /* refresh default router list */
757                 bzero(&drany, sizeof(drany));
758                 defrouter_delreq(&drany, 0);
759                 defrouter_select();
760         }
761
762         /*
763          * Nuke neighbor cache entries for the ifp.
764          * Note that rt->rt_ifp may not be the same as ifp,
765          * due to KAME goto ours hack.  See RTM_RESOLVE case in
766          * nd6_rtrequest(), and ip6_input().
767          */
768         ln = llinfo_nd6.ln_next;
769         while (ln && ln != &llinfo_nd6) {
770                 struct rtentry *rt;
771                 struct sockaddr_dl *sdl;
772
773                 nln = ln->ln_next;
774                 rt = ln->ln_rt;
775                 if (rt && rt->rt_gateway &&
776                     rt->rt_gateway->sa_family == AF_LINK) {
777                         sdl = (struct sockaddr_dl *)rt->rt_gateway;
778                         if (sdl->sdl_index == ifp->if_index)
779                                 nln = nd6_free(rt);
780                 }
781                 ln = nln;
782         }
783 }
784
785 struct rtentry *
786 nd6_lookup(struct in6_addr *addr6, int create, struct ifnet *ifp)
787 {
788         struct rtentry *rt;
789         struct sockaddr_in6 sin6;
790
791         bzero(&sin6, sizeof(sin6));
792         sin6.sin6_len = sizeof(struct sockaddr_in6);
793         sin6.sin6_family = AF_INET6;
794         sin6.sin6_addr = *addr6;
795
796         if (create)
797                 rt = rtlookup((struct sockaddr *)&sin6);
798         else
799                 rt = rtpurelookup((struct sockaddr *)&sin6);
800         if (rt && !(rt->rt_flags & RTF_LLINFO)) {
801                 /*
802                  * This is the case for the default route.
803                  * If we want to create a neighbor cache for the address, we
804                  * should free the route for the destination and allocate an
805                  * interface route.
806                  */
807                 if (create) {
808                         --rt->rt_refcnt;
809                         rt = NULL;
810                 }
811         }
812         if (!rt) {
813                 if (create && ifp) {
814                         int e;
815
816                         /*
817                          * If no route is available and create is set,
818                          * we allocate a host route for the destination
819                          * and treat it like an interface route.
820                          * This hack is necessary for a neighbor which can't
821                          * be covered by our own prefix.
822                          */
823                         struct ifaddr *ifa =
824                                 ifaof_ifpforaddr((struct sockaddr *)&sin6, ifp);
825                         if (ifa == NULL)
826                                 return (NULL);
827
828                         /*
829                          * Create a new route.  RTF_LLINFO is necessary
830                          * to create a Neighbor Cache entry for the
831                          * destination in nd6_rtrequest which will be
832                          * called in rtrequest via ifa->ifa_rtrequest.
833                          */
834                         if ((e = rtrequest(RTM_ADD, (struct sockaddr *)&sin6,
835                                            ifa->ifa_addr,
836                                            (struct sockaddr *)&all1_sa,
837                                            (ifa->ifa_flags |
838                                             RTF_HOST | RTF_LLINFO) &
839                                            ~RTF_CLONING,
840                                            &rt)) != 0)
841                                 log(LOG_ERR,
842                                     "nd6_lookup: failed to add route for a "
843                                     "neighbor(%s), errno=%d\n",
844                                     ip6_sprintf(addr6), e);
845                         if (rt == NULL)
846                                 return (NULL);
847                         if (rt->rt_llinfo) {
848                                 struct llinfo_nd6 *ln =
849                                         (struct llinfo_nd6 *)rt->rt_llinfo;
850                                 ln->ln_state = ND6_LLINFO_NOSTATE;
851                         }
852                 } else
853                         return (NULL);
854         }
855         rt->rt_refcnt--;
856         /*
857          * Validation for the entry.
858          * Note that the check for rt_llinfo is necessary because a cloned
859          * route from a parent route that has the L flag (e.g. the default
860          * route to a p2p interface) may have the flag, too, while the
861          * destination is not actually a neighbor.
862          * XXX: we can't use rt->rt_ifp to check for the interface, since
863          *      it might be the loopback interface if the entry is for our
864          *      own address on a non-loopback interface. Instead, we should
865          *      use rt->rt_ifa->ifa_ifp, which would specify the REAL
866          *      interface.
867          */
868         if ((rt->rt_flags & RTF_GATEWAY) || !(rt->rt_flags & RTF_LLINFO) ||
869             rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
870             (ifp && rt->rt_ifa->ifa_ifp != ifp)) {
871                 if (create) {
872                         log(LOG_DEBUG, "nd6_lookup: failed to lookup %s (if = %s)\n",
873                             ip6_sprintf(addr6), ifp ? if_name(ifp) : "unspec");
874                         /* xxx more logs... kazu */
875                 }
876                 return (NULL);
877         }
878         return (rt);
879 }
880
881 /*
882  * Detect if a given IPv6 address identifies a neighbor on a given link.
883  * XXX: should take care of the destination of a p2p link?
884  */
885 int
886 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
887 {
888         struct ifaddr_container *ifac;
889         int i;
890
891 #define IFADDR6(a) ((((struct in6_ifaddr *)(a))->ia_addr).sin6_addr)
892 #define IFMASK6(a) ((((struct in6_ifaddr *)(a))->ia_prefixmask).sin6_addr)
893
894         /*
895          * A link-local address is always a neighbor.
896          * XXX: we should use the sin6_scope_id field rather than the embedded
897          * interface index.
898          */
899         if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr) &&
900             ntohs(*(u_int16_t *)&addr->sin6_addr.s6_addr[2]) == ifp->if_index)
901                 return (1);
902
903         /*
904          * If the address matches one of our addresses,
905          * it should be a neighbor.
906          */
907         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
908                 struct ifaddr *ifa = ifac->ifa;
909
910                 if (ifa->ifa_addr->sa_family != AF_INET6)
911                         next: continue;
912
913                 for (i = 0; i < 4; i++) {
914                         if ((IFADDR6(ifa).s6_addr32[i] ^
915                              addr->sin6_addr.s6_addr32[i]) &
916                             IFMASK6(ifa).s6_addr32[i])
917                                 goto next;
918                 }
919                 return (1);
920         }
921
922         /*
923          * Even if the address matches none of our addresses, it might be
924          * in the neighbor cache.
925          */
926         if (nd6_lookup(&addr->sin6_addr, 0, ifp) != NULL)
927                 return (1);
928
929         return (0);
930 #undef IFADDR6
931 #undef IFMASK6
932 }
933
934 /*
935  * Free an nd6 llinfo entry.
936  */
937 struct llinfo_nd6 *
938 nd6_free(struct rtentry *rt)
939 {
940         struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo, *next;
941         struct in6_addr in6 = ((struct sockaddr_in6 *)rt_key(rt))->sin6_addr;
942         struct nd_defrouter *dr;
943
944         /*
945          * we used to have kpfctlinput(PRC_HOSTDEAD) here.
946          * even though it is not harmful, it was not really necessary.
947          */
948
949         if (!ip6_forwarding && ip6_accept_rtadv) { /* XXX: too restrictive? */
950                 mtx_lock(&nd6_mtx);
951                 dr = defrouter_lookup(&((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
952                                       rt->rt_ifp);
953
954                 if (ln->ln_router || dr) {
955                         /*
956                          * rt6_flush must be called whether or not the neighbor
957                          * is in the Default Router List.
958                          * See a corresponding comment in nd6_na_input().
959                          */
960                         rt6_flush(&in6, rt->rt_ifp);
961                 }
962
963                 if (dr) {
964                         /*
965                          * Unreachablity of a router might affect the default
966                          * router selection and on-link detection of advertised
967                          * prefixes.
968                          */
969
970                         /*
971                          * Temporarily fake the state to choose a new default
972                          * router and to perform on-link determination of
973                          * prefixes correctly.
974                          * Below the state will be set correctly,
975                          * or the entry itself will be deleted.
976                          */
977                         ln->ln_state = ND6_LLINFO_INCOMPLETE;
978
979                         /*
980                          * Since defrouter_select() does not affect the
981                          * on-link determination and MIP6 needs the check
982                          * before the default router selection, we perform
983                          * the check now.
984                          */
985                         pfxlist_onlink_check();
986
987                         if (dr == TAILQ_FIRST(&nd_defrouter)) {
988                                 /*
989                                  * It is used as the current default router,
990                                  * so we have to move it to the end of the
991                                  * list and choose a new one.
992                                  * XXX: it is not very efficient if this is
993                                  *      the only router.
994                                  */
995                                 TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
996                                 TAILQ_INSERT_TAIL(&nd_defrouter, dr, dr_entry);
997
998                                 defrouter_select();
999                         }
1000                 }
1001                 mtx_unlock(&nd6_mtx);
1002         }
1003
1004         /*
1005          * Before deleting the entry, remember the next entry as the
1006          * return value.  We need this because pfxlist_onlink_check() above
1007          * might have freed other entries (particularly the old next entry) as
1008          * a side effect (XXX).
1009          */
1010         next = ln->ln_next;
1011
1012         /*
1013          * Detach the route from the routing tree and the list of neighbor
1014          * caches, and disable the route entry not to be used in already
1015          * cached routes.
1016          */
1017         rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt), 0, NULL);
1018
1019         return (next);
1020 }
1021
1022 /*
1023  * Upper-layer reachability hint for Neighbor Unreachability Detection.
1024  *
1025  * XXX cost-effective metods?
1026  */
1027 void
1028 nd6_nud_hint(struct rtentry *rt, struct in6_addr *dst6, int force)
1029 {
1030         struct llinfo_nd6 *ln;
1031
1032         /*
1033          * If the caller specified "rt", use that.  Otherwise, resolve the
1034          * routing table by supplied "dst6".
1035          */
1036         if (!rt) {
1037                 if (!dst6)
1038                         return;
1039                 if (!(rt = nd6_lookup(dst6, 0, NULL)))
1040                         return;
1041         }
1042
1043         if ((rt->rt_flags & RTF_GATEWAY) ||
1044             !(rt->rt_flags & RTF_LLINFO) ||
1045             rt->rt_llinfo == NULL || rt->rt_gateway == NULL ||
1046             rt->rt_gateway->sa_family != AF_LINK) {
1047                 /* This is not a host route. */
1048                 return;
1049         }
1050
1051         ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1052         if (ln->ln_state < ND6_LLINFO_REACHABLE)
1053                 return;
1054
1055         /*
1056          * if we get upper-layer reachability confirmation many times,
1057          * it is possible we have false information.
1058          */
1059         if (!force) {
1060                 ln->ln_byhint++;
1061                 if (ln->ln_byhint > nd6_maxnudhint)
1062                         return;
1063         }
1064
1065         ln->ln_state = ND6_LLINFO_REACHABLE;
1066         if (ln->ln_expire)
1067                 ln->ln_expire = time_uptime +
1068                         ND_IFINFO(rt->rt_ifp)->reachable;
1069 }
1070
1071 void
1072 nd6_rtrequest(int req, struct rtentry *rt)
1073 {
1074         struct sockaddr *gate = rt->rt_gateway;
1075         struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1076         static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1077         struct ifnet *ifp = rt->rt_ifp;
1078         struct ifaddr *ifa;
1079
1080         if ((rt->rt_flags & RTF_GATEWAY))
1081                 return;
1082
1083         if (nd6_need_cache(ifp) == 0 && !(rt->rt_flags & RTF_HOST)) {
1084                 /*
1085                  * This is probably an interface direct route for a link
1086                  * which does not need neighbor caches (e.g. fe80::%lo0/64).
1087                  * We do not need special treatment below for such a route.
1088                  * Moreover, the RTF_LLINFO flag which would be set below
1089                  * would annoy the ndp(8) command.
1090                  */
1091                 return;
1092         }
1093
1094         if (req == RTM_RESOLVE &&
1095             (nd6_need_cache(ifp) == 0 || /* stf case */
1096              !nd6_is_addr_neighbor((struct sockaddr_in6 *)rt_key(rt), ifp))) {
1097                 /*
1098                  * FreeBSD and BSD/OS often make a cloned host route based
1099                  * on a less-specific route (e.g. the default route).
1100                  * If the less specific route does not have a "gateway"
1101                  * (this is the case when the route just goes to a p2p or an
1102                  * stf interface), we'll mistakenly make a neighbor cache for
1103                  * the host route, and will see strange neighbor solicitation
1104                  * for the corresponding destination.  In order to avoid the
1105                  * confusion, we check if the destination of the route is
1106                  * a neighbor in terms of neighbor discovery, and stop the
1107                  * process if not.  Additionally, we remove the LLINFO flag
1108                  * so that ndp(8) will not try to get the neighbor information
1109                  * of the destination.
1110                  */
1111                 rt->rt_flags &= ~RTF_LLINFO;
1112                 return;
1113         }
1114
1115         switch (req) {
1116         case RTM_ADD:
1117                 /*
1118                  * There is no backward compatibility :)
1119                  *
1120                  * if (!(rt->rt_flags & RTF_HOST) &&
1121                  *     SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
1122                  *         rt->rt_flags |= RTF_CLONING;
1123                  */
1124                 if (rt->rt_flags & (RTF_CLONING | RTF_LLINFO)) {
1125                         /*
1126                          * Case 1: This route should come from
1127                          * a route to interface.  RTF_LLINFO flag is set
1128                          * for a host route whose destination should be
1129                          * treated as on-link.
1130                          */
1131                         rt_setgate(rt, rt_key(rt),
1132                                    (struct sockaddr *)&null_sdl,
1133                                    RTL_DONTREPORT);
1134                         gate = rt->rt_gateway;
1135                         SDL(gate)->sdl_type = ifp->if_type;
1136                         SDL(gate)->sdl_index = ifp->if_index;
1137                         if (ln)
1138                                 ln->ln_expire = time_uptime;
1139 #if 1
1140                         if (ln && ln->ln_expire == 0) {
1141                                 /* kludge for desktops */
1142 #if 0
1143                                 kprintf("nd6_rtequest: time.tv_sec is zero; "
1144                                        "treat it as 1\n");
1145 #endif
1146                                 ln->ln_expire = 1;
1147                         }
1148 #endif
1149                         if ((rt->rt_flags & RTF_CLONING))
1150                                 break;
1151                 }
1152                 /*
1153                  * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
1154                  * We don't do that here since llinfo is not ready yet.
1155                  *
1156                  * There are also couple of other things to be discussed:
1157                  * - unsolicited NA code needs improvement beforehand
1158                  * - RFC2461 says we MAY send multicast unsolicited NA
1159                  *   (7.2.6 paragraph 4), however, it also says that we
1160                  *   SHOULD provide a mechanism to prevent multicast NA storm.
1161                  *   we don't have anything like it right now.
1162                  *   note that the mechanism needs a mutual agreement
1163                  *   between proxies, which means that we need to implement
1164                  *   a new protocol, or a new kludge.
1165                  * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
1166                  *   we need to check ip6forwarding before sending it.
1167                  *   (or should we allow proxy ND configuration only for
1168                  *   routers?  there's no mention about proxy ND from hosts)
1169                  */
1170 #if 0
1171                 /* XXX it does not work */
1172                 if (rt->rt_flags & RTF_ANNOUNCE)
1173                         nd6_na_output(ifp,
1174                               &SIN6(rt_key(rt))->sin6_addr,
1175                               &SIN6(rt_key(rt))->sin6_addr,
1176                               ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
1177                               1, NULL);
1178 #endif
1179                 /* FALLTHROUGH */
1180         case RTM_RESOLVE:
1181                 if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
1182                         /*
1183                          * Address resolution isn't necessary for a point to
1184                          * point link, so we can skip this test for a p2p link.
1185                          */
1186                         if (gate->sa_family != AF_LINK ||
1187                             gate->sa_len < sizeof(null_sdl)) {
1188                                 log(LOG_DEBUG,
1189                                     "nd6_rtrequest: bad gateway value: %s\n",
1190                                     if_name(ifp));
1191                                 break;
1192                         }
1193                         SDL(gate)->sdl_type = ifp->if_type;
1194                         SDL(gate)->sdl_index = ifp->if_index;
1195                 }
1196                 if (ln != NULL)
1197                         break;  /* This happens on a route change */
1198                 /*
1199                  * Case 2: This route may come from cloning, or a manual route
1200                  * add with a LL address.
1201                  */
1202                 R_Malloc(ln, struct llinfo_nd6 *, sizeof(*ln));
1203                 rt->rt_llinfo = (caddr_t)ln;
1204                 if (!ln) {
1205                         log(LOG_DEBUG, "nd6_rtrequest: malloc failed\n");
1206                         break;
1207                 }
1208                 nd6_inuse++;
1209                 nd6_allocated++;
1210                 bzero(ln, sizeof(*ln));
1211                 ln->ln_rt = rt;
1212                 /* this is required for "ndp" command. - shin */
1213                 if (req == RTM_ADD) {
1214                         /*
1215                          * gate should have some valid AF_LINK entry,
1216                          * and ln->ln_expire should have some lifetime
1217                          * which is specified by ndp command.
1218                          */
1219                         ln->ln_state = ND6_LLINFO_REACHABLE;
1220                         ln->ln_byhint = 0;
1221                 } else {
1222                         /*
1223                          * When req == RTM_RESOLVE, rt is created and
1224                          * initialized in rtrequest(), so rt_expire is 0.
1225                          */
1226                         ln->ln_state = ND6_LLINFO_NOSTATE;
1227                         ln->ln_expire = time_uptime;
1228                 }
1229                 rt->rt_flags |= RTF_LLINFO;
1230                 ln->ln_next = llinfo_nd6.ln_next;
1231                 llinfo_nd6.ln_next = ln;
1232                 ln->ln_prev = &llinfo_nd6;
1233                 ln->ln_next->ln_prev = ln;
1234
1235                 /*
1236                  * check if rt_key(rt) is one of my address assigned
1237                  * to the interface.
1238                  */
1239                 ifa = (struct ifaddr *)in6ifa_ifpwithaddr(rt->rt_ifp,
1240                                           &SIN6(rt_key(rt))->sin6_addr);
1241                 if (ifa) {
1242                         caddr_t macp = nd6_ifptomac(ifp);
1243                         ln->ln_expire = 0;
1244                         ln->ln_state = ND6_LLINFO_REACHABLE;
1245                         ln->ln_byhint = 0;
1246                         if (macp) {
1247                                 bcopy(macp, LLADDR(SDL(gate)), ifp->if_addrlen);
1248                                 SDL(gate)->sdl_alen = ifp->if_addrlen;
1249                         }
1250                         if (nd6_useloopback) {
1251                                 rt->rt_ifp = &loif[0];  /* XXX */
1252                                 /*
1253                                  * Make sure rt_ifa be equal to the ifaddr
1254                                  * corresponding to the address.
1255                                  * We need this because when we refer
1256                                  * rt_ifa->ia6_flags in ip6_input, we assume
1257                                  * that the rt_ifa points to the address instead
1258                                  * of the loopback address.
1259                                  */
1260                                 if (ifa != rt->rt_ifa) {
1261                                         IFAFREE(rt->rt_ifa);
1262                                         IFAREF(ifa);
1263                                         rt->rt_ifa = ifa;
1264                                 }
1265                         }
1266                 } else if (rt->rt_flags & RTF_ANNOUNCE) {
1267                         ln->ln_expire = 0;
1268                         ln->ln_state = ND6_LLINFO_REACHABLE;
1269                         ln->ln_byhint = 0;
1270
1271                         /* join solicited node multicast for proxy ND */
1272                         if (ifp->if_flags & IFF_MULTICAST) {
1273                                 struct in6_addr llsol;
1274                                 int error;
1275
1276                                 llsol = SIN6(rt_key(rt))->sin6_addr;
1277                                 llsol.s6_addr16[0] = htons(0xff02);
1278                                 llsol.s6_addr16[1] = htons(ifp->if_index);
1279                                 llsol.s6_addr32[1] = 0;
1280                                 llsol.s6_addr32[2] = htonl(1);
1281                                 llsol.s6_addr8[12] = 0xff;
1282
1283                                 if (!in6_addmulti(&llsol, ifp, &error)) {
1284                                         nd6log((LOG_ERR, "%s: failed to join "
1285                                             "%s (errno=%d)\n", if_name(ifp),
1286                                             ip6_sprintf(&llsol), error));
1287                                 }
1288                         }
1289                 }
1290                 break;
1291
1292         case RTM_DELETE:
1293                 if (!ln)
1294                         break;
1295                 /* leave from solicited node multicast for proxy ND */
1296                 if ((rt->rt_flags & RTF_ANNOUNCE) &&
1297                     (ifp->if_flags & IFF_MULTICAST)) {
1298                         struct in6_addr llsol;
1299                         struct in6_multi *in6m;
1300
1301                         llsol = SIN6(rt_key(rt))->sin6_addr;
1302                         llsol.s6_addr16[0] = htons(0xff02);
1303                         llsol.s6_addr16[1] = htons(ifp->if_index);
1304                         llsol.s6_addr32[1] = 0;
1305                         llsol.s6_addr32[2] = htonl(1);
1306                         llsol.s6_addr8[12] = 0xff;
1307
1308                         in6m = IN6_LOOKUP_MULTI(&llsol, ifp);
1309                         if (in6m)
1310                                 in6_delmulti(in6m);
1311                 }
1312                 nd6_inuse--;
1313                 ln->ln_next->ln_prev = ln->ln_prev;
1314                 ln->ln_prev->ln_next = ln->ln_next;
1315                 ln->ln_prev = NULL;
1316                 rt->rt_llinfo = 0;
1317                 rt->rt_flags &= ~RTF_LLINFO;
1318                 if (ln->ln_hold)
1319                         m_freem(ln->ln_hold);
1320                 Free((caddr_t)ln);
1321         }
1322 }
1323
1324 int
1325 nd6_ioctl(u_long cmd, caddr_t   data, struct ifnet *ifp)
1326 {
1327         struct in6_drlist *drl = (struct in6_drlist *)data;
1328         struct in6_prlist *prl = (struct in6_prlist *)data;
1329         struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1330         struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1331         struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1332         struct nd_defrouter *dr, any;
1333         struct nd_prefix *pr;
1334         struct rtentry *rt;
1335         int i = 0, error = 0;
1336
1337         switch (cmd) {
1338         case SIOCGDRLST_IN6:
1339                 /*
1340                  * obsolete API, use sysctl under net.inet6.icmp6
1341                  */
1342                 bzero(drl, sizeof(*drl));
1343                 mtx_lock(&nd6_mtx);
1344                 dr = TAILQ_FIRST(&nd_defrouter);
1345                 while (dr && i < DRLSTSIZ) {
1346                         drl->defrouter[i].rtaddr = dr->rtaddr;
1347                         if (IN6_IS_ADDR_LINKLOCAL(&drl->defrouter[i].rtaddr)) {
1348                                 /* XXX: need to this hack for KAME stack */
1349                                 drl->defrouter[i].rtaddr.s6_addr16[1] = 0;
1350                         } else
1351                                 log(LOG_ERR,
1352                                     "default router list contains a "
1353                                     "non-linklocal address(%s)\n",
1354                                     ip6_sprintf(&drl->defrouter[i].rtaddr));
1355
1356                         drl->defrouter[i].flags = dr->flags;
1357                         drl->defrouter[i].rtlifetime = dr->rtlifetime;
1358                         drl->defrouter[i].expire = dr->expire;
1359                         drl->defrouter[i].if_index = dr->ifp->if_index;
1360                         i++;
1361                         dr = TAILQ_NEXT(dr, dr_entry);
1362                 }
1363                 mtx_unlock(&nd6_mtx);
1364                 break;
1365         case SIOCGPRLST_IN6:
1366                 /*
1367                  * obsolete API, use sysctl under net.inet6.icmp6
1368                  */
1369                 /*
1370                  * XXX meaning of fields, especialy "raflags", is very
1371                  * differnet between RA prefix list and RR/static prefix list.
1372                  * how about separating ioctls into two?
1373                  */
1374                 bzero(prl, sizeof(*prl));
1375                 mtx_lock(&nd6_mtx);
1376                 pr = nd_prefix.lh_first;
1377                 while (pr && i < PRLSTSIZ) {
1378                         struct nd_pfxrouter *pfr;
1379                         int j;
1380
1381                         in6_embedscope(&prl->prefix[i].prefix,
1382                             &pr->ndpr_prefix, NULL, NULL);
1383                         prl->prefix[i].raflags = pr->ndpr_raf;
1384                         prl->prefix[i].prefixlen = pr->ndpr_plen;
1385                         prl->prefix[i].vltime = pr->ndpr_vltime;
1386                         prl->prefix[i].pltime = pr->ndpr_pltime;
1387                         prl->prefix[i].if_index = pr->ndpr_ifp->if_index;
1388                         prl->prefix[i].expire = pr->ndpr_expire;
1389
1390                         pfr = pr->ndpr_advrtrs.lh_first;
1391                         j = 0;
1392                         while (pfr) {
1393                                 if (j < DRLSTSIZ) {
1394 #define RTRADDR prl->prefix[i].advrtr[j]
1395                                         RTRADDR = pfr->router->rtaddr;
1396                                         if (IN6_IS_ADDR_LINKLOCAL(&RTRADDR)) {
1397                                                 /* XXX: hack for KAME */
1398                                                 RTRADDR.s6_addr16[1] = 0;
1399                                         } else
1400                                                 log(LOG_ERR,
1401                                                     "a router(%s) advertises "
1402                                                     "a prefix with "
1403                                                     "non-link local address\n",
1404                                                     ip6_sprintf(&RTRADDR));
1405 #undef RTRADDR
1406                                 }
1407                                 j++;
1408                                 pfr = pfr->pfr_next;
1409                         }
1410                         prl->prefix[i].advrtrs = j;
1411                         prl->prefix[i].origin = PR_ORIG_RA;
1412
1413                         i++;
1414                         pr = pr->ndpr_next;
1415                 }
1416                 mtx_unlock(&nd6_mtx);
1417
1418                 break;
1419         case OSIOCGIFINFO_IN6:
1420                 /* XXX: old ndp(8) assumes a positive value for linkmtu. */
1421                 bzero(&ndi->ndi, sizeof(ndi->ndi));
1422                 ndi->ndi.linkmtu = ND_IFINFO(ifp)->linkmtu;
1423                 ndi->ndi.maxmtu = ND_IFINFO(ifp)->maxmtu;
1424                 ndi->ndi.basereachable = ND_IFINFO(ifp)->basereachable;
1425                 ndi->ndi.reachable = ND_IFINFO(ifp)->reachable;
1426                 ndi->ndi.retrans = ND_IFINFO(ifp)->retrans;
1427                 ndi->ndi.flags = ND_IFINFO(ifp)->flags;
1428                 ndi->ndi.recalctm = ND_IFINFO(ifp)->recalctm;
1429                 ndi->ndi.chlim = ND_IFINFO(ifp)->chlim;
1430                 ndi->ndi.receivedra = ND_IFINFO(ifp)->receivedra;
1431                 break;
1432         case SIOCGIFINFO_IN6:
1433                 ndi->ndi = *ND_IFINFO(ifp);
1434                 break;
1435         case SIOCSIFINFO_FLAGS:
1436                 ND_IFINFO(ifp)->flags = ndi->ndi.flags;
1437                 break;
1438         case SIOCSNDFLUSH_IN6:  /* XXX: the ioctl name is confusing... */
1439                 /* flush default router list */
1440                 /*
1441                  * xxx sumikawa: should not delete route if default
1442                  * route equals to the top of default router list
1443                  */
1444                 bzero(&any, sizeof(any));
1445                 defrouter_delreq(&any, 0);
1446                 defrouter_select();
1447                 /* xxx sumikawa: flush prefix list */
1448                 break;
1449         case SIOCSPFXFLUSH_IN6:
1450             {
1451                 /* flush all the prefix advertised by routers */
1452                 struct nd_prefix *pr, *next;
1453
1454                 mtx_lock(&nd6_mtx);
1455                 for (pr = nd_prefix.lh_first; pr; pr = next) {
1456                         struct in6_ifaddr *ia, *ia_next;
1457
1458                         next = pr->ndpr_next;
1459
1460                         if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1461                                 continue; /* XXX */
1462
1463                         /* do we really have to remove addresses as well? */
1464                         for (ia = in6_ifaddr; ia; ia = ia_next) {
1465                                 /* ia might be removed.  keep the next ptr. */
1466                                 ia_next = ia->ia_next;
1467
1468                                 if (!(ia->ia6_flags & IN6_IFF_AUTOCONF))
1469                                         continue;
1470
1471                                 if (ia->ia6_ndpr == pr)
1472                                         in6_purgeaddr(&ia->ia_ifa);
1473                         }
1474                         prelist_remove(pr);
1475                 }
1476                 mtx_unlock(&nd6_mtx);
1477                 break;
1478             }
1479         case SIOCSRTRFLUSH_IN6:
1480             {
1481                 /* flush all the default routers */
1482                 struct nd_defrouter *dr, *next;
1483
1484                 mtx_lock(&nd6_mtx);
1485                 if ((dr = TAILQ_FIRST(&nd_defrouter)) != NULL) {
1486                         /*
1487                          * The first entry of the list may be stored in
1488                          * the routing table, so we'll delete it later.
1489                          */
1490                         for (dr = TAILQ_NEXT(dr, dr_entry); dr; dr = next) {
1491                                 next = TAILQ_NEXT(dr, dr_entry);
1492                                 defrtrlist_del(dr);
1493                         }
1494                         defrtrlist_del(TAILQ_FIRST(&nd_defrouter));
1495                 }
1496                 mtx_unlock(&nd6_mtx);
1497                 break;
1498             }
1499         case SIOCGNBRINFO_IN6:
1500             {
1501                 struct llinfo_nd6 *ln;
1502                 struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1503
1504                 /*
1505                  * XXX: KAME specific hack for scoped addresses
1506                  *      XXXX: for other scopes than link-local?
1507                  */
1508                 if (IN6_IS_ADDR_LINKLOCAL(&nbi->addr) ||
1509                     IN6_IS_ADDR_MC_LINKLOCAL(&nbi->addr)) {
1510                         u_int16_t *idp = (u_int16_t *)&nb_addr.s6_addr[2];
1511
1512                         if (*idp == 0)
1513                                 *idp = htons(ifp->if_index);
1514                 }
1515
1516                 mtx_lock(&nd6_mtx);
1517                 if ((rt = nd6_lookup(&nb_addr, 0, ifp)) == NULL) {
1518                         error = EINVAL;
1519                         mtx_unlock(&nd6_mtx);
1520                         break;
1521                 }
1522                 ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1523                 nbi->state = ln->ln_state;
1524                 nbi->asked = ln->ln_asked;
1525                 nbi->isrouter = ln->ln_router;
1526                 nbi->expire = ln->ln_expire;
1527                 mtx_unlock(&nd6_mtx);
1528
1529                 break;
1530             }
1531         case SIOCGDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1532                 ndif->ifindex = nd6_defifindex;
1533                 break;
1534         case SIOCSDEFIFACE_IN6: /* XXX: should be implemented as a sysctl? */
1535                 return (nd6_setdefaultiface(ndif->ifindex));
1536                 break;
1537         }
1538         return (error);
1539 }
1540
1541 /*
1542  * Create neighbor cache entry and cache link-layer address,
1543  * on reception of inbound ND6 packets. (RS/RA/NS/redirect)
1544  */
1545 struct rtentry *
1546 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1547                  int lladdrlen,
1548                  int type,      /* ICMP6 type */
1549                  int code       /* type dependent information */)
1550 {
1551         struct rtentry *rt = NULL;
1552         struct llinfo_nd6 *ln = NULL;
1553         int is_newentry;
1554         struct sockaddr_dl *sdl = NULL;
1555         int do_update;
1556         int olladdr;
1557         int llchange;
1558         int newstate = 0;
1559
1560         if (!ifp)
1561                 panic("ifp == NULL in nd6_cache_lladdr");
1562         if (!from)
1563                 panic("from == NULL in nd6_cache_lladdr");
1564
1565         /* nothing must be updated for unspecified address */
1566         if (IN6_IS_ADDR_UNSPECIFIED(from))
1567                 return NULL;
1568
1569         /*
1570          * Validation about ifp->if_addrlen and lladdrlen must be done in
1571          * the caller.
1572          *
1573          * XXX If the link does not have link-layer adderss, what should
1574          * we do? (ifp->if_addrlen == 0)
1575          * Spec says nothing in sections for RA, RS and NA.  There's small
1576          * description on it in NS section (RFC 2461 7.2.3).
1577          */
1578
1579         rt = nd6_lookup(from, 0, ifp);
1580         if (!rt) {
1581 #if 0
1582                 /* nothing must be done if there's no lladdr */
1583                 if (!lladdr || !lladdrlen)
1584                         return NULL;
1585 #endif
1586
1587                 rt = nd6_lookup(from, 1, ifp);
1588                 is_newentry = 1;
1589         } else {
1590                 /* do nothing if static ndp is set */
1591                 if (rt->rt_flags & RTF_STATIC)
1592                         return NULL;
1593                 is_newentry = 0;
1594         }
1595
1596         if (!rt)
1597                 return NULL;
1598         if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
1599 fail:
1600                 nd6_free(rt);
1601                 return NULL;
1602         }
1603         ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1604         if (!ln)
1605                 goto fail;
1606         if (!rt->rt_gateway)
1607                 goto fail;
1608         if (rt->rt_gateway->sa_family != AF_LINK)
1609                 goto fail;
1610         sdl = SDL(rt->rt_gateway);
1611
1612         olladdr = (sdl->sdl_alen) ? 1 : 0;
1613         if (olladdr && lladdr) {
1614                 if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
1615                         llchange = 1;
1616                 else
1617                         llchange = 0;
1618         } else
1619                 llchange = 0;
1620
1621         /*
1622          * newentry olladdr  lladdr  llchange   (*=record)
1623          *      0       n       n       --      (1)
1624          *      0       y       n       --      (2)
1625          *      0       n       y       --      (3) * STALE
1626          *      0       y       y       n       (4) *
1627          *      0       y       y       y       (5) * STALE
1628          *      1       --      n       --      (6)   NOSTATE(= PASSIVE)
1629          *      1       --      y       --      (7) * STALE
1630          */
1631
1632         if (lladdr) {           /* (3-5) and (7) */
1633                 /*
1634                  * Record source link-layer address
1635                  * XXX is it dependent to ifp->if_type?
1636                  */
1637                 sdl->sdl_alen = ifp->if_addrlen;
1638                 bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1639         }
1640
1641         if (!is_newentry) {
1642                 if ((!olladdr && lladdr)                /* (3) */
1643                  || (olladdr && lladdr && llchange)) {  /* (5) */
1644                         do_update = 1;
1645                         newstate = ND6_LLINFO_STALE;
1646                 } else                                  /* (1-2,4) */
1647                         do_update = 0;
1648         } else {
1649                 do_update = 1;
1650                 if (!lladdr)                            /* (6) */
1651                         newstate = ND6_LLINFO_NOSTATE;
1652                 else                                    /* (7) */
1653                         newstate = ND6_LLINFO_STALE;
1654         }
1655
1656         if (do_update) {
1657                 /*
1658                  * Update the state of the neighbor cache.
1659                  */
1660                 ln->ln_state = newstate;
1661
1662                 if (ln->ln_state == ND6_LLINFO_STALE) {
1663                         /*
1664                          * XXX: since nd6_output() below will cause
1665                          * state tansition to DELAY and reset the timer,
1666                          * we must set the timer now, although it is actually
1667                          * meaningless.
1668                          */
1669                         ln->ln_expire = time_uptime + nd6_gctimer;
1670
1671                         if (ln->ln_hold) {
1672                                 /*
1673                                  * we assume ifp is not a p2p here, so just
1674                                  * set the 2nd argument as the 1st one.
1675                                  */
1676                                 nd6_output(ifp, ifp, ln->ln_hold,
1677                                            (struct sockaddr_in6 *)rt_key(rt),
1678                                            rt);
1679                                 ln->ln_hold = NULL;
1680                         }
1681                 } else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1682                         /* probe right away */
1683                         ln->ln_expire = time_uptime;
1684                 }
1685         }
1686
1687         /*
1688          * ICMP6 type dependent behavior.
1689          *
1690          * NS: clear IsRouter if new entry
1691          * RS: clear IsRouter
1692          * RA: set IsRouter if there's lladdr
1693          * redir: clear IsRouter if new entry
1694          *
1695          * RA case, (1):
1696          * The spec says that we must set IsRouter in the following cases:
1697          * - If lladdr exist, set IsRouter.  This means (1-5).
1698          * - If it is old entry (!newentry), set IsRouter.  This means (7).
1699          * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1700          * A quetion arises for (1) case.  (1) case has no lladdr in the
1701          * neighbor cache, this is similar to (6).
1702          * This case is rare but we figured that we MUST NOT set IsRouter.
1703          *
1704          * newentry olladdr  lladdr  llchange       NS  RS  RA  redir
1705          *                                                      D R
1706          *      0       n       n       --      (1)     c   ?     s
1707          *      0       y       n       --      (2)     c   s     s
1708          *      0       n       y       --      (3)     c   s     s
1709          *      0       y       y       n       (4)     c   s     s
1710          *      0       y       y       y       (5)     c   s     s
1711          *      1       --      n       --      (6) c   c       c s
1712          *      1       --      y       --      (7) c   c   s   c s
1713          *
1714          *                                      (c=clear s=set)
1715          */
1716         switch (type & 0xff) {
1717         case ND_NEIGHBOR_SOLICIT:
1718                 /*
1719                  * New entry must have is_router flag cleared.
1720                  */
1721                 if (is_newentry)        /* (6-7) */
1722                         ln->ln_router = 0;
1723                 break;
1724         case ND_REDIRECT:
1725                 /*
1726                  * If the icmp is a redirect to a better router, always set the
1727                  * is_router flag. Otherwise, if the entry is newly created,
1728                  * clear the flag. [RFC 2461, sec 8.3]
1729                  */
1730                 if (code == ND_REDIRECT_ROUTER)
1731                         ln->ln_router = 1;
1732                 else if (is_newentry) /* (6-7) */
1733                         ln->ln_router = 0;
1734                 break;
1735         case ND_ROUTER_SOLICIT:
1736                 /*
1737                  * is_router flag must always be cleared.
1738                  */
1739                 ln->ln_router = 0;
1740                 break;
1741         case ND_ROUTER_ADVERT:
1742                 /*
1743                  * Mark an entry with lladdr as a router.
1744                  */
1745                 if ((!is_newentry && (olladdr || lladdr))       /* (2-5) */
1746                  || (is_newentry && lladdr)) {                  /* (7) */
1747                         ln->ln_router = 1;
1748                 }
1749                 break;
1750         }
1751
1752         /*
1753          * When the link-layer address of a router changes, select the
1754          * best router again.  In particular, when the neighbor entry is newly
1755          * created, it might affect the selection policy.
1756          * Question: can we restrict the first condition to the "is_newentry"
1757          * case?
1758          * XXX: when we hear an RA from a new router with the link-layer
1759          * address option, defrouter_select() is called twice, since
1760          * defrtrlist_update called the function as well.  However, I believe
1761          * we can compromise the overhead, since it only happens the first
1762          * time.
1763          * XXX: although defrouter_select() should not have a bad effect
1764          * for those are not autoconfigured hosts, we explicitly avoid such
1765          * cases for safety.
1766          */
1767         if (do_update && ln->ln_router && !ip6_forwarding && ip6_accept_rtadv)
1768                 defrouter_select();
1769
1770         return rt;
1771 }
1772
1773 static void
1774 nd6_slowtimo(void *ignored_arg)
1775 {
1776         struct nd_ifinfo *nd6if;
1777         struct ifnet *ifp;
1778
1779         mtx_lock(&nd6_mtx);
1780         callout_reset(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
1781                         nd6_slowtimo, NULL);
1782         for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list)) {
1783                 if (ifp->if_afdata[AF_INET6] == NULL)
1784                         continue;
1785                 nd6if = ND_IFINFO(ifp);
1786                 if (nd6if->basereachable && /* already initialized */
1787                     (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1788                         /*
1789                          * Since reachable time rarely changes by router
1790                          * advertisements, we SHOULD insure that a new random
1791                          * value gets recomputed at least once every few hours.
1792                          * (RFC 2461, 6.3.4)
1793                          */
1794                         nd6if->recalctm = nd6_recalc_reachtm_interval;
1795                         nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1796                 }
1797         }
1798         mtx_unlock(&nd6_mtx);
1799 }
1800
1801 #define gotoerr(e) { error = (e); goto bad;}
1802
1803 int
1804 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
1805            struct sockaddr_in6 *dst, struct rtentry *rt)
1806 {
1807         struct llinfo_nd6 *ln = NULL;
1808         int error = 0;
1809
1810         if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1811                 goto sendpkt;
1812
1813         if (nd6_need_cache(ifp) == 0)
1814                 goto sendpkt;
1815
1816         /*
1817          * next hop determination.  This routine is derived from ether_outpout.
1818          */
1819         if (rt != NULL) {
1820                 if (!(rt->rt_flags & RTF_UP)) {
1821                         rt = rtlookup((struct sockaddr *)dst);
1822                         if (rt == NULL)
1823                                 gotoerr(EHOSTUNREACH);
1824                         rt->rt_refcnt--;
1825                         if (rt->rt_ifp != ifp) {
1826                                 /* XXX: loop care? */
1827                                 return nd6_output(ifp, origifp, m, dst, rt);
1828                         }
1829                 }
1830                 if (rt->rt_flags & RTF_GATEWAY) {
1831                         struct sockaddr_in6 *gw6;
1832
1833                         /*
1834                          * We skip link-layer address resolution and NUD
1835                          * if the gateway is not a neighbor from ND point
1836                          * of view, regardless of the value of nd_ifinfo.flags.
1837                          * The second condition is a bit tricky; we skip
1838                          * if the gateway is our own address, which is
1839                          * sometimes used to install a route to a p2p link.
1840                          */
1841                         gw6 = (struct sockaddr_in6 *)rt->rt_gateway;
1842                         if (!nd6_is_addr_neighbor(gw6, ifp) ||
1843                             in6ifa_ifpwithaddr(ifp, &gw6->sin6_addr)) {
1844                                 /*
1845                                  * We allow this kind of tricky route only
1846                                  * when the outgoing interface is p2p.
1847                                  * XXX: we may need a more generic rule here.
1848                                  */
1849                                 if (!(ifp->if_flags & IFF_POINTOPOINT))
1850                                         gotoerr(EHOSTUNREACH);
1851
1852                                 goto sendpkt;
1853                         }
1854
1855                         if (rt->rt_gwroute == NULL) {
1856                                 rt->rt_gwroute = rtlookup(rt->rt_gateway);
1857                                 if (rt->rt_gwroute == NULL)
1858                                         gotoerr(EHOSTUNREACH);
1859                         } else if (!(rt->rt_gwroute->rt_flags & RTF_UP)) {
1860                                 rtfree(rt->rt_gwroute);
1861                                 rt->rt_gwroute = rtlookup(rt->rt_gateway);
1862                                 if (rt->rt_gwroute == NULL)
1863                                         gotoerr(EHOSTUNREACH);
1864                         }
1865                 }
1866         }
1867
1868         /*
1869          * Address resolution or Neighbor Unreachability Detection
1870          * for the next hop.
1871          * At this point, the destination of the packet must be a unicast
1872          * or an anycast address(i.e. not a multicast).
1873          */
1874
1875         /* Look up the neighbor cache for the nexthop */
1876         if (rt && (rt->rt_flags & RTF_LLINFO))
1877                 ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1878         else {
1879                 /*
1880                  * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
1881                  * the condition below is not very efficient.  But we believe
1882                  * it is tolerable, because this should be a rare case.
1883                  */
1884                 if (nd6_is_addr_neighbor(dst, ifp) &&
1885                     (rt = nd6_lookup(&dst->sin6_addr, 1, ifp)) != NULL)
1886                         ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1887         }
1888         if (!ln || !rt) {
1889                 if (!(ifp->if_flags & IFF_POINTOPOINT) &&
1890                     !(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
1891                         log(LOG_DEBUG,
1892                             "nd6_output: can't allocate llinfo for %s "
1893                             "(ln=%p, rt=%p)\n",
1894                             ip6_sprintf(&dst->sin6_addr), ln, rt);
1895                         gotoerr(EIO);   /* XXX: good error? */
1896                 }
1897
1898                 goto sendpkt;   /* send anyway */
1899         }
1900
1901         /* We don't have to do link-layer address resolution on a p2p link. */
1902         if ((ifp->if_flags & IFF_POINTOPOINT) &&
1903             ln->ln_state < ND6_LLINFO_REACHABLE) {
1904                 ln->ln_state = ND6_LLINFO_STALE;
1905                 ln->ln_expire = time_uptime + nd6_gctimer;
1906         }
1907
1908         /*
1909          * The first time we send a packet to a neighbor whose entry is
1910          * STALE, we have to change the state to DELAY and a sets a timer to
1911          * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
1912          * neighbor unreachability detection on expiration.
1913          * (RFC 2461 7.3.3)
1914          */
1915         if (ln->ln_state == ND6_LLINFO_STALE) {
1916                 ln->ln_asked = 0;
1917                 ln->ln_state = ND6_LLINFO_DELAY;
1918                 ln->ln_expire = time_uptime + nd6_delay;
1919         }
1920
1921         /*
1922          * If the neighbor cache entry has a state other than INCOMPLETE
1923          * (i.e. its link-layer address is already resolved), just
1924          * send the packet.
1925          */
1926         if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
1927                 goto sendpkt;
1928
1929         /*
1930          * There is a neighbor cache entry, but no ethernet address
1931          * response yet.  Replace the held mbuf (if any) with this
1932          * latest one.
1933          *
1934          * This code conforms to the rate-limiting rule described in Section
1935          * 7.2.2 of RFC 2461, because the timer is set correctly after sending
1936          * an NS below.
1937          */
1938         if (ln->ln_state == ND6_LLINFO_NOSTATE)
1939                 ln->ln_state = ND6_LLINFO_INCOMPLETE;
1940         if (ln->ln_hold)
1941                 m_freem(ln->ln_hold);
1942         ln->ln_hold = m;
1943         if (ln->ln_expire) {
1944                 if (ln->ln_asked < nd6_mmaxtries &&
1945                     ln->ln_expire < time_uptime) {
1946                         ln->ln_asked++;
1947                         ln->ln_expire = time_uptime +
1948                                 ND_IFINFO(ifp)->retrans / 1000;
1949                         nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, 0);
1950                 }
1951         }
1952         return (0);
1953
1954 sendpkt:
1955         if (ifp->if_flags & IFF_LOOPBACK)
1956                 error = ifp->if_output(origifp, m, (struct sockaddr *)dst, rt);
1957         else
1958                 error = ifp->if_output(ifp, m, (struct sockaddr *)dst, rt);
1959         return (error);
1960
1961 bad:
1962         m_freem(m);
1963         return (error);
1964 }
1965 #undef gotoerr
1966
1967 int
1968 nd6_need_cache(struct ifnet *ifp)
1969 {
1970         /*
1971          * XXX: we currently do not make neighbor cache on any interface
1972          * other than Ethernet and GIF.
1973          *
1974          * RFC2893 says:
1975          * - unidirectional tunnels needs no ND
1976          */
1977         switch (ifp->if_type) {
1978         case IFT_ETHER:
1979         case IFT_IEEE1394:
1980 #ifdef IFT_L2VLAN
1981         case IFT_L2VLAN:
1982 #endif
1983 #ifdef IFT_IEEE80211
1984         case IFT_IEEE80211:
1985 #endif
1986 #ifdef IFT_CARP
1987         case IFT_CARP:
1988 #endif
1989         case IFT_GIF:           /* XXX need more cases? */
1990                 return (1);
1991         default:
1992                 return (0);
1993         }
1994 }
1995
1996 int
1997 nd6_storelladdr(struct ifnet *ifp, struct rtentry *rt0, struct mbuf *m,
1998                 struct sockaddr *dst, u_char *desten)
1999 {
2000         struct sockaddr_dl *sdl;
2001         struct rtentry *rt;
2002
2003
2004         if (m->m_flags & M_MCAST) {
2005                 switch (ifp->if_type) {
2006                 case IFT_ETHER:
2007 #ifdef IFT_L2VLAN
2008         case IFT_L2VLAN:
2009 #endif
2010 #ifdef IFT_IEEE80211
2011                 case IFT_IEEE80211:
2012 #endif
2013                         ETHER_MAP_IPV6_MULTICAST(&SIN6(dst)->sin6_addr,
2014                                                  desten);
2015                         return (1);
2016                 case IFT_IEEE1394:
2017                         bcopy(ifp->if_broadcastaddr, desten, ifp->if_addrlen);
2018                         return (1);
2019                 default:
2020                         m_freem(m);
2021                         return (0);
2022                 }
2023         }
2024         if (rt0 == NULL) {
2025                 /* this could happen, if we could not allocate memory */
2026                 m_freem(m);
2027                 return (0);
2028         }
2029         if (rt_llroute(dst, rt0, &rt) != 0) {
2030                 m_freem(m);
2031                 return (0);
2032         }
2033         if (rt->rt_gateway->sa_family != AF_LINK) {
2034                 kprintf("nd6_storelladdr: something odd happens\n");
2035                 m_freem(m);
2036                 return (0);
2037         }
2038         sdl = SDL(rt->rt_gateway);
2039         if (sdl->sdl_alen == 0) {
2040                 /* this should be impossible, but we bark here for debugging */
2041                 kprintf("nd6_storelladdr: sdl_alen == 0\n");
2042                 m_freem(m);
2043                 return (0);
2044         }
2045
2046         bcopy(LLADDR(sdl), desten, sdl->sdl_alen);
2047         return (1);
2048 }
2049
2050 static int nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS);
2051 static int nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS);
2052 #ifdef SYSCTL_DECL
2053 SYSCTL_DECL(_net_inet6_icmp6);
2054 #endif
2055 SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2056         CTLFLAG_RD, nd6_sysctl_drlist, "List default routers");
2057 SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2058         CTLFLAG_RD, nd6_sysctl_prlist, "List prefixes");
2059
2060 static int
2061 nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2062 {
2063         int error;
2064         char buf[1024];
2065         struct in6_defrouter *d, *de;
2066         struct nd_defrouter *dr;
2067
2068         if (req->newptr)
2069                 return EPERM;
2070         error = 0;
2071
2072         for (dr = TAILQ_FIRST(&nd_defrouter);
2073              dr;
2074              dr = TAILQ_NEXT(dr, dr_entry)) {
2075                 d = (struct in6_defrouter *)buf;
2076                 de = (struct in6_defrouter *)(buf + sizeof(buf));
2077
2078                 if (d + 1 <= de) {
2079                         bzero(d, sizeof(*d));
2080                         d->rtaddr.sin6_family = AF_INET6;
2081                         d->rtaddr.sin6_len = sizeof(d->rtaddr);
2082                         if (in6_recoverscope(&d->rtaddr, &dr->rtaddr,
2083                             dr->ifp) != 0)
2084                                 log(LOG_ERR,
2085                                     "scope error in "
2086                                     "default router list (%s)\n",
2087                                     ip6_sprintf(&dr->rtaddr));
2088                         d->flags = dr->flags;
2089                         d->rtlifetime = dr->rtlifetime;
2090                         d->expire = dr->expire;
2091                         d->if_index = dr->ifp->if_index;
2092                 } else
2093                         panic("buffer too short");
2094
2095                 error = SYSCTL_OUT(req, buf, sizeof(*d));
2096                 if (error)
2097                         break;
2098         }
2099         return error;
2100 }
2101
2102 static int
2103 nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2104 {
2105         int error;
2106         char buf[1024];
2107         struct in6_prefix *p, *pe;
2108         struct nd_prefix *pr;
2109
2110         if (req->newptr)
2111                 return EPERM;
2112         error = 0;
2113
2114         for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
2115                 u_short advrtrs;
2116                 size_t advance;
2117                 struct sockaddr_in6 *sin6, *s6;
2118                 struct nd_pfxrouter *pfr;
2119
2120                 p = (struct in6_prefix *)buf;
2121                 pe = (struct in6_prefix *)(buf + sizeof(buf));
2122
2123                 if (p + 1 <= pe) {
2124                         bzero(p, sizeof(*p));
2125                         sin6 = (struct sockaddr_in6 *)(p + 1);
2126
2127                         p->prefix = pr->ndpr_prefix;
2128                         if (in6_recoverscope(&p->prefix,
2129                             &p->prefix.sin6_addr, pr->ndpr_ifp) != 0)
2130                                 log(LOG_ERR,
2131                                     "scope error in prefix list (%s)\n",
2132                                     ip6_sprintf(&p->prefix.sin6_addr));
2133                         p->raflags = pr->ndpr_raf;
2134                         p->prefixlen = pr->ndpr_plen;
2135                         p->vltime = pr->ndpr_vltime;
2136                         p->pltime = pr->ndpr_pltime;
2137                         p->if_index = pr->ndpr_ifp->if_index;
2138                         p->expire = pr->ndpr_expire;
2139                         p->refcnt = pr->ndpr_refcnt;
2140                         p->flags = pr->ndpr_stateflags;
2141                         p->origin = PR_ORIG_RA;
2142                         advrtrs = 0;
2143                         for (pfr = pr->ndpr_advrtrs.lh_first;
2144                              pfr;
2145                              pfr = pfr->pfr_next) {
2146                                 if ((void *)&sin6[advrtrs + 1] >
2147                                     (void *)pe) {
2148                                         advrtrs++;
2149                                         continue;
2150                                 }
2151                                 s6 = &sin6[advrtrs];
2152                                 bzero(s6, sizeof(*s6));
2153                                 s6->sin6_family = AF_INET6;
2154                                 s6->sin6_len = sizeof(*sin6);
2155                                 if (in6_recoverscope(s6, &pfr->router->rtaddr,
2156                                                      pfr->router->ifp) != 0)
2157                                         log(LOG_ERR,
2158                                             "scope error in "
2159                                             "prefix list (%s)\n",
2160                                             ip6_sprintf(&pfr->router->rtaddr));
2161                                 advrtrs++;
2162                         }
2163                         p->advrtrs = advrtrs;
2164                 } else
2165                         panic("buffer too short");
2166
2167                 advance = sizeof(*p) + sizeof(*sin6) * advrtrs;
2168                 error = SYSCTL_OUT(req, buf, advance);
2169                 if (error)
2170                         break;
2171         }
2172         return error;
2173 }