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