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