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