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