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