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