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