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