xref: /openbsd-src/sys/netinet6/nd6.c (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
1 /*	$OpenBSD: nd6.c,v 1.235 2021/03/08 16:49:07 florian Exp $	*/
2 /*	$KAME: nd6.c,v 1.280 2002/06/08 19:52:07 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 <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/timeout.h>
36 #include <sys/malloc.h>
37 #include <sys/mbuf.h>
38 #include <sys/socket.h>
39 #include <sys/sockio.h>
40 #include <sys/time.h>
41 #include <sys/kernel.h>
42 #include <sys/pool.h>
43 #include <sys/protosw.h>
44 #include <sys/errno.h>
45 #include <sys/ioctl.h>
46 #include <sys/syslog.h>
47 #include <sys/queue.h>
48 #include <sys/stdint.h>
49 #include <sys/task.h>
50 
51 #include <net/if.h>
52 #include <net/if_dl.h>
53 #include <net/if_types.h>
54 #include <net/route.h>
55 
56 #include <netinet/in.h>
57 #include <netinet/if_ether.h>
58 #include <netinet/ip_ipsp.h>
59 
60 #include <netinet6/in6_var.h>
61 #include <netinet/ip6.h>
62 #include <netinet6/ip6_var.h>
63 #include <netinet6/nd6.h>
64 #include <netinet/icmp6.h>
65 
66 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
67 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
68 
69 /* timer values */
70 int	nd6_timer_next	= -1;	/* at which uptime nd6_timer runs */
71 time_t	nd6_expire_next	= -1;	/* at which uptime nd6_expire runs */
72 int	nd6_delay	= 5;	/* delay first probe time 5 second */
73 int	nd6_umaxtries	= 3;	/* maximum unicast query */
74 int	nd6_mmaxtries	= 3;	/* maximum multicast query */
75 int	nd6_gctimer	= (60 * 60 * 24); /* 1 day: garbage collection timer */
76 
77 /* preventing too many loops in ND option parsing */
78 int nd6_maxndopt = 10;	/* max # of ND options allowed */
79 
80 int nd6_maxnudhint = 0;	/* max # of subsequent upper layer hints */
81 
82 #ifdef ND6_DEBUG
83 int nd6_debug = 1;
84 #else
85 int nd6_debug = 0;
86 #endif
87 
88 TAILQ_HEAD(llinfo_nd6_head, llinfo_nd6) nd6_list;
89 struct	pool nd6_pool;		/* pool for llinfo_nd6 structures */
90 int	nd6_inuse, nd6_allocated;
91 
92 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
93 
94 void nd6_timer(void *);
95 void nd6_slowtimo(void *);
96 void nd6_expire(void *);
97 void nd6_expire_timer(void *);
98 void nd6_invalidate(struct rtentry *);
99 void nd6_free(struct rtentry *);
100 int nd6_llinfo_timer(struct rtentry *);
101 
102 struct timeout nd6_timer_to;
103 struct timeout nd6_slowtimo_ch;
104 struct timeout nd6_expire_timeout;
105 struct task nd6_expire_task;
106 
107 void
108 nd6_init(void)
109 {
110 	static int nd6_init_done = 0;
111 
112 	if (nd6_init_done) {
113 		log(LOG_NOTICE, "%s called more than once\n", __func__);
114 		return;
115 	}
116 
117 	TAILQ_INIT(&nd6_list);
118 	pool_init(&nd6_pool, sizeof(struct llinfo_nd6), 0,
119 	    IPL_SOFTNET, 0, "nd6", NULL);
120 
121 	task_set(&nd6_expire_task, nd6_expire, NULL);
122 
123 	nd6_init_done = 1;
124 
125 	/* start timer */
126 	timeout_set_proc(&nd6_timer_to, nd6_timer, &nd6_timer_to);
127 	timeout_set_proc(&nd6_slowtimo_ch, nd6_slowtimo, NULL);
128 	timeout_add_sec(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL);
129 	timeout_set(&nd6_expire_timeout, nd6_expire_timer, NULL);
130 }
131 
132 struct nd_ifinfo *
133 nd6_ifattach(struct ifnet *ifp)
134 {
135 	struct nd_ifinfo *nd;
136 
137 	nd = malloc(sizeof(*nd), M_IP6NDP, M_WAITOK | M_ZERO);
138 
139 	nd->initialized = 1;
140 
141 	nd->basereachable = REACHABLE_TIME;
142 	nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
143 	nd->retrans = RETRANS_TIMER;
144 
145 	return nd;
146 }
147 
148 void
149 nd6_ifdetach(struct nd_ifinfo *nd)
150 {
151 
152 	free(nd, M_IP6NDP, sizeof(*nd));
153 }
154 
155 void
156 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
157 {
158 	bzero(ndopts, sizeof(*ndopts));
159 	ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
160 	ndopts->nd_opts_last
161 		= (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
162 
163 	if (icmp6len == 0) {
164 		ndopts->nd_opts_done = 1;
165 		ndopts->nd_opts_search = NULL;
166 	}
167 }
168 
169 /*
170  * Take one ND option.
171  */
172 struct nd_opt_hdr *
173 nd6_option(union nd_opts *ndopts)
174 {
175 	struct nd_opt_hdr *nd_opt;
176 	int olen;
177 
178 	if (!ndopts)
179 		panic("%s: ndopts == NULL", __func__);
180 	if (!ndopts->nd_opts_last)
181 		panic("%s: uninitialized ndopts", __func__);
182 	if (!ndopts->nd_opts_search)
183 		return NULL;
184 	if (ndopts->nd_opts_done)
185 		return NULL;
186 
187 	nd_opt = ndopts->nd_opts_search;
188 
189 	/* make sure nd_opt_len is inside the buffer */
190 	if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
191 		bzero(ndopts, sizeof(*ndopts));
192 		return NULL;
193 	}
194 
195 	olen = nd_opt->nd_opt_len << 3;
196 	if (olen == 0) {
197 		/*
198 		 * Message validation requires that all included
199 		 * options have a length that is greater than zero.
200 		 */
201 		bzero(ndopts, sizeof(*ndopts));
202 		return NULL;
203 	}
204 
205 	ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
206 	if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
207 		/* option overruns the end of buffer, invalid */
208 		bzero(ndopts, sizeof(*ndopts));
209 		return NULL;
210 	} else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
211 		/* reached the end of options chain */
212 		ndopts->nd_opts_done = 1;
213 		ndopts->nd_opts_search = NULL;
214 	}
215 	return nd_opt;
216 }
217 
218 /*
219  * Parse multiple ND options.
220  * This function is much easier to use, for ND routines that do not need
221  * multiple options of the same type.
222  */
223 int
224 nd6_options(union nd_opts *ndopts)
225 {
226 	struct nd_opt_hdr *nd_opt;
227 	int i = 0;
228 
229 	if (!ndopts)
230 		panic("%s: ndopts == NULL", __func__);
231 	if (!ndopts->nd_opts_last)
232 		panic("%s: uninitialized ndopts", __func__);
233 	if (!ndopts->nd_opts_search)
234 		return 0;
235 
236 	while (1) {
237 		nd_opt = nd6_option(ndopts);
238 		if (!nd_opt && !ndopts->nd_opts_last) {
239 			/*
240 			 * Message validation requires that all included
241 			 * options have a length that is greater than zero.
242 			 */
243 			icmp6stat_inc(icp6s_nd_badopt);
244 			bzero(ndopts, sizeof(*ndopts));
245 			return -1;
246 		}
247 
248 		if (!nd_opt)
249 			goto skip1;
250 
251 		switch (nd_opt->nd_opt_type) {
252 		case ND_OPT_SOURCE_LINKADDR:
253 		case ND_OPT_TARGET_LINKADDR:
254 		case ND_OPT_MTU:
255 		case ND_OPT_REDIRECTED_HEADER:
256 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
257 				nd6log((LOG_INFO,
258 				    "duplicated ND6 option found (type=%d)\n",
259 				    nd_opt->nd_opt_type));
260 				/* XXX bark? */
261 			} else {
262 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
263 					= nd_opt;
264 			}
265 			break;
266 		case ND_OPT_PREFIX_INFORMATION:
267 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
268 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
269 					= nd_opt;
270 			}
271 			ndopts->nd_opts_pi_end =
272 				(struct nd_opt_prefix_info *)nd_opt;
273 			break;
274 		default:
275 			/*
276 			 * Unknown options must be silently ignored,
277 			 * to accommodate future extension to the protocol.
278 			 */
279 			nd6log((LOG_DEBUG,
280 			    "nd6_options: unsupported option %d - "
281 			    "option ignored\n", nd_opt->nd_opt_type));
282 		}
283 
284 skip1:
285 		i++;
286 		if (i > nd6_maxndopt) {
287 			icmp6stat_inc(icp6s_nd_toomanyopt);
288 			nd6log((LOG_INFO, "too many loop in nd opt\n"));
289 			break;
290 		}
291 
292 		if (ndopts->nd_opts_done)
293 			break;
294 	}
295 
296 	return 0;
297 }
298 
299 /*
300  * ND6 timer routine to handle ND6 entries
301  */
302 void
303 nd6_llinfo_settimer(struct llinfo_nd6 *ln, unsigned int secs)
304 {
305 	time_t expire = getuptime() + secs;
306 
307 	NET_ASSERT_LOCKED();
308 	KASSERT(!ISSET(ln->ln_rt->rt_flags, RTF_LOCAL));
309 
310 	ln->ln_rt->rt_expire = expire;
311 	if (!timeout_pending(&nd6_timer_to) || expire < nd6_timer_next) {
312 		nd6_timer_next = expire;
313 		timeout_add_sec(&nd6_timer_to, secs);
314 	}
315 }
316 
317 void
318 nd6_timer(void *arg)
319 {
320 	struct llinfo_nd6 *ln, *nln;
321 	time_t expire = getuptime() + nd6_gctimer;
322 	int secs;
323 
324 	NET_LOCK();
325 	TAILQ_FOREACH_SAFE(ln, &nd6_list, ln_list, nln) {
326 		struct rtentry *rt = ln->ln_rt;
327 
328 		if (rt->rt_expire && rt->rt_expire <= getuptime())
329 			if (nd6_llinfo_timer(rt))
330 				continue;
331 
332 		if (rt->rt_expire && rt->rt_expire < expire)
333 			expire = rt->rt_expire;
334 	}
335 
336 	secs = expire - getuptime();
337 	if (secs < 0)
338 		secs = 0;
339 	if (!TAILQ_EMPTY(&nd6_list)) {
340 		nd6_timer_next = getuptime() + secs;
341 		timeout_add_sec(&nd6_timer_to, secs);
342 	}
343 
344 	NET_UNLOCK();
345 }
346 
347 /*
348  * ND timer state handling.
349  *
350  * Returns 1 if `rt' should no longer be used, 0 otherwise.
351  */
352 int
353 nd6_llinfo_timer(struct rtentry *rt)
354 {
355 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
356 	struct sockaddr_in6 *dst = satosin6(rt_key(rt));
357 	struct ifnet *ifp;
358 	struct nd_ifinfo *ndi = NULL;
359 
360 	NET_ASSERT_LOCKED();
361 
362 	if ((ifp = if_get(rt->rt_ifidx)) == NULL)
363 		return 1;
364 
365 	ndi = ND_IFINFO(ifp);
366 
367 	switch (ln->ln_state) {
368 	case ND6_LLINFO_INCOMPLETE:
369 		if (ln->ln_asked < nd6_mmaxtries) {
370 			ln->ln_asked++;
371 			nd6_llinfo_settimer(ln, ndi->retrans / 1000);
372 			nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, 0);
373 		} else {
374 			struct mbuf *m = ln->ln_hold;
375 			if (m) {
376 				ln->ln_hold = NULL;
377 				/*
378 				 * Fake rcvif to make the ICMP error
379 				 * more helpful in diagnosing for the
380 				 * receiver.
381 				 * XXX: should we consider
382 				 * older rcvif?
383 				 */
384 				m->m_pkthdr.ph_ifidx = rt->rt_ifidx;
385 
386 				icmp6_error(m, ICMP6_DST_UNREACH,
387 				    ICMP6_DST_UNREACH_ADDR, 0);
388 				if (ln->ln_hold == m) {
389 					/* m is back in ln_hold. Discard. */
390 					m_freem(ln->ln_hold);
391 					ln->ln_hold = NULL;
392 				}
393 			}
394 			nd6_free(rt);
395 			ln = NULL;
396 		}
397 		break;
398 	case ND6_LLINFO_REACHABLE:
399 		if (!ND6_LLINFO_PERMANENT(ln)) {
400 			ln->ln_state = ND6_LLINFO_STALE;
401 			nd6_llinfo_settimer(ln, nd6_gctimer);
402 		}
403 		break;
404 
405 	case ND6_LLINFO_STALE:
406 	case ND6_LLINFO_PURGE:
407 		/* Garbage Collection(RFC 2461 5.3) */
408 		if (!ND6_LLINFO_PERMANENT(ln)) {
409 			nd6_free(rt);
410 			ln = NULL;
411 		}
412 		break;
413 
414 	case ND6_LLINFO_DELAY:
415 		if (ndi) {
416 			/* We need NUD */
417 			ln->ln_asked = 1;
418 			ln->ln_state = ND6_LLINFO_PROBE;
419 			nd6_llinfo_settimer(ln, ndi->retrans / 1000);
420 			nd6_ns_output(ifp, &dst->sin6_addr,
421 			    &dst->sin6_addr, ln, 0);
422 		}
423 		break;
424 	case ND6_LLINFO_PROBE:
425 		if (ln->ln_asked < nd6_umaxtries) {
426 			ln->ln_asked++;
427 			nd6_llinfo_settimer(ln, ndi->retrans / 1000);
428 			nd6_ns_output(ifp, &dst->sin6_addr,
429 			    &dst->sin6_addr, ln, 0);
430 		} else {
431 			nd6_free(rt);
432 			ln = NULL;
433 		}
434 		break;
435 	}
436 
437 	if_put(ifp);
438 
439 	return (ln == NULL);
440 }
441 
442 void
443 nd6_expire_timer_update(struct in6_ifaddr *ia6)
444 {
445 	time_t expire_time = INT64_MAX;
446 	int secs;
447 
448 	KERNEL_ASSERT_LOCKED();
449 
450 	if (ia6->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME)
451 		expire_time = ia6->ia6_lifetime.ia6t_expire;
452 
453 	if (!(ia6->ia6_flags & IN6_IFF_DEPRECATED) &&
454 	    ia6->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME &&
455 	    expire_time > ia6->ia6_lifetime.ia6t_preferred)
456 		expire_time = ia6->ia6_lifetime.ia6t_preferred;
457 
458 	if (expire_time == INT64_MAX)
459 		return;
460 
461 	/*
462 	 * IFA6_IS_INVALID() and IFA6_IS_DEPRECATED() check for uptime
463 	 * greater than ia6t_expire or ia6t_preferred, not greater or equal.
464 	 * Schedule timeout one second later so that either IFA6_IS_INVALID()
465 	 * or IFA6_IS_DEPRECATED() is true.
466 	 */
467 	expire_time++;
468 
469 	if (!timeout_pending(&nd6_expire_timeout) ||
470 	    nd6_expire_next > expire_time) {
471 		secs = expire_time - getuptime();
472 		if (secs < 0)
473 			secs = 0;
474 
475 		timeout_add_sec(&nd6_expire_timeout, secs);
476 		nd6_expire_next = expire_time;
477 	}
478 }
479 
480 /*
481  * Expire interface addresses.
482  */
483 void
484 nd6_expire(void *unused)
485 {
486 	struct ifnet *ifp;
487 
488 	KERNEL_LOCK();
489 	NET_LOCK();
490 
491 	TAILQ_FOREACH(ifp, &ifnet, if_list) {
492 		struct ifaddr *ifa, *nifa;
493 		struct in6_ifaddr *ia6;
494 
495 		TAILQ_FOREACH_SAFE(ifa, &ifp->if_addrlist, ifa_list, nifa) {
496 			if (ifa->ifa_addr->sa_family != AF_INET6)
497 				continue;
498 			ia6 = ifatoia6(ifa);
499 			/* check address lifetime */
500 			if (IFA6_IS_INVALID(ia6)) {
501 				in6_purgeaddr(&ia6->ia_ifa);
502 			} else {
503 				if (IFA6_IS_DEPRECATED(ia6))
504 					ia6->ia6_flags |= IN6_IFF_DEPRECATED;
505 				nd6_expire_timer_update(ia6);
506 			}
507 		}
508 	}
509 
510 	NET_UNLOCK();
511 	KERNEL_UNLOCK();
512 }
513 
514 void
515 nd6_expire_timer(void *unused)
516 {
517 	task_add(net_tq(0), &nd6_expire_task);
518 }
519 
520 /*
521  * Nuke neighbor cache/prefix/default router management table, right before
522  * ifp goes away.
523  */
524 void
525 nd6_purge(struct ifnet *ifp)
526 {
527 	struct llinfo_nd6 *ln, *nln;
528 
529 	NET_ASSERT_LOCKED();
530 
531 	/*
532 	 * Nuke neighbor cache entries for the ifp.
533 	 */
534 	TAILQ_FOREACH_SAFE(ln, &nd6_list, ln_list, nln) {
535 		struct rtentry *rt;
536 		struct sockaddr_dl *sdl;
537 
538 		rt = ln->ln_rt;
539 		if (rt != NULL && rt->rt_gateway != NULL &&
540 		    rt->rt_gateway->sa_family == AF_LINK) {
541 			sdl = satosdl(rt->rt_gateway);
542 			if (sdl->sdl_index == ifp->if_index)
543 				nd6_free(rt);
544 		}
545 	}
546 }
547 
548 struct rtentry *
549 nd6_lookup(struct in6_addr *addr6, int create, struct ifnet *ifp,
550     u_int rtableid)
551 {
552 	struct rtentry *rt;
553 	struct sockaddr_in6 sin6;
554 	int flags;
555 
556 	bzero(&sin6, sizeof(sin6));
557 	sin6.sin6_len = sizeof(struct sockaddr_in6);
558 	sin6.sin6_family = AF_INET6;
559 	sin6.sin6_addr = *addr6;
560 	flags = (create) ? RT_RESOLVE : 0;
561 
562 	rt = rtalloc(sin6tosa(&sin6), flags, rtableid);
563 	if (rt != NULL && (rt->rt_flags & RTF_LLINFO) == 0) {
564 		/*
565 		 * This is the case for the default route.
566 		 * If we want to create a neighbor cache for the address, we
567 		 * should free the route for the destination and allocate an
568 		 * interface route.
569 		 */
570 		if (create) {
571 			rtfree(rt);
572 			rt = NULL;
573 		}
574 	}
575 	if (rt == NULL) {
576 		if (create && ifp) {
577 			struct rt_addrinfo info;
578 			struct ifaddr *ifa;
579 			int error;
580 
581 			/*
582 			 * If no route is available and create is set,
583 			 * we allocate a host route for the destination
584 			 * and treat it like an interface route.
585 			 * This hack is necessary for a neighbor which can't
586 			 * be covered by our own prefix.
587 			 */
588 			ifa = ifaof_ifpforaddr(sin6tosa(&sin6), ifp);
589 			if (ifa == NULL)
590 				return (NULL);
591 
592 			/*
593 			 * Create a new route.  RTF_LLINFO is necessary
594 			 * to create a Neighbor Cache entry for the
595 			 * destination in nd6_rtrequest which will be
596 			 * called in rtrequest.
597 			 */
598 			bzero(&info, sizeof(info));
599 			info.rti_ifa = ifa;
600 			info.rti_flags = RTF_HOST | RTF_LLINFO;
601 			info.rti_info[RTAX_DST] = sin6tosa(&sin6);
602 			info.rti_info[RTAX_GATEWAY] = sdltosa(ifp->if_sadl);
603 			error = rtrequest(RTM_ADD, &info, RTP_CONNECTED, &rt,
604 			    rtableid);
605 			if (error)
606 				return (NULL);
607 			if (rt->rt_llinfo != NULL) {
608 				struct llinfo_nd6 *ln =
609 				    (struct llinfo_nd6 *)rt->rt_llinfo;
610 				ln->ln_state = ND6_LLINFO_NOSTATE;
611 			}
612 		} else
613 			return (NULL);
614 	}
615 	/*
616 	 * Validation for the entry.
617 	 * Note that the check for rt_llinfo is necessary because a cloned
618 	 * route from a parent route that has the L flag (e.g. the default
619 	 * route to a p2p interface) may have the flag, too, while the
620 	 * destination is not actually a neighbor.
621 	 */
622 	if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
623 	    rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
624 	    (ifp != NULL && rt->rt_ifidx != ifp->if_index)) {
625 		if (create) {
626 			char addr[INET6_ADDRSTRLEN];
627 			nd6log((LOG_DEBUG, "%s: failed to lookup %s (if=%s)\n",
628 			    __func__,
629 			    inet_ntop(AF_INET6, addr6, addr, sizeof(addr)),
630 			    ifp ? ifp->if_xname : "unspec"));
631 		}
632 		rtfree(rt);
633 		return (NULL);
634 	}
635 	return (rt);
636 }
637 
638 /*
639  * Detect if a given IPv6 address identifies a neighbor on a given link.
640  * XXX: should take care of the destination of a p2p link?
641  */
642 int
643 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
644 {
645 	struct in6_ifaddr *ia6;
646 	struct ifaddr *ifa;
647 	struct rtentry *rt;
648 
649 	/*
650 	 * A link-local address is always a neighbor.
651 	 * XXX: we should use the sin6_scope_id field rather than the embedded
652 	 * interface index.
653 	 * XXX: a link does not necessarily specify a single interface.
654 	 */
655 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr) &&
656 	    ntohs(*(u_int16_t *)&addr->sin6_addr.s6_addr[2]) == ifp->if_index)
657 		return (1);
658 
659 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
660 		if (ifa->ifa_addr->sa_family != AF_INET6)
661 			continue;
662 
663 		ia6 = ifatoia6(ifa);
664 
665 		/* Prefix check down below. */
666 		if (ia6->ia6_flags & IN6_IFF_AUTOCONF)
667 			continue;
668 
669 		if (IN6_ARE_MASKED_ADDR_EQUAL(&addr->sin6_addr,
670 		    &ia6->ia_addr.sin6_addr,
671 		    &ia6->ia_prefixmask.sin6_addr))
672 			return (1);
673 	}
674 
675 	/*
676 	 * Even if the address matches none of our addresses, it might be
677 	 * in the neighbor cache.
678 	 */
679 	rt = nd6_lookup(&addr->sin6_addr, 0, ifp, ifp->if_rdomain);
680 	if (rt != NULL) {
681 		rtfree(rt);
682 		return (1);
683 	}
684 
685 	return (0);
686 }
687 
688 void
689 nd6_invalidate(struct rtentry *rt)
690 {
691 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
692 	struct sockaddr_dl *sdl = satosdl(rt->rt_gateway);
693 
694 	m_freem(ln->ln_hold);
695 	sdl->sdl_alen = 0;
696 	ln->ln_hold = NULL;
697 	ln->ln_state = ND6_LLINFO_INCOMPLETE;
698 	ln->ln_asked = 0;
699 }
700 
701 /*
702  * Free an nd6 llinfo entry.
703  * Since the function would cause significant changes in the kernel, DO NOT
704  * make it global, unless you have a strong reason for the change, and are sure
705  * that the change is safe.
706  */
707 void
708 nd6_free(struct rtentry *rt)
709 {
710 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
711 	struct in6_addr in6 = satosin6(rt_key(rt))->sin6_addr;
712 	struct ifnet *ifp;
713 
714 	NET_ASSERT_LOCKED();
715 
716 	ifp = if_get(rt->rt_ifidx);
717 
718 	if (!ip6_forwarding) {
719 		if (ln->ln_router) {
720 			/*
721 			 * rt6_flush must be called whether or not the neighbor
722 			 * is in the Default Router List.
723 			 * See a corresponding comment in nd6_na_input().
724 			 */
725 			rt6_flush(&in6, ifp);
726 		}
727 	}
728 
729 	KASSERT(!ISSET(rt->rt_flags, RTF_LOCAL));
730 	nd6_invalidate(rt);
731 
732 	/*
733 	 * Detach the route from the routing tree and the list of neighbor
734 	 * caches, and disable the route entry not to be used in already
735 	 * cached routes.
736 	 */
737 	if (!ISSET(rt->rt_flags, RTF_STATIC|RTF_CACHED))
738 		rtdeletemsg(rt, ifp, ifp->if_rdomain);
739 
740 	if_put(ifp);
741 }
742 
743 /*
744  * Upper-layer reachability hint for Neighbor Unreachability Detection.
745  *
746  * XXX cost-effective methods?
747  */
748 void
749 nd6_nud_hint(struct rtentry *rt)
750 {
751 	struct llinfo_nd6 *ln;
752 	struct ifnet *ifp;
753 
754 	ifp = if_get(rt->rt_ifidx);
755 	if (ifp == NULL)
756 		return;
757 
758 	if ((rt->rt_flags & RTF_GATEWAY) != 0 ||
759 	    (rt->rt_flags & RTF_LLINFO) == 0 ||
760 	    rt->rt_llinfo == NULL || rt->rt_gateway == NULL ||
761 	    rt->rt_gateway->sa_family != AF_LINK) {
762 		/* This is not a host route. */
763 		goto out;
764 	}
765 
766 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
767 	if (ln->ln_state < ND6_LLINFO_REACHABLE)
768 		goto out;
769 
770 	/*
771 	 * if we get upper-layer reachability confirmation many times,
772 	 * it is possible we have false information.
773 	 */
774 	ln->ln_byhint++;
775 	if (ln->ln_byhint > nd6_maxnudhint)
776 		goto out;
777 
778 	ln->ln_state = ND6_LLINFO_REACHABLE;
779 	if (!ND6_LLINFO_PERMANENT(ln))
780 		nd6_llinfo_settimer(ln, ND_IFINFO(ifp)->reachable);
781 out:
782 	if_put(ifp);
783 }
784 
785 void
786 nd6_rtrequest(struct ifnet *ifp, int req, struct rtentry *rt)
787 {
788 	struct sockaddr *gate = rt->rt_gateway;
789 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
790 	struct ifaddr *ifa;
791 
792 	if (ISSET(rt->rt_flags, RTF_GATEWAY|RTF_MULTICAST|RTF_MPLS))
793 		return;
794 
795 	if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
796 		/*
797 		 * This is probably an interface direct route for a link
798 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
799 		 * We do not need special treatment below for such a route.
800 		 * Moreover, the RTF_LLINFO flag which would be set below
801 		 * would annoy the ndp(8) command.
802 		 */
803 		return;
804 	}
805 
806 	if (req == RTM_RESOLVE && nd6_need_cache(ifp) == 0) {
807 		/*
808 		 * For routing daemons like ospf6d we allow neighbor discovery
809 		 * based on the cloning route only.  This allows us to sent
810 		 * packets directly into a network without having an address
811 		 * with matching prefix on the interface.  If the cloning
812 		 * route is used for an stf interface, we would mistakenly
813 		 * make a neighbor cache for the host route, and would see
814 		 * strange neighbor solicitation for the corresponding
815 		 * destination.  In order to avoid confusion, we check if the
816 		 * interface is suitable for neighbor discovery, and stop the
817 		 * process if not.  Additionally, we remove the LLINFO flag
818 		 * so that ndp(8) will not try to get the neighbor information
819 		 * of the destination.
820 		 */
821 		rt->rt_flags &= ~RTF_LLINFO;
822 		return;
823 	}
824 
825 	switch (req) {
826 	case RTM_ADD:
827 		if ((rt->rt_flags & RTF_CLONING) ||
828 		    ((rt->rt_flags & (RTF_LLINFO | RTF_LOCAL)) && ln == NULL)) {
829 			if (ln != NULL)
830 				nd6_llinfo_settimer(ln, 0);
831 			if ((rt->rt_flags & RTF_CLONING) != 0)
832 				break;
833 		}
834 		/*
835 		 * In IPv4 code, we try to announce new RTF_ANNOUNCE entry here.
836 		 * We don't do that here since llinfo is not ready yet.
837 		 *
838 		 * There are also couple of other things to be discussed:
839 		 * - unsolicited NA code needs improvement beforehand
840 		 * - RFC2461 says we MAY send multicast unsolicited NA
841 		 *   (7.2.6 paragraph 4), however, it also says that we
842 		 *   SHOULD provide a mechanism to prevent multicast NA storm.
843 		 *   we don't have anything like it right now.
844 		 *   note that the mechanism needs a mutual agreement
845 		 *   between proxies, which means that we need to implement
846 		 *   a new protocol, or a new kludge.
847 		 * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
848 		 *   we need to check ip6forwarding before sending it.
849 		 *   (or should we allow proxy ND configuration only for
850 		 *   routers?  there's no mention about proxy ND from hosts)
851 		 */
852 #if 0
853 		/* XXX it does not work */
854 		if (rt->rt_flags & RTF_ANNOUNCE)
855 			nd6_na_output(ifp,
856 			      &satosin6(rt_key(rt))->sin6_addr,
857 			      &satosin6(rt_key(rt))->sin6_addr,
858 			      ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
859 			      1, NULL);
860 #endif
861 		/* FALLTHROUGH */
862 	case RTM_RESOLVE:
863 		if (gate->sa_family != AF_LINK ||
864 		    gate->sa_len < sizeof(struct sockaddr_dl)) {
865 			log(LOG_DEBUG, "%s: bad gateway value: %s\n",
866 			    __func__, ifp->if_xname);
867 			break;
868 		}
869 		satosdl(gate)->sdl_type = ifp->if_type;
870 		satosdl(gate)->sdl_index = ifp->if_index;
871 		if (ln != NULL)
872 			break;	/* This happens on a route change */
873 		/*
874 		 * Case 2: This route may come from cloning, or a manual route
875 		 * add with a LL address.
876 		 */
877 		ln = pool_get(&nd6_pool, PR_NOWAIT | PR_ZERO);
878 		rt->rt_llinfo = (caddr_t)ln;
879 		if (ln == NULL) {
880 			log(LOG_DEBUG, "%s: pool get failed\n", __func__);
881 			break;
882 		}
883 		nd6_inuse++;
884 		nd6_allocated++;
885 		ln->ln_rt = rt;
886 		/* this is required for "ndp" command. - shin */
887 		if (req == RTM_ADD) {
888 		        /*
889 			 * gate should have some valid AF_LINK entry,
890 			 * and ln expire should have some lifetime
891 			 * which is specified by ndp command.
892 			 */
893 			ln->ln_state = ND6_LLINFO_REACHABLE;
894 			ln->ln_byhint = 0;
895 		} else {
896 		        /*
897 			 * When req == RTM_RESOLVE, rt is created and
898 			 * initialized in rtrequest(), so rt_expire is 0.
899 			 */
900 			ln->ln_state = ND6_LLINFO_NOSTATE;
901 			nd6_llinfo_settimer(ln, 0);
902 		}
903 		rt->rt_flags |= RTF_LLINFO;
904 		TAILQ_INSERT_HEAD(&nd6_list, ln, ln_list);
905 
906 		/*
907 		 * If we have too many cache entries, initiate immediate
908 		 * purging for some "less recently used" entries.  Note that
909 		 * we cannot directly call nd6_free() here because it would
910 		 * cause re-entering rtable related routines triggering an LOR
911 		 * problem for FreeBSD.
912 		 */
913 		if (ip6_neighborgcthresh >= 0 &&
914 		    nd6_inuse >= ip6_neighborgcthresh) {
915 			int i;
916 
917 			for (i = 0; i < 10; i++) {
918 				struct llinfo_nd6 *ln_end;
919 
920 				ln_end = TAILQ_LAST(&nd6_list, llinfo_nd6_head);
921 				if (ln_end == ln)
922 					break;
923 
924 				/* Move this entry to the head */
925 				TAILQ_REMOVE(&nd6_list, ln_end, ln_list);
926 				TAILQ_INSERT_HEAD(&nd6_list, ln_end, ln_list);
927 
928 				if (ND6_LLINFO_PERMANENT(ln_end))
929 					continue;
930 
931 				if (ln_end->ln_state > ND6_LLINFO_INCOMPLETE)
932 					ln_end->ln_state = ND6_LLINFO_STALE;
933 				else
934 					ln_end->ln_state = ND6_LLINFO_PURGE;
935 				nd6_llinfo_settimer(ln_end, 0);
936 			}
937 		}
938 
939 		/*
940 		 * check if rt_key(rt) is one of my address assigned
941 		 * to the interface.
942 		 */
943 		ifa = &in6ifa_ifpwithaddr(ifp,
944 		    &satosin6(rt_key(rt))->sin6_addr)->ia_ifa;
945 		if (ifa) {
946 			ln->ln_state = ND6_LLINFO_REACHABLE;
947 			ln->ln_byhint = 0;
948 			rt->rt_expire = 0;
949 			KASSERT(ifa == rt->rt_ifa);
950 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
951 			ln->ln_state = ND6_LLINFO_REACHABLE;
952 			ln->ln_byhint = 0;
953 			rt->rt_expire = 0;
954 
955 			/* join solicited node multicast for proxy ND */
956 			if (ifp->if_flags & IFF_MULTICAST) {
957 				struct in6_addr llsol;
958 				int error;
959 
960 				llsol = satosin6(rt_key(rt))->sin6_addr;
961 				llsol.s6_addr16[0] = htons(0xff02);
962 				llsol.s6_addr16[1] = htons(ifp->if_index);
963 				llsol.s6_addr32[1] = 0;
964 				llsol.s6_addr32[2] = htonl(1);
965 				llsol.s6_addr8[12] = 0xff;
966 
967 				if (in6_addmulti(&llsol, ifp, &error)) {
968 					char addr[INET6_ADDRSTRLEN];
969 					nd6log((LOG_ERR, "%s: failed to join "
970 					    "%s (errno=%d)\n", ifp->if_xname,
971 					    inet_ntop(AF_INET6, &llsol,
972 						addr, sizeof(addr)),
973 					    error));
974 				}
975 			}
976 		}
977 		break;
978 
979 	case RTM_DELETE:
980 		if (ln == NULL)
981 			break;
982 		/* leave from solicited node multicast for proxy ND */
983 		if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
984 		    (ifp->if_flags & IFF_MULTICAST) != 0) {
985 			struct in6_addr llsol;
986 			struct in6_multi *in6m;
987 
988 			llsol = satosin6(rt_key(rt))->sin6_addr;
989 			llsol.s6_addr16[0] = htons(0xff02);
990 			llsol.s6_addr16[1] = htons(ifp->if_index);
991 			llsol.s6_addr32[1] = 0;
992 			llsol.s6_addr32[2] = htonl(1);
993 			llsol.s6_addr8[12] = 0xff;
994 
995 			IN6_LOOKUP_MULTI(llsol, ifp, in6m);
996 			if (in6m)
997 				in6_delmulti(in6m);
998 		}
999 		nd6_inuse--;
1000 		TAILQ_REMOVE(&nd6_list, ln, ln_list);
1001 		rt->rt_expire = 0;
1002 		rt->rt_llinfo = NULL;
1003 		rt->rt_flags &= ~RTF_LLINFO;
1004 		m_freem(ln->ln_hold);
1005 		pool_put(&nd6_pool, ln);
1006 		break;
1007 
1008 	case RTM_INVALIDATE:
1009 		if (ln == NULL)
1010 			break;
1011 		if (!ISSET(rt->rt_flags, RTF_LOCAL))
1012 			nd6_invalidate(rt);
1013 		break;
1014 	}
1015 }
1016 
1017 int
1018 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1019 {
1020 	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1021 	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1022 	struct rtentry *rt;
1023 
1024 	switch (cmd) {
1025 	case SIOCGIFINFO_IN6:
1026 		NET_RLOCK_IN_IOCTL();
1027 		ndi->ndi = *ND_IFINFO(ifp);
1028 		NET_RUNLOCK_IN_IOCTL();
1029 		return (0);
1030 	case SIOCGNBRINFO_IN6:
1031 	{
1032 		struct llinfo_nd6 *ln;
1033 		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1034 		time_t expire;
1035 
1036 		NET_RLOCK_IN_IOCTL();
1037 		/*
1038 		 * XXX: KAME specific hack for scoped addresses
1039 		 *      XXXX: for other scopes than link-local?
1040 		 */
1041 		if (IN6_IS_ADDR_LINKLOCAL(&nbi->addr) ||
1042 		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi->addr)) {
1043 			u_int16_t *idp = (u_int16_t *)&nb_addr.s6_addr[2];
1044 
1045 			if (*idp == 0)
1046 				*idp = htons(ifp->if_index);
1047 		}
1048 
1049 		rt = nd6_lookup(&nb_addr, 0, ifp, ifp->if_rdomain);
1050 		if (rt == NULL ||
1051 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) == NULL) {
1052 			rtfree(rt);
1053 			NET_RUNLOCK_IN_IOCTL();
1054 			return (EINVAL);
1055 		}
1056 		expire = ln->ln_rt->rt_expire;
1057 		if (expire != 0) {
1058 			expire -= getuptime();
1059 			expire += gettime();
1060 		}
1061 
1062 		nbi->state = ln->ln_state;
1063 		nbi->asked = ln->ln_asked;
1064 		nbi->isrouter = ln->ln_router;
1065 		nbi->expire = expire;
1066 
1067 		rtfree(rt);
1068 		NET_RUNLOCK_IN_IOCTL();
1069 		return (0);
1070 	}
1071 	}
1072 	return (0);
1073 }
1074 
1075 /*
1076  * Create neighbor cache entry and cache link-layer address,
1077  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1078  *
1079  * type - ICMP6 type
1080  * code - type dependent information
1081  */
1082 void
1083 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1084     int lladdrlen, int type, int code)
1085 {
1086 	struct rtentry *rt = NULL;
1087 	struct llinfo_nd6 *ln = NULL;
1088 	int is_newentry;
1089 	struct sockaddr_dl *sdl = NULL;
1090 	int do_update;
1091 	int olladdr;
1092 	int llchange;
1093 	int newstate = 0;
1094 
1095 	if (!ifp)
1096 		panic("%s: ifp == NULL", __func__);
1097 	if (!from)
1098 		panic("%s: from == NULL", __func__);
1099 
1100 	/* nothing must be updated for unspecified address */
1101 	if (IN6_IS_ADDR_UNSPECIFIED(from))
1102 		return;
1103 
1104 	/*
1105 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
1106 	 * the caller.
1107 	 *
1108 	 * XXX If the link does not have link-layer address, what should
1109 	 * we do? (ifp->if_addrlen == 0)
1110 	 * Spec says nothing in sections for RA, RS and NA.  There's small
1111 	 * description on it in NS section (RFC 2461 7.2.3).
1112 	 */
1113 
1114 	rt = nd6_lookup(from, 0, ifp, ifp->if_rdomain);
1115 	if (rt == NULL) {
1116 		rt = nd6_lookup(from, 1, ifp, ifp->if_rdomain);
1117 		is_newentry = 1;
1118 	} else {
1119 		/* do not overwrite local or static entry */
1120 		if (ISSET(rt->rt_flags, RTF_STATIC|RTF_LOCAL)) {
1121 			rtfree(rt);
1122 			return;
1123 		}
1124 		is_newentry = 0;
1125 	}
1126 
1127 	if (!rt)
1128 		return;
1129 	if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
1130 fail:
1131 		nd6_free(rt);
1132 		rtfree(rt);
1133 		return;
1134 	}
1135 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1136 	if (ln == NULL)
1137 		goto fail;
1138 	if (rt->rt_gateway == NULL)
1139 		goto fail;
1140 	if (rt->rt_gateway->sa_family != AF_LINK)
1141 		goto fail;
1142 	sdl = satosdl(rt->rt_gateway);
1143 
1144 	olladdr = (sdl->sdl_alen) ? 1 : 0;
1145 	if (olladdr && lladdr) {
1146 		if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
1147 			llchange = 1;
1148 		else
1149 			llchange = 0;
1150 	} else
1151 		llchange = 0;
1152 
1153 	/*
1154 	 * newentry olladdr  lladdr  llchange	(*=record)
1155 	 *	0	n	n	--	(1)
1156 	 *	0	y	n	--	(2)
1157 	 *	0	n	y	--	(3) * STALE
1158 	 *	0	y	y	n	(4) *
1159 	 *	0	y	y	y	(5) * STALE
1160 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
1161 	 *	1	--	y	--	(7) * STALE
1162 	 */
1163 
1164 	if (llchange) {
1165 		char addr[INET6_ADDRSTRLEN];
1166 		log(LOG_INFO, "ndp info overwritten for %s by %s on %s\n",
1167 		    inet_ntop(AF_INET6, from, addr, sizeof(addr)),
1168 		    ether_sprintf(lladdr), ifp->if_xname);
1169 	}
1170 	if (lladdr) {		/* (3-5) and (7) */
1171 		/*
1172 		 * Record source link-layer address
1173 		 * XXX is it dependent to ifp->if_type?
1174 		 */
1175 		sdl->sdl_alen = ifp->if_addrlen;
1176 		bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1177 	}
1178 
1179 	if (!is_newentry) {
1180 		if ((!olladdr && lladdr) ||		/* (3) */
1181 		    (olladdr && lladdr && llchange)) {	/* (5) */
1182 			do_update = 1;
1183 			newstate = ND6_LLINFO_STALE;
1184 		} else					/* (1-2,4) */
1185 			do_update = 0;
1186 	} else {
1187 		do_update = 1;
1188 		if (!lladdr)				/* (6) */
1189 			newstate = ND6_LLINFO_NOSTATE;
1190 		else					/* (7) */
1191 			newstate = ND6_LLINFO_STALE;
1192 	}
1193 
1194 	if (do_update) {
1195 		/*
1196 		 * Update the state of the neighbor cache.
1197 		 */
1198 		ln->ln_state = newstate;
1199 
1200 		if (ln->ln_state == ND6_LLINFO_STALE) {
1201 			/*
1202 			 * Since nd6_resolve() in ifp->if_output() will cause
1203 			 * state transition to DELAY and reset the timer,
1204 			 * we must set the timer now, although it is actually
1205 			 * meaningless.
1206 			 */
1207 			nd6_llinfo_settimer(ln, nd6_gctimer);
1208 
1209 			if (ln->ln_hold) {
1210 				struct mbuf *n = ln->ln_hold;
1211 				ln->ln_hold = NULL;
1212 				/*
1213 				 * we assume ifp is not a p2p here, so just
1214 				 * set the 2nd argument as the 1st one.
1215 				 */
1216 				ifp->if_output(ifp, n, rt_key(rt), rt);
1217 				if (ln->ln_hold == n) {
1218 					/* n is back in ln_hold. Discard. */
1219 					m_freem(ln->ln_hold);
1220 					ln->ln_hold = NULL;
1221 				}
1222 			}
1223 		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1224 			/* probe right away */
1225 			nd6_llinfo_settimer(ln, 0);
1226 		}
1227 	}
1228 
1229 	/*
1230 	 * ICMP6 type dependent behavior.
1231 	 *
1232 	 * NS: clear IsRouter if new entry
1233 	 * RS: clear IsRouter
1234 	 * RA: set IsRouter if there's lladdr
1235 	 * redir: clear IsRouter if new entry
1236 	 *
1237 	 * RA case, (1):
1238 	 * The spec says that we must set IsRouter in the following cases:
1239 	 * - If lladdr exist, set IsRouter.  This means (1-5).
1240 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
1241 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1242 	 * A question arises for (1) case.  (1) case has no lladdr in the
1243 	 * neighbor cache, this is similar to (6).
1244 	 * This case is rare but we figured that we MUST NOT set IsRouter.
1245 	 *
1246 	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
1247 	 *							D R
1248 	 *	0	n	n	--	(1)	c   ?     s
1249 	 *	0	y	n	--	(2)	c   s     s
1250 	 *	0	n	y	--	(3)	c   s     s
1251 	 *	0	y	y	n	(4)	c   s     s
1252 	 *	0	y	y	y	(5)	c   s     s
1253 	 *	1	--	n	--	(6) c	c	c s
1254 	 *	1	--	y	--	(7) c	c   s	c s
1255 	 *
1256 	 *					(c=clear s=set)
1257 	 */
1258 	switch (type & 0xff) {
1259 	case ND_NEIGHBOR_SOLICIT:
1260 		/*
1261 		 * New entry must have is_router flag cleared.
1262 		 */
1263 		if (is_newentry)	/* (6-7) */
1264 			ln->ln_router = 0;
1265 		break;
1266 	case ND_REDIRECT:
1267 		/*
1268 		 * If the icmp is a redirect to a better router, always set the
1269 		 * is_router flag.  Otherwise, if the entry is newly created,
1270 		 * clear the flag.  [RFC 2461, sec 8.3]
1271 		 */
1272 		if (code == ND_REDIRECT_ROUTER)
1273 			ln->ln_router = 1;
1274 		else if (is_newentry) /* (6-7) */
1275 			ln->ln_router = 0;
1276 		break;
1277 	case ND_ROUTER_SOLICIT:
1278 		/*
1279 		 * is_router flag must always be cleared.
1280 		 */
1281 		ln->ln_router = 0;
1282 		break;
1283 	case ND_ROUTER_ADVERT:
1284 		/*
1285 		 * Mark an entry with lladdr as a router.
1286 		 */
1287 		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
1288 		    (is_newentry && lladdr)) {			/* (7) */
1289 			ln->ln_router = 1;
1290 		}
1291 		break;
1292 	}
1293 
1294 	rtfree(rt);
1295 }
1296 
1297 void
1298 nd6_slowtimo(void *ignored_arg)
1299 {
1300 	struct nd_ifinfo *nd6if;
1301 	struct ifnet *ifp;
1302 
1303 	NET_LOCK();
1304 
1305 	timeout_add_sec(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL);
1306 
1307 	TAILQ_FOREACH(ifp, &ifnet, if_list) {
1308 		nd6if = ND_IFINFO(ifp);
1309 		if (nd6if->basereachable && /* already initialized */
1310 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1311 			/*
1312 			 * Since reachable time rarely changes by router
1313 			 * advertisements, we SHOULD insure that a new random
1314 			 * value gets recomputed at least once every few hours.
1315 			 * (RFC 2461, 6.3.4)
1316 			 */
1317 			nd6if->recalctm = nd6_recalc_reachtm_interval;
1318 			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1319 		}
1320 	}
1321 	NET_UNLOCK();
1322 }
1323 
1324 int
1325 nd6_resolve(struct ifnet *ifp, struct rtentry *rt0, struct mbuf *m,
1326     struct sockaddr *dst, u_char *desten)
1327 {
1328 	struct sockaddr_dl *sdl;
1329 	struct rtentry *rt;
1330 	struct llinfo_nd6 *ln = NULL;
1331 
1332 	if (m->m_flags & M_MCAST) {
1333 		ETHER_MAP_IPV6_MULTICAST(&satosin6(dst)->sin6_addr, desten);
1334 		return (0);
1335 	}
1336 
1337 	rt = rt_getll(rt0);
1338 
1339 	if (ISSET(rt->rt_flags, RTF_REJECT) &&
1340 	    (rt->rt_expire == 0 || getuptime() < rt->rt_expire)) {
1341 		m_freem(m);
1342 		return (rt == rt0 ? EHOSTDOWN : EHOSTUNREACH);
1343 	}
1344 
1345 	/*
1346 	 * Address resolution or Neighbor Unreachability Detection
1347 	 * for the next hop.
1348 	 * At this point, the destination of the packet must be a unicast
1349 	 * or an anycast address(i.e. not a multicast).
1350 	 */
1351 	if (!ISSET(rt->rt_flags, RTF_LLINFO)) {
1352 		char addr[INET6_ADDRSTRLEN];
1353 		log(LOG_DEBUG, "%s: %s: route contains no ND information\n",
1354 		    __func__, inet_ntop(AF_INET6,
1355 		    &satosin6(rt_key(rt))->sin6_addr, addr, sizeof(addr)));
1356 		m_freem(m);
1357 		return (EINVAL);
1358 	}
1359 
1360 	if (rt->rt_gateway->sa_family != AF_LINK) {
1361 		printf("%s: something odd happens\n", __func__);
1362 		m_freem(m);
1363 		return (EINVAL);
1364 	}
1365 
1366 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1367 	KASSERT(ln != NULL);
1368 
1369 	/*
1370 	 * Move this entry to the head of the queue so that it is less likely
1371 	 * for this entry to be a target of forced garbage collection (see
1372 	 * nd6_rtrequest()).
1373 	 */
1374 	TAILQ_REMOVE(&nd6_list, ln, ln_list);
1375 	TAILQ_INSERT_HEAD(&nd6_list, ln, ln_list);
1376 
1377 	/*
1378 	 * The first time we send a packet to a neighbor whose entry is
1379 	 * STALE, we have to change the state to DELAY and a sets a timer to
1380 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
1381 	 * neighbor unreachability detection on expiration.
1382 	 * (RFC 2461 7.3.3)
1383 	 */
1384 	if (ln->ln_state == ND6_LLINFO_STALE) {
1385 		ln->ln_asked = 0;
1386 		ln->ln_state = ND6_LLINFO_DELAY;
1387 		nd6_llinfo_settimer(ln, nd6_delay);
1388 	}
1389 
1390 	/*
1391 	 * If the neighbor cache entry has a state other than INCOMPLETE
1392 	 * (i.e. its link-layer address is already resolved), just
1393 	 * send the packet.
1394 	 */
1395 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE) {
1396 		sdl = satosdl(rt->rt_gateway);
1397 		if (sdl->sdl_alen != ETHER_ADDR_LEN) {
1398 			char addr[INET6_ADDRSTRLEN];
1399 			log(LOG_DEBUG, "%s: %s: incorrect nd6 information\n",
1400 			    __func__,
1401 			    inet_ntop(AF_INET6, &satosin6(dst)->sin6_addr,
1402 				addr, sizeof(addr)));
1403 			m_freem(m);
1404 			return (EINVAL);
1405 		}
1406 
1407 		bcopy(LLADDR(sdl), desten, sdl->sdl_alen);
1408 		return (0);
1409 	}
1410 
1411 	/*
1412 	 * There is a neighbor cache entry, but no ethernet address
1413 	 * response yet.  Replace the held mbuf (if any) with this
1414 	 * latest one.
1415 	 */
1416 	if (ln->ln_state == ND6_LLINFO_NOSTATE)
1417 		ln->ln_state = ND6_LLINFO_INCOMPLETE;
1418 	m_freem(ln->ln_hold);
1419 	ln->ln_hold = m;
1420 
1421 	/*
1422 	 * If there has been no NS for the neighbor after entering the
1423 	 * INCOMPLETE state, send the first solicitation.
1424 	 */
1425 	if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
1426 		ln->ln_asked++;
1427 		nd6_llinfo_settimer(ln, ND_IFINFO(ifp)->retrans / 1000);
1428 		nd6_ns_output(ifp, NULL, &satosin6(dst)->sin6_addr, ln, 0);
1429 	}
1430 	return (EAGAIN);
1431 }
1432 
1433 int
1434 nd6_need_cache(struct ifnet *ifp)
1435 {
1436 	/*
1437 	 * RFC2893 says:
1438 	 * - unidirectional tunnels needs no ND
1439 	 */
1440 	switch (ifp->if_type) {
1441 	case IFT_ETHER:
1442 	case IFT_IEEE80211:
1443 	case IFT_CARP:
1444 		return (1);
1445 	default:
1446 		return (0);
1447 	}
1448 }
1449