xref: /openbsd-src/sys/netinet6/nd6.c (revision 4c1e55dc91edd6e69ccc60ce855900fbc12cf34f)
1 /*	$OpenBSD: nd6.c,v 1.91 2012/01/03 23:41:51 bluhm 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 void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
100 void nd6_slowtimo(void *);
101 struct llinfo_nd6 *nd6_free(struct rtentry *, int);
102 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 int fill_drlist(void *, size_t *, size_t);
109 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(void)
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_sec(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL);
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 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, *ndr;
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_sec(&nd6_timer_ch, nd6_prune);
517 
518 	/* expire default router list */
519 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter, dr_entry, ndr)
520 		if (dr->expire && dr->expire < time_second)
521 			defrtrlist_del(dr);
522 
523 	/*
524 	 * expire interface addresses.
525 	 * in the past the loop was inside prefix expiry processing.
526 	 * However, from a stricter spec-conformance standpoint, we should
527 	 * rather separate address lifetimes and prefix lifetimes.
528 	 */
529 	for (ia6 = in6_ifaddr; ia6; ia6 = nia6) {
530 		nia6 = ia6->ia_next;
531 		/* check address lifetime */
532 		if (IFA6_IS_INVALID(ia6)) {
533 			in6_purgeaddr(&ia6->ia_ifa);
534 		} else if (IFA6_IS_DEPRECATED(ia6)) {
535 			ia6->ia6_flags |= IN6_IFF_DEPRECATED;
536 		} else {
537 			/*
538 			 * A new RA might have made a deprecated address
539 			 * preferred.
540 			 */
541 			ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
542 		}
543 	}
544 
545 	/* expire prefix list */
546 	pr = LIST_FIRST(&nd_prefix);
547 	while (pr != NULL) {
548 		/*
549 		 * check prefix lifetime.
550 		 * since pltime is just for autoconf, pltime processing for
551 		 * prefix is not necessary.
552 		 */
553 		if (pr->ndpr_vltime != ND6_INFINITE_LIFETIME &&
554 		    time_second - pr->ndpr_lastupdate > pr->ndpr_vltime) {
555 			struct nd_prefix *t;
556 			t = LIST_NEXT(pr, ndpr_entry);
557 
558 			/*
559 			 * address expiration and prefix expiration are
560 			 * separate.  NEVER perform in6_purgeaddr here.
561 			 */
562 
563 			prelist_remove(pr);
564 			pr = t;
565 		} else
566 			pr = LIST_NEXT(pr, ndpr_entry);
567 	}
568 	splx(s);
569 }
570 
571 /*
572  * Nuke neighbor cache/prefix/default router management table, right before
573  * ifp goes away.
574  */
575 void
576 nd6_purge(struct ifnet *ifp)
577 {
578 	struct llinfo_nd6 *ln, *nln;
579 	struct nd_defrouter *dr, *ndr;
580 	struct nd_prefix *pr, *npr;
581 
582 	/*
583 	 * Nuke default router list entries toward ifp.
584 	 * We defer removal of default router list entries that is installed
585 	 * in the routing table, in order to keep additional side effects as
586 	 * small as possible.
587 	 */
588 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter, dr_entry, ndr) {
589 		if (dr->installed)
590 			continue;
591 
592 		if (dr->ifp == ifp)
593 			defrtrlist_del(dr);
594 	}
595 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter, dr_entry, ndr) {
596 		if (!dr->installed)
597 			continue;
598 
599 		if (dr->ifp == ifp)
600 			defrtrlist_del(dr);
601 	}
602 
603 	/* Nuke prefix list entries toward ifp */
604 	for (pr = LIST_FIRST(&nd_prefix); pr != NULL; pr = npr) {
605 		npr = LIST_NEXT(pr, ndpr_entry);
606 		if (pr->ndpr_ifp == ifp) {
607 			/*
608 			 * Because if_detach() does *not* release prefixes
609 			 * while purging addresses the reference count will
610 			 * still be above zero. We therefore reset it to
611 			 * make sure that the prefix really gets purged.
612 			 */
613 			pr->ndpr_refcnt = 0;
614 			/*
615 			 * Previously, pr->ndpr_addr is removed as well,
616 			 * but I strongly believe we don't have to do it.
617 			 * nd6_purge() is only called from in6_ifdetach(),
618 			 * which removes all the associated interface addresses
619 			 * by itself.
620 			 * (jinmei@kame.net 20010129)
621 			 */
622 			prelist_remove(pr);
623 		}
624 	}
625 
626 	/* cancel default outgoing interface setting */
627 	if (nd6_defifindex == ifp->if_index)
628 		nd6_setdefaultiface(0);
629 
630 	if (!ip6_forwarding && ip6_accept_rtadv) { /* XXX: too restrictive? */
631 		/* refresh default router list */
632 		defrouter_select();
633 	}
634 
635 	/*
636 	 * Nuke neighbor cache entries for the ifp.
637 	 * Note that rt->rt_ifp may not be the same as ifp,
638 	 * due to KAME goto ours hack.  See RTM_RESOLVE case in
639 	 * nd6_rtrequest(), and ip6_input().
640 	 */
641 	ln = llinfo_nd6.ln_next;
642 	while (ln && ln != &llinfo_nd6) {
643 		struct rtentry *rt;
644 		struct sockaddr_dl *sdl;
645 
646 		nln = ln->ln_next;
647 		rt = ln->ln_rt;
648 		if (rt && rt->rt_gateway &&
649 		    rt->rt_gateway->sa_family == AF_LINK) {
650 			sdl = (struct sockaddr_dl *)rt->rt_gateway;
651 			if (sdl->sdl_index == ifp->if_index)
652 				nln = nd6_free(rt, 0);
653 		}
654 		ln = nln;
655 	}
656 }
657 
658 struct rtentry *
659 nd6_lookup(struct in6_addr *addr6, int create, struct ifnet *ifp)
660 {
661 	struct rtentry *rt;
662 	struct sockaddr_in6 sin6;
663 
664 	bzero(&sin6, sizeof(sin6));
665 	sin6.sin6_len = sizeof(struct sockaddr_in6);
666 	sin6.sin6_family = AF_INET6;
667 	sin6.sin6_addr = *addr6;
668 
669 	rt = rtalloc1((struct sockaddr *)&sin6, create, ifp->if_rdomain);
670 	if (rt && (rt->rt_flags & RTF_LLINFO) == 0) {
671 		/*
672 		 * This is the case for the default route.
673 		 * If we want to create a neighbor cache for the address, we
674 		 * should free the route for the destination and allocate an
675 		 * interface route.
676 		 */
677 		if (create) {
678 			RTFREE(rt);
679 			rt = 0;
680 		}
681 	}
682 	if (!rt) {
683 		if (create && ifp) {
684 			struct rt_addrinfo info;
685 			int e;
686 
687 			/*
688 			 * If no route is available and create is set,
689 			 * we allocate a host route for the destination
690 			 * and treat it like an interface route.
691 			 * This hack is necessary for a neighbor which can't
692 			 * be covered by our own prefix.
693 			 */
694 			struct ifaddr *ifa =
695 			    ifaof_ifpforaddr((struct sockaddr *)&sin6, ifp);
696 			if (ifa == NULL)
697 				return (NULL);
698 
699 			/*
700 			 * Create a new route.  RTF_LLINFO is necessary
701 			 * to create a Neighbor Cache entry for the
702 			 * destination in nd6_rtrequest which will be
703 			 * called in rtrequest1 via ifa->ifa_rtrequest.
704 			 */
705 			bzero(&info, sizeof(info));
706 			info.rti_flags = (ifa->ifa_flags | RTF_HOST |
707 			    RTF_LLINFO) & ~RTF_CLONING;
708 			info.rti_info[RTAX_DST] = (struct sockaddr *)&sin6;
709 			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
710 			info.rti_info[RTAX_NETMASK] =
711 			    (struct sockaddr *)&all1_sa;
712 			if ((e = rtrequest1(RTM_ADD, &info, RTP_CONNECTED,
713 			    &rt, ifp->if_rdomain)) != 0) {
714 #if 0
715 				log(LOG_ERR,
716 				    "nd6_lookup: failed to add route for a "
717 				    "neighbor(%s), errno=%d\n",
718 				    ip6_sprintf(addr6), e);
719 #endif
720 				return (NULL);
721 			}
722 			if (rt == NULL)
723 				return (NULL);
724 			if (rt->rt_llinfo) {
725 				struct llinfo_nd6 *ln =
726 				    (struct llinfo_nd6 *)rt->rt_llinfo;
727 				ln->ln_state = ND6_LLINFO_NOSTATE;
728 			}
729 		} else
730 			return (NULL);
731 	}
732 	rt->rt_refcnt--;
733 	/*
734 	 * Validation for the entry.
735 	 * Note that the check for rt_llinfo is necessary because a cloned
736 	 * route from a parent route that has the L flag (e.g. the default
737 	 * route to a p2p interface) may have the flag, too, while the
738 	 * destination is not actually a neighbor.
739 	 * XXX: we can't use rt->rt_ifp to check for the interface, since
740 	 *      it might be the loopback interface if the entry is for our
741 	 *      own address on a non-loopback interface. Instead, we should
742 	 *      use rt->rt_ifa->ifa_ifp, which would specify the REAL
743 	 *	interface.
744 	 */
745 	if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
746 	    rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
747 	    (ifp && rt->rt_ifa->ifa_ifp != ifp)) {
748 		if (create) {
749 			nd6log((LOG_DEBUG,
750 			    "nd6_lookup: failed to lookup %s (if = %s)\n",
751 			    ip6_sprintf(addr6),
752 			    ifp ? ifp->if_xname : "unspec"));
753 		}
754 		return (NULL);
755 	}
756 	return (rt);
757 }
758 
759 /*
760  * Detect if a given IPv6 address identifies a neighbor on a given link.
761  * XXX: should take care of the destination of a p2p link?
762  */
763 int
764 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
765 {
766 	struct nd_prefix *pr;
767 	struct rtentry *rt;
768 
769 	/*
770 	 * A link-local address is always a neighbor.
771 	 * XXX: we should use the sin6_scope_id field rather than the embedded
772 	 * interface index.
773 	 * XXX: a link does not necessarily specify a single interface.
774 	 */
775 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr) &&
776 	    ntohs(*(u_int16_t *)&addr->sin6_addr.s6_addr[2]) == ifp->if_index)
777 		return (1);
778 
779 	/*
780 	 * If the address matches one of our on-link prefixes, it should be a
781 	 * neighbor.
782 	 */
783 	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
784 		if (pr->ndpr_ifp != ifp)
785 			continue;
786 
787 		if (!(pr->ndpr_stateflags & NDPRF_ONLINK))
788 			continue;
789 
790 		if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
791 		    &addr->sin6_addr, &pr->ndpr_mask))
792 			return (1);
793 	}
794 
795 	/*
796 	 * If the default router list is empty, all addresses are regarded
797 	 * as on-link, and thus, as a neighbor.
798 	 * XXX: we restrict the condition to hosts, because routers usually do
799 	 * not have the "default router list".
800 	 */
801 	if (!ip6_forwarding && TAILQ_EMPTY(&nd_defrouter) &&
802 	    nd6_defifindex == ifp->if_index) {
803 		return (1);
804 	}
805 
806 	/*
807 	 * Even if the address matches none of our addresses, it might be
808 	 * in the neighbor cache.
809 	 */
810 	if ((rt = nd6_lookup(&addr->sin6_addr, 0, ifp)) != NULL)
811 		return (1);
812 
813 	return (0);
814 }
815 
816 /*
817  * Free an nd6 llinfo entry.
818  * Since the function would cause significant changes in the kernel, DO NOT
819  * make it global, unless you have a strong reason for the change, and are sure
820  * that the change is safe.
821  */
822 struct llinfo_nd6 *
823 nd6_free(struct rtentry *rt, int gc)
824 {
825 	struct rt_addrinfo info;
826 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo, *next;
827 	struct in6_addr in6 = ((struct sockaddr_in6 *)rt_key(rt))->sin6_addr;
828 	struct nd_defrouter *dr;
829 
830 	/*
831 	 * we used to have pfctlinput(PRC_HOSTDEAD) here.
832 	 * even though it is not harmful, it was not really necessary.
833 	 */
834 
835 	if (!ip6_forwarding) {
836 		int s;
837 		s = splsoftnet();
838 		dr = defrouter_lookup(&((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
839 		    rt->rt_ifp);
840 
841 		if (dr != NULL && dr->expire &&
842 		    ln->ln_state == ND6_LLINFO_STALE && gc) {
843 			/*
844 			 * If the reason for the deletion is just garbage
845 			 * collection, and the neighbor is an active default
846 			 * router, do not delete it.  Instead, reset the GC
847 			 * timer using the router's lifetime.
848 			 * Simply deleting the entry would affect default
849 			 * router selection, which is not necessarily a good
850 			 * thing, especially when we're using router preference
851 			 * values.
852 			 * XXX: the check for ln_state would be redundant,
853 			 *      but we intentionally keep it just in case.
854 			 */
855 			if (dr->expire > time_second * hz) {
856 				nd6_llinfo_settimer(ln,
857 				    dr->expire - time_second * hz);
858 			} else
859 				nd6_llinfo_settimer(ln, (long)nd6_gctimer * hz);
860 			splx(s);
861 			return (ln->ln_next);
862 		}
863 
864 		if (ln->ln_router || dr) {
865 			/*
866 			 * rt6_flush must be called whether or not the neighbor
867 			 * is in the Default Router List.
868 			 * See a corresponding comment in nd6_na_input().
869 			 */
870 			rt6_flush(&in6, rt->rt_ifp);
871 		}
872 
873 		if (dr) {
874 			/*
875 			 * Unreachability of a router might affect the default
876 			 * router selection and on-link detection of advertised
877 			 * prefixes.
878 			 */
879 
880 			/*
881 			 * Temporarily fake the state to choose a new default
882 			 * router and to perform on-link determination of
883 			 * prefixes correctly.
884 			 * Below the state will be set correctly,
885 			 * or the entry itself will be deleted.
886 			 */
887 			ln->ln_state = ND6_LLINFO_INCOMPLETE;
888 
889 			/*
890 			 * Since defrouter_select() does not affect the
891 			 * on-link determination and MIP6 needs the check
892 			 * before the default router selection, we perform
893 			 * the check now.
894 			 */
895 			pfxlist_onlink_check();
896 
897 			/*
898 			 * refresh default router list
899 			 */
900 			defrouter_select();
901 		}
902 		splx(s);
903 	}
904 
905 	/*
906 	 * Before deleting the entry, remember the next entry as the
907 	 * return value.  We need this because pfxlist_onlink_check() above
908 	 * might have freed other entries (particularly the old next entry) as
909 	 * a side effect (XXX).
910 	 */
911 	next = ln->ln_next;
912 
913 	/*
914 	 * Detach the route from the routing tree and the list of neighbor
915 	 * caches, and disable the route entry not to be used in already
916 	 * cached routes.
917 	 */
918 	bzero(&info, sizeof(info));
919 	info.rti_info[RTAX_DST] = rt_key(rt);
920 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
921 	rtrequest1(RTM_DELETE, &info, rt->rt_priority, NULL,
922 	    rt->rt_ifp->if_rdomain);
923 
924 	return (next);
925 }
926 
927 /*
928  * Upper-layer reachability hint for Neighbor Unreachability Detection.
929  *
930  * XXX cost-effective methods?
931  */
932 void
933 nd6_nud_hint(struct rtentry *rt, struct in6_addr *dst6, int force)
934 {
935 	struct llinfo_nd6 *ln;
936 
937 	/*
938 	 * If the caller specified "rt", use that.  Otherwise, resolve the
939 	 * routing table by supplied "dst6".
940 	 */
941 	if (!rt) {
942 		if (!dst6)
943 			return;
944 		if (!(rt = nd6_lookup(dst6, 0, NULL)))
945 			return;
946 	}
947 
948 	if ((rt->rt_flags & RTF_GATEWAY) != 0 ||
949 	    (rt->rt_flags & RTF_LLINFO) == 0 ||
950 	    !rt->rt_llinfo || !rt->rt_gateway ||
951 	    rt->rt_gateway->sa_family != AF_LINK) {
952 		/* This is not a host route. */
953 		return;
954 	}
955 
956 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
957 	if (ln->ln_state < ND6_LLINFO_REACHABLE)
958 		return;
959 
960 	/*
961 	 * if we get upper-layer reachability confirmation many times,
962 	 * it is possible we have false information.
963 	 */
964 	if (!force) {
965 		ln->ln_byhint++;
966 		if (ln->ln_byhint > nd6_maxnudhint)
967 			return;
968 	}
969 
970 	ln->ln_state = ND6_LLINFO_REACHABLE;
971 	if (!ND6_LLINFO_PERMANENT(ln)) {
972 		nd6_llinfo_settimer(ln,
973 		    (long)ND_IFINFO(rt->rt_ifp)->reachable * hz);
974 	}
975 }
976 
977 /*
978  * info - XXX: unused
979  */
980 
981 void
982 nd6_rtrequest(int req, struct rtentry *rt, struct rt_addrinfo *info)
983 {
984 	struct sockaddr *gate = rt->rt_gateway;
985 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)rt->rt_llinfo;
986 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
987 	struct ifnet *ifp = rt->rt_ifp;
988 	struct ifaddr *ifa;
989 	struct nd_defrouter *dr;
990 
991 	if (req == RTM_DELETE && (rt->rt_flags & RTF_GATEWAY) &&
992 	    (IN6_ARE_ADDR_EQUAL(&(satosin6(rt_key(rt)))->sin6_addr,
993 	    &in6addr_any) && rt_mask(rt) && (rt_mask(rt)->sa_len == 0 ||
994 	    IN6_ARE_ADDR_EQUAL(&(satosin6(rt_mask(rt)))->sin6_addr,
995 	    &in6addr_any)))) {
996 		dr = defrouter_lookup(&SIN6(gate)->sin6_addr, ifp);
997 		if (dr)
998 			dr->installed = 0;
999 	}
1000 
1001 	if ((rt->rt_flags & RTF_GATEWAY) != 0)
1002 		return;
1003 
1004 	if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
1005 		/*
1006 		 * This is probably an interface direct route for a link
1007 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
1008 		 * We do not need special treatment below for such a route.
1009 		 * Moreover, the RTF_LLINFO flag which would be set below
1010 		 * would annoy the ndp(8) command.
1011 		 */
1012 		return;
1013 	}
1014 
1015 	if (req == RTM_RESOLVE && nd6_need_cache(ifp) == 0) {
1016 		/*
1017 		 * For routing daemons like ospf6d we allow neighbor discovery
1018 		 * based on the cloning route only.  This allows us to sent
1019 		 * packets directly into a network without having an address
1020 		 * with matching prefix on the interface.  If the cloning
1021 		 * route is used for an stf interface, we would mistakenly
1022 		 * make a neighbor cache for the host route, and would see
1023 		 * strange neighbor solicitation for the corresponding
1024 		 * destination.  In order to avoid confusion, we check if the
1025 		 * interface is suitable for 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 = &in6ifa_ifpwithaddr(rt->rt_ifp,
1179 		    &SIN6(rt_key(rt))->sin6_addr)->ia_ifa;
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 		TAILQ_FOREACH(dr, &nd_defrouter, dr_entry) {
1286 			if (i >= DRLSTSIZ)
1287 				break;
1288 			drl->defrouter[i].rtaddr = dr->rtaddr;
1289 			if (IN6_IS_ADDR_LINKLOCAL(&drl->defrouter[i].rtaddr)) {
1290 				/* XXX: need to this hack for KAME stack */
1291 				drl->defrouter[i].rtaddr.s6_addr16[1] = 0;
1292 			} else
1293 				log(LOG_ERR,
1294 				    "default router list contains a "
1295 				    "non-linklocal address(%s)\n",
1296 				    ip6_sprintf(&drl->defrouter[i].rtaddr));
1297 
1298 			drl->defrouter[i].flags = dr->flags;
1299 			drl->defrouter[i].rtlifetime = dr->rtlifetime;
1300 			drl->defrouter[i].expire = dr->expire;
1301 			drl->defrouter[i].if_index = dr->ifp->if_index;
1302 			i++;
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, *ndr;
1420 
1421 		s = splsoftnet();
1422 		defrouter_reset();
1423 		TAILQ_FOREACH_SAFE(dr, &nd_defrouter, dr_entry, ndr)
1424 			defrtrlist_del(dr);
1425 		defrouter_select();
1426 		splx(s);
1427 		break;
1428 	}
1429 	case SIOCGNBRINFO_IN6:
1430 	{
1431 		struct llinfo_nd6 *ln;
1432 		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1433 
1434 		/*
1435 		 * XXX: KAME specific hack for scoped addresses
1436 		 *      XXXX: for other scopes than link-local?
1437 		 */
1438 		if (IN6_IS_ADDR_LINKLOCAL(&nbi->addr) ||
1439 		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi->addr)) {
1440 			u_int16_t *idp = (u_int16_t *)&nb_addr.s6_addr[2];
1441 
1442 			if (*idp == 0)
1443 				*idp = htons(ifp->if_index);
1444 		}
1445 
1446 		s = splsoftnet();
1447 		if ((rt = nd6_lookup(&nb_addr, 0, ifp)) == NULL ||
1448 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) == NULL) {
1449 			error = EINVAL;
1450 			splx(s);
1451 			break;
1452 		}
1453 		nbi->state = ln->ln_state;
1454 		nbi->asked = ln->ln_asked;
1455 		nbi->isrouter = ln->ln_router;
1456 		nbi->expire = ln->ln_expire;
1457 		splx(s);
1458 
1459 		break;
1460 	}
1461 	case SIOCGDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1462 		ndif->ifindex = nd6_defifindex;
1463 		break;
1464 	case SIOCSDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1465 		return (nd6_setdefaultiface(ndif->ifindex));
1466 		break;
1467 	}
1468 	return (error);
1469 }
1470 
1471 /*
1472  * Create neighbor cache entry and cache link-layer address,
1473  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1474  *
1475  * type - ICMP6 type
1476  * code - type dependent information
1477  */
1478 struct rtentry *
1479 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1480     int lladdrlen, int type, int code)
1481 {
1482 	struct rtentry *rt = NULL;
1483 	struct llinfo_nd6 *ln = NULL;
1484 	int is_newentry;
1485 	struct sockaddr_dl *sdl = NULL;
1486 	int do_update;
1487 	int olladdr;
1488 	int llchange;
1489 	int newstate = 0;
1490 
1491 	if (!ifp)
1492 		panic("ifp == NULL in nd6_cache_lladdr");
1493 	if (!from)
1494 		panic("from == NULL in nd6_cache_lladdr");
1495 
1496 	/* nothing must be updated for unspecified address */
1497 	if (IN6_IS_ADDR_UNSPECIFIED(from))
1498 		return NULL;
1499 
1500 	/*
1501 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
1502 	 * the caller.
1503 	 *
1504 	 * XXX If the link does not have link-layer address, what should
1505 	 * we do? (ifp->if_addrlen == 0)
1506 	 * Spec says nothing in sections for RA, RS and NA.  There's small
1507 	 * description on it in NS section (RFC 2461 7.2.3).
1508 	 */
1509 
1510 	rt = nd6_lookup(from, 0, ifp);
1511 	if (!rt) {
1512 #if 0
1513 		/* nothing must be done if there's no lladdr */
1514 		if (!lladdr || !lladdrlen)
1515 			return NULL;
1516 #endif
1517 
1518 		rt = nd6_lookup(from, RT_REPORT, ifp);
1519 		is_newentry = 1;
1520 	} else {
1521 		/* do nothing if static ndp is set */
1522 		if (rt->rt_flags & RTF_STATIC)
1523 			return NULL;
1524 		is_newentry = 0;
1525 	}
1526 
1527 	if (!rt)
1528 		return NULL;
1529 	if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
1530 fail:
1531 		(void)nd6_free(rt, 0);
1532 		return NULL;
1533 	}
1534 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1535 	if (!ln)
1536 		goto fail;
1537 	if (!rt->rt_gateway)
1538 		goto fail;
1539 	if (rt->rt_gateway->sa_family != AF_LINK)
1540 		goto fail;
1541 	sdl = SDL(rt->rt_gateway);
1542 
1543 	olladdr = (sdl->sdl_alen) ? 1 : 0;
1544 	if (olladdr && lladdr) {
1545 		if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
1546 			llchange = 1;
1547 		else
1548 			llchange = 0;
1549 	} else
1550 		llchange = 0;
1551 
1552 	/*
1553 	 * newentry olladdr  lladdr  llchange	(*=record)
1554 	 *	0	n	n	--	(1)
1555 	 *	0	y	n	--	(2)
1556 	 *	0	n	y	--	(3) * STALE
1557 	 *	0	y	y	n	(4) *
1558 	 *	0	y	y	y	(5) * STALE
1559 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
1560 	 *	1	--	y	--	(7) * STALE
1561 	 */
1562 
1563 	if (llchange) {
1564 		log(LOG_INFO, "ndp info overwritten for %s by %s on %s\n",
1565 		    ip6_sprintf(from), ether_sprintf(lladdr), ifp->if_xname);
1566 	}
1567 	if (lladdr) {		/* (3-5) and (7) */
1568 		/*
1569 		 * Record source link-layer address
1570 		 * XXX is it dependent to ifp->if_type?
1571 		 */
1572 		sdl->sdl_alen = ifp->if_addrlen;
1573 		bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1574 	}
1575 
1576 	if (!is_newentry) {
1577 		if ((!olladdr && lladdr) ||		/* (3) */
1578 		    (olladdr && lladdr && llchange)) {	/* (5) */
1579 			do_update = 1;
1580 			newstate = ND6_LLINFO_STALE;
1581 		} else					/* (1-2,4) */
1582 			do_update = 0;
1583 	} else {
1584 		do_update = 1;
1585 		if (!lladdr)				/* (6) */
1586 			newstate = ND6_LLINFO_NOSTATE;
1587 		else					/* (7) */
1588 			newstate = ND6_LLINFO_STALE;
1589 	}
1590 
1591 	if (do_update) {
1592 		/*
1593 		 * Update the state of the neighbor cache.
1594 		 */
1595 		ln->ln_state = newstate;
1596 
1597 		if (ln->ln_state == ND6_LLINFO_STALE) {
1598 			/*
1599 			 * XXX: since nd6_output() below will cause
1600 			 * state transition to DELAY and reset the timer,
1601 			 * we must set the timer now, although it is actually
1602 			 * meaningless.
1603 			 */
1604 			nd6_llinfo_settimer(ln, (long)nd6_gctimer * hz);
1605 
1606 			if (ln->ln_hold) {
1607 				struct mbuf *n = ln->ln_hold;
1608 				ln->ln_hold = NULL;
1609 				/*
1610 				 * we assume ifp is not a p2p here, so just
1611 				 * set the 2nd argument as the 1st one.
1612 				 */
1613 				nd6_output(ifp, ifp, n,
1614 				    (struct sockaddr_in6 *)rt_key(rt), rt);
1615 				if (ln->ln_hold == n) {
1616 					/* n is back in ln_hold. Discard. */
1617 					m_freem(ln->ln_hold);
1618 					ln->ln_hold = NULL;
1619 				}
1620 			}
1621 		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1622 			/* probe right away */
1623 			nd6_llinfo_settimer((void *)ln, 0);
1624 		}
1625 	}
1626 
1627 	/*
1628 	 * ICMP6 type dependent behavior.
1629 	 *
1630 	 * NS: clear IsRouter if new entry
1631 	 * RS: clear IsRouter
1632 	 * RA: set IsRouter if there's lladdr
1633 	 * redir: clear IsRouter if new entry
1634 	 *
1635 	 * RA case, (1):
1636 	 * The spec says that we must set IsRouter in the following cases:
1637 	 * - If lladdr exist, set IsRouter.  This means (1-5).
1638 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
1639 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1640 	 * A question arises for (1) case.  (1) case has no lladdr in the
1641 	 * neighbor cache, this is similar to (6).
1642 	 * This case is rare but we figured that we MUST NOT set IsRouter.
1643 	 *
1644 	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
1645 	 *							D R
1646 	 *	0	n	n	--	(1)	c   ?     s
1647 	 *	0	y	n	--	(2)	c   s     s
1648 	 *	0	n	y	--	(3)	c   s     s
1649 	 *	0	y	y	n	(4)	c   s     s
1650 	 *	0	y	y	y	(5)	c   s     s
1651 	 *	1	--	n	--	(6) c	c 	c s
1652 	 *	1	--	y	--	(7) c	c   s	c s
1653 	 *
1654 	 *					(c=clear s=set)
1655 	 */
1656 	switch (type & 0xff) {
1657 	case ND_NEIGHBOR_SOLICIT:
1658 		/*
1659 		 * New entry must have is_router flag cleared.
1660 		 */
1661 		if (is_newentry)	/* (6-7) */
1662 			ln->ln_router = 0;
1663 		break;
1664 	case ND_REDIRECT:
1665 		/*
1666 		 * If the icmp is a redirect to a better router, always set the
1667 		 * is_router flag.  Otherwise, if the entry is newly created,
1668 		 * clear the flag.  [RFC 2461, sec 8.3]
1669 		 */
1670 		if (code == ND_REDIRECT_ROUTER)
1671 			ln->ln_router = 1;
1672 		else if (is_newentry) /* (6-7) */
1673 			ln->ln_router = 0;
1674 		break;
1675 	case ND_ROUTER_SOLICIT:
1676 		/*
1677 		 * is_router flag must always be cleared.
1678 		 */
1679 		ln->ln_router = 0;
1680 		break;
1681 	case ND_ROUTER_ADVERT:
1682 		/*
1683 		 * Mark an entry with lladdr as a router.
1684 		 */
1685 		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
1686 		    (is_newentry && lladdr)) {			/* (7) */
1687 			ln->ln_router = 1;
1688 		}
1689 		break;
1690 	}
1691 
1692 	/*
1693 	 * When the link-layer address of a router changes, select the
1694 	 * best router again.  In particular, when the neighbor entry is newly
1695 	 * created, it might affect the selection policy.
1696 	 * Question: can we restrict the first condition to the "is_newentry"
1697 	 * case?
1698 	 * XXX: when we hear an RA from a new router with the link-layer
1699 	 * address option, defrouter_select() is called twice, since
1700 	 * defrtrlist_update called the function as well.  However, I believe
1701 	 * we can compromise the overhead, since it only happens the first
1702 	 * time.
1703 	 * XXX: although defrouter_select() should not have a bad effect
1704 	 * for those are not autoconfigured hosts, we explicitly avoid such
1705 	 * cases for safety.
1706 	 */
1707 	if (do_update && ln->ln_router && !ip6_forwarding && ip6_accept_rtadv)
1708 		defrouter_select();
1709 
1710 	return rt;
1711 }
1712 
1713 void
1714 nd6_slowtimo(void *ignored_arg)
1715 {
1716 	int s = splsoftnet();
1717 	struct nd_ifinfo *nd6if;
1718 	struct ifnet *ifp;
1719 
1720 	timeout_set(&nd6_slowtimo_ch, nd6_slowtimo, NULL);
1721 	timeout_add_sec(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL);
1722 	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
1723 	{
1724 		nd6if = ND_IFINFO(ifp);
1725 		if (nd6if->basereachable && /* already initialized */
1726 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1727 			/*
1728 			 * Since reachable time rarely changes by router
1729 			 * advertisements, we SHOULD insure that a new random
1730 			 * value gets recomputed at least once every few hours.
1731 			 * (RFC 2461, 6.3.4)
1732 			 */
1733 			nd6if->recalctm = nd6_recalc_reachtm_interval;
1734 			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1735 		}
1736 	}
1737 	splx(s);
1738 }
1739 
1740 #define senderr(e) { error = (e); goto bad;}
1741 int
1742 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
1743     struct sockaddr_in6 *dst, struct rtentry *rt0)
1744 {
1745 	struct mbuf *m = m0;
1746 	struct rtentry *rt = rt0;
1747 	struct sockaddr_in6 *gw6 = NULL;
1748 	struct llinfo_nd6 *ln = NULL;
1749 	int error = 0;
1750 #ifdef IPSEC
1751 	struct m_tag *mtag;
1752 #endif /* IPSEC */
1753 
1754 	if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1755 		goto sendpkt;
1756 
1757 	if (nd6_need_cache(ifp) == 0)
1758 		goto sendpkt;
1759 
1760 	/*
1761 	 * next hop determination.  This routine is derived from ether_output.
1762 	 */
1763 	if (rt) {
1764 		if ((rt->rt_flags & RTF_UP) == 0) {
1765 			if ((rt0 = rt = rtalloc1((struct sockaddr *)dst,
1766 			    RT_REPORT, m->m_pkthdr.rdomain)) != NULL)
1767 			{
1768 				rt->rt_refcnt--;
1769 				if (rt->rt_ifp != ifp)
1770 					senderr(EHOSTUNREACH);
1771 			} else
1772 				senderr(EHOSTUNREACH);
1773 		}
1774 
1775 		if (rt->rt_flags & RTF_GATEWAY) {
1776 			gw6 = (struct sockaddr_in6 *)rt->rt_gateway;
1777 
1778 			/*
1779 			 * We skip link-layer address resolution and NUD
1780 			 * if the gateway is not a neighbor from ND point
1781 			 * of view, regardless of the value of nd_ifinfo.flags.
1782 			 * The second condition is a bit tricky; we skip
1783 			 * if the gateway is our own address, which is
1784 			 * sometimes used to install a route to a p2p link.
1785 			 */
1786 			if (!nd6_is_addr_neighbor(gw6, ifp) ||
1787 			    in6ifa_ifpwithaddr(ifp, &gw6->sin6_addr)) {
1788 				/*
1789 				 * We allow this kind of tricky route only
1790 				 * when the outgoing interface is p2p.
1791 				 * XXX: we may need a more generic rule here.
1792 				 */
1793 				if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1794 					senderr(EHOSTUNREACH);
1795 
1796 				goto sendpkt;
1797 			}
1798 
1799 			if (rt->rt_gwroute == 0)
1800 				goto lookup;
1801 			if (((rt = rt->rt_gwroute)->rt_flags & RTF_UP) == 0) {
1802 				rtfree(rt); rt = rt0;
1803 			lookup:
1804 				rt->rt_gwroute = rtalloc1(rt->rt_gateway,
1805 				    RT_REPORT, m->m_pkthdr.rdomain);
1806 				if ((rt = rt->rt_gwroute) == 0)
1807 					senderr(EHOSTUNREACH);
1808 			}
1809 		}
1810 	}
1811 
1812 	/*
1813 	 * Address resolution or Neighbor Unreachability Detection
1814 	 * for the next hop.
1815 	 * At this point, the destination of the packet must be a unicast
1816 	 * or an anycast address(i.e. not a multicast).
1817 	 */
1818 
1819 	/* Look up the neighbor cache for the nexthop */
1820 	if (rt && (rt->rt_flags & RTF_LLINFO) != 0)
1821 		ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1822 	else {
1823 		/*
1824 		 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
1825 		 * the condition below is not very efficient.  But we believe
1826 		 * it is tolerable, because this should be a rare case.
1827 		 */
1828 		if (nd6_is_addr_neighbor(dst, ifp) &&
1829 		    (rt = nd6_lookup(&dst->sin6_addr, RT_REPORT, ifp)) != NULL)
1830 			ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1831 	}
1832 	if (!ln || !rt) {
1833 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
1834 		    !(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
1835 			log(LOG_DEBUG,
1836 			    "nd6_output: can't allocate llinfo for %s "
1837 			    "(ln=%p, rt=%p)\n",
1838 			    ip6_sprintf(&dst->sin6_addr), ln, rt);
1839 			senderr(EIO);	/* XXX: good error? */
1840 		}
1841 
1842 		goto sendpkt;	/* send anyway */
1843 	}
1844 
1845 	/*
1846 	 * Move this entry to the head of the queue so that it is less likely
1847 	 * for this entry to be a target of forced garbage collection (see
1848 	 * nd6_rtrequest()).
1849 	 */
1850 	LN_DEQUEUE(ln);
1851 	LN_INSERTHEAD(ln);
1852 
1853 	/* We don't have to do link-layer address resolution on a p2p link. */
1854 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
1855 	    ln->ln_state < ND6_LLINFO_REACHABLE) {
1856 		ln->ln_state = ND6_LLINFO_STALE;
1857 		nd6_llinfo_settimer(ln, (long)nd6_gctimer * hz);
1858 	}
1859 
1860 	/*
1861 	 * The first time we send a packet to a neighbor whose entry is
1862 	 * STALE, we have to change the state to DELAY and a sets a timer to
1863 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
1864 	 * neighbor unreachability detection on expiration.
1865 	 * (RFC 2461 7.3.3)
1866 	 */
1867 	if (ln->ln_state == ND6_LLINFO_STALE) {
1868 		ln->ln_asked = 0;
1869 		ln->ln_state = ND6_LLINFO_DELAY;
1870 		nd6_llinfo_settimer(ln, nd6_delay * hz);
1871 	}
1872 
1873 	/*
1874 	 * If the neighbor cache entry has a state other than INCOMPLETE
1875 	 * (i.e. its link-layer address is already resolved), just
1876 	 * send the packet.
1877 	 */
1878 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
1879 		goto sendpkt;
1880 
1881 	/*
1882 	 * There is a neighbor cache entry, but no ethernet address
1883 	 * response yet.  Replace the held mbuf (if any) with this
1884 	 * latest one.
1885 	 */
1886 	if (ln->ln_state == ND6_LLINFO_NOSTATE)
1887 		ln->ln_state = ND6_LLINFO_INCOMPLETE;
1888 	if (ln->ln_hold)
1889 		m_freem(ln->ln_hold);
1890 	ln->ln_hold = m;
1891 	/*
1892 	 * If there has been no NS for the neighbor after entering the
1893 	 * INCOMPLETE state, send the first solicitation.
1894 	 */
1895 	if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
1896 		ln->ln_asked++;
1897 		nd6_llinfo_settimer(ln,
1898 		    (long)ND_IFINFO(ifp)->retrans * hz / 1000);
1899 		nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, 0);
1900 	}
1901 	return (0);
1902 
1903   sendpkt:
1904 #ifdef IPSEC
1905 	/*
1906 	 * If we got here and IPsec crypto processing didn't happen, drop it.
1907 	 */
1908 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
1909 #endif /* IPSEC */
1910 
1911 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
1912 #ifdef IPSEC
1913 		if (mtag != NULL) {
1914 			/* Tell IPsec to do its own crypto. */
1915 			ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
1916 			error = EACCES;
1917 			goto bad;
1918 		}
1919 #endif /* IPSEC */
1920 		return ((*ifp->if_output)(origifp, m, (struct sockaddr *)dst,
1921 		    rt));
1922 	}
1923 #ifdef IPSEC
1924 	if (mtag != NULL) {
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, size_t newlen)
2015 {
2016 	void *p;
2017 	size_t ol;
2018 	int error;
2019 
2020 	error = 0;
2021 
2022 	if (newp)
2023 		return EPERM;
2024 	if (oldp && !oldlenp)
2025 		return EINVAL;
2026 	ol = oldlenp ? *oldlenp : 0;
2027 
2028 	if (oldp) {
2029 		p = malloc(*oldlenp, M_TEMP, M_WAITOK | M_CANFAIL);
2030 		if (!p)
2031 			return ENOMEM;
2032 	} else
2033 		p = NULL;
2034 	switch (name) {
2035 	case ICMPV6CTL_ND6_DRLIST:
2036 		error = fill_drlist(p, oldlenp, ol);
2037 		if (!error && p && oldp)
2038 			error = copyout(p, oldp, *oldlenp);
2039 		break;
2040 
2041 	case ICMPV6CTL_ND6_PRLIST:
2042 		error = fill_prlist(p, oldlenp, ol);
2043 		if (!error && p && oldp)
2044 			error = copyout(p, oldp, *oldlenp);
2045 		break;
2046 
2047 	default:
2048 		error = ENOPROTOOPT;
2049 		break;
2050 	}
2051 	if (p)
2052 		free(p, M_TEMP);
2053 
2054 	return (error);
2055 }
2056 
2057 int
2058 fill_drlist(void *oldp, size_t *oldlenp, size_t ol)
2059 {
2060 	int error = 0, s;
2061 	struct in6_defrouter *d = NULL, *de = NULL;
2062 	struct nd_defrouter *dr;
2063 	size_t l;
2064 
2065 	s = splsoftnet();
2066 
2067 	if (oldp) {
2068 		d = (struct in6_defrouter *)oldp;
2069 		de = (struct in6_defrouter *)((caddr_t)oldp + *oldlenp);
2070 	}
2071 	l = 0;
2072 
2073 	TAILQ_FOREACH(dr, &nd_defrouter, dr_entry) {
2074 		if (oldp && d + 1 <= de) {
2075 			bzero(d, sizeof(*d));
2076 			d->rtaddr.sin6_family = AF_INET6;
2077 			d->rtaddr.sin6_len = sizeof(struct sockaddr_in6);
2078 			d->rtaddr.sin6_addr = dr->rtaddr;
2079 			in6_recoverscope(&d->rtaddr, &d->rtaddr.sin6_addr,
2080 			    dr->ifp);
2081 			d->flags = dr->flags;
2082 			d->rtlifetime = dr->rtlifetime;
2083 			d->expire = dr->expire;
2084 			d->if_index = dr->ifp->if_index;
2085 		}
2086 
2087 		l += sizeof(*d);
2088 		if (d)
2089 			d++;
2090 	}
2091 
2092 	if (oldp) {
2093 		*oldlenp = l;	/* (caddr_t)d - (caddr_t)oldp */
2094 		if (l > ol)
2095 			error = ENOMEM;
2096 	} else
2097 		*oldlenp = l;
2098 
2099 	splx(s);
2100 
2101 	return (error);
2102 }
2103 
2104 int
2105 fill_prlist(void *oldp, size_t *oldlenp, size_t ol)
2106 {
2107 	int error = 0, s;
2108 	struct nd_prefix *pr;
2109 	struct in6_prefix *p = NULL;
2110 	struct in6_prefix *pe = NULL;
2111 	size_t l;
2112 
2113 	s = splsoftnet();
2114 
2115 	if (oldp) {
2116 		p = (struct in6_prefix *)oldp;
2117 		pe = (struct in6_prefix *)((caddr_t)oldp + *oldlenp);
2118 	}
2119 	l = 0;
2120 
2121 	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
2122 		u_short advrtrs;
2123 		size_t advance;
2124 		struct sockaddr_in6 *sin6;
2125 		struct sockaddr_in6 *s6;
2126 		struct nd_pfxrouter *pfr;
2127 
2128 		if (oldp && p + 1 <= pe)
2129 		{
2130 			bzero(p, sizeof(*p));
2131 			sin6 = (struct sockaddr_in6 *)(p + 1);
2132 
2133 			p->prefix = pr->ndpr_prefix;
2134 			if (in6_recoverscope(&p->prefix,
2135 			    &p->prefix.sin6_addr, pr->ndpr_ifp) != 0)
2136 				log(LOG_ERR,
2137 				    "scope error in prefix list (%s)\n",
2138 				    ip6_sprintf(&p->prefix.sin6_addr));
2139 			p->raflags = pr->ndpr_raf;
2140 			p->prefixlen = pr->ndpr_plen;
2141 			p->vltime = pr->ndpr_vltime;
2142 			p->pltime = pr->ndpr_pltime;
2143 			p->if_index = pr->ndpr_ifp->if_index;
2144 			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2145 				p->expire = 0;
2146 			else {
2147 				time_t maxexpire;
2148 
2149 				/* XXX: we assume time_t is signed. */
2150 				maxexpire = (-1) &
2151 					~(1 << ((sizeof(maxexpire) * 8) - 1));
2152 				if (pr->ndpr_vltime <
2153 				    maxexpire - pr->ndpr_lastupdate) {
2154 					p->expire = pr->ndpr_lastupdate +
2155 						pr->ndpr_vltime;
2156 				} else
2157 					p->expire = maxexpire;
2158 			}
2159 			p->refcnt = pr->ndpr_refcnt;
2160 			p->flags = pr->ndpr_stateflags;
2161 			p->origin = PR_ORIG_RA;
2162 			advrtrs = 0;
2163 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
2164 				if ((void *)&sin6[advrtrs + 1] > (void *)pe) {
2165 					advrtrs++;
2166 					continue;
2167 				}
2168 				s6 = &sin6[advrtrs];
2169 				s6->sin6_family = AF_INET6;
2170 				s6->sin6_len = sizeof(struct sockaddr_in6);
2171 				s6->sin6_addr = pfr->router->rtaddr;
2172 				in6_recoverscope(s6, &pfr->router->rtaddr,
2173 				    pfr->router->ifp);
2174 				advrtrs++;
2175 			}
2176 			p->advrtrs = advrtrs;
2177 		}
2178 		else {
2179 			advrtrs = 0;
2180 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
2181 				advrtrs++;
2182 		}
2183 
2184 		advance = sizeof(*p) + sizeof(*sin6) * advrtrs;
2185 		l += advance;
2186 		if (p)
2187 			p = (struct in6_prefix *)((caddr_t)p + advance);
2188 	}
2189 
2190 	if (oldp) {
2191 		*oldlenp = l;	/* (caddr_t)d - (caddr_t)oldp */
2192 		if (l > ol)
2193 			error = ENOMEM;
2194 	} else
2195 		*oldlenp = l;
2196 
2197 	splx(s);
2198 
2199 	return (error);
2200 }
2201