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