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