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