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