xref: /openbsd-src/sys/netinet6/nd6.c (revision 2b0358df1d88d06ef4139321dd05bd5e05d91eaf)
1 /*	$OpenBSD: nd6.c,v 1.82 2009/01/30 11:56:59 rainer 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_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 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_sec(&nd6_timer_ch, nd6_prune);
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 	struct nd_defrouter *dr;
999 
1000 	if (req == RTM_DELETE && (rt->rt_flags & RTF_GATEWAY) &&
1001 	    (IN6_ARE_ADDR_EQUAL(&(satosin6(rt_key(rt)))->sin6_addr,
1002 	    &in6addr_any) && rt_mask(rt) && (rt_mask(rt)->sa_len == 0 ||
1003 	    IN6_ARE_ADDR_EQUAL(&(satosin6(rt_mask(rt)))->sin6_addr,
1004 	    &in6addr_any)))) {
1005 		dr = defrouter_lookup(&SIN6(gate)->sin6_addr, ifp);
1006 		if (dr)
1007 			dr->installed = 0;
1008 	}
1009 
1010 	if ((rt->rt_flags & RTF_GATEWAY) != 0)
1011 		return;
1012 
1013 	if (nd6_need_cache(ifp) == 0 && (rt->rt_flags & RTF_HOST) == 0) {
1014 		/*
1015 		 * This is probably an interface direct route for a link
1016 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
1017 		 * We do not need special treatment below for such a route.
1018 		 * Moreover, the RTF_LLINFO flag which would be set below
1019 		 * would annoy the ndp(8) command.
1020 		 */
1021 		return;
1022 	}
1023 
1024 	if (req == RTM_RESOLVE &&
1025 	    (nd6_need_cache(ifp) == 0 || /* stf case */
1026 	     !nd6_is_addr_neighbor((struct sockaddr_in6 *)rt_key(rt), ifp))) {
1027 		/*
1028 		 * FreeBSD and BSD/OS often make a cloned host route based
1029 		 * on a less-specific route (e.g. the default route).
1030 		 * If the less specific route does not have a "gateway"
1031 		 * (this is the case when the route just goes to a p2p or an
1032 		 * stf interface), we'll mistakenly make a neighbor cache for
1033 		 * the host route, and will see strange neighbor solicitation
1034 		 * for the corresponding destination.  In order to avoid the
1035 		 * confusion, we check if the destination of the route is
1036 		 * a neighbor in terms of neighbor discovery, and stop the
1037 		 * process if not.  Additionally, we remove the LLINFO flag
1038 		 * so that ndp(8) will not try to get the neighbor information
1039 		 * of the destination.
1040 		 */
1041 		rt->rt_flags &= ~RTF_LLINFO;
1042 		return;
1043 	}
1044 
1045 	switch (req) {
1046 	case RTM_ADD:
1047 		/*
1048 		 * There is no backward compatibility :)
1049 		 *
1050 		 * if ((rt->rt_flags & RTF_HOST) == 0 &&
1051 		 *     SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
1052 		 *	   rt->rt_flags |= RTF_CLONING;
1053 		 */
1054 		if ((rt->rt_flags & RTF_CLONING) ||
1055 		    ((rt->rt_flags & RTF_LLINFO) && !ln)) {
1056 			/*
1057 			 * Case 1: This route should come from a route to
1058 			 * interface (RTF_CLONING case) or the route should be
1059 			 * treated as on-link but is currently not
1060 			 * (RTF_LLINFO && !ln case).
1061 			 */
1062 			rt_setgate(rt, rt_key(rt),
1063 				   (struct sockaddr *)&null_sdl, 0);
1064 			gate = rt->rt_gateway;
1065 			SDL(gate)->sdl_type = ifp->if_type;
1066 			SDL(gate)->sdl_index = ifp->if_index;
1067 			if (ln)
1068 				nd6_llinfo_settimer(ln, 0);
1069 			if ((rt->rt_flags & RTF_CLONING) != 0)
1070 				break;
1071 		}
1072 		/*
1073 		 * In IPv4 code, we try to announce new RTF_ANNOUNCE entry here.
1074 		 * We don't do that here since llinfo is not ready yet.
1075 		 *
1076 		 * There are also couple of other things to be discussed:
1077 		 * - unsolicited NA code needs improvement beforehand
1078 		 * - RFC2461 says we MAY send multicast unsolicited NA
1079 		 *   (7.2.6 paragraph 4), however, it also says that we
1080 		 *   SHOULD provide a mechanism to prevent multicast NA storm.
1081 		 *   we don't have anything like it right now.
1082 		 *   note that the mechanism needs a mutual agreement
1083 		 *   between proxies, which means that we need to implement
1084 		 *   a new protocol, or a new kludge.
1085 		 * - from RFC2461 6.2.4, host MUST NOT send an unsolicited NA.
1086 		 *   we need to check ip6forwarding before sending it.
1087 		 *   (or should we allow proxy ND configuration only for
1088 		 *   routers?  there's no mention about proxy ND from hosts)
1089 		 */
1090 #if 0
1091 		/* XXX it does not work */
1092 		if (rt->rt_flags & RTF_ANNOUNCE)
1093 			nd6_na_output(ifp,
1094 			      &SIN6(rt_key(rt))->sin6_addr,
1095 			      &SIN6(rt_key(rt))->sin6_addr,
1096 			      ip6_forwarding ? ND_NA_FLAG_ROUTER : 0,
1097 			      1, NULL);
1098 #endif
1099 		/* FALLTHROUGH */
1100 	case RTM_RESOLVE:
1101 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) == 0) {
1102 			/*
1103 			 * Address resolution isn't necessary for a point to
1104 			 * point link, so we can skip this test for a p2p link.
1105 			 */
1106 			if (gate->sa_family != AF_LINK ||
1107 			    gate->sa_len < sizeof(null_sdl)) {
1108 				log(LOG_DEBUG,
1109 				    "nd6_rtrequest: bad gateway value: %s\n",
1110 				    ifp->if_xname);
1111 				break;
1112 			}
1113 			SDL(gate)->sdl_type = ifp->if_type;
1114 			SDL(gate)->sdl_index = ifp->if_index;
1115 		}
1116 		if (ln != NULL)
1117 			break;	/* This happens on a route change */
1118 		/*
1119 		 * Case 2: This route may come from cloning, or a manual route
1120 		 * add with a LL address.
1121 		 */
1122 		R_Malloc(ln, struct llinfo_nd6 *, sizeof(*ln));
1123 		rt->rt_llinfo = (caddr_t)ln;
1124 		if (!ln) {
1125 			log(LOG_DEBUG, "nd6_rtrequest: malloc failed\n");
1126 			break;
1127 		}
1128 		nd6_inuse++;
1129 		nd6_allocated++;
1130 		Bzero(ln, sizeof(*ln));
1131 		ln->ln_rt = rt;
1132 		timeout_set(&ln->ln_timer_ch, nd6_llinfo_timer, ln);
1133 		/* this is required for "ndp" command. - shin */
1134 		if (req == RTM_ADD) {
1135 		        /*
1136 			 * gate should have some valid AF_LINK entry,
1137 			 * and ln->ln_expire should have some lifetime
1138 			 * which is specified by ndp command.
1139 			 */
1140 			ln->ln_state = ND6_LLINFO_REACHABLE;
1141 			ln->ln_byhint = 0;
1142 		} else {
1143 		        /*
1144 			 * When req == RTM_RESOLVE, rt is created and
1145 			 * initialized in rtrequest(), so rt_expire is 0.
1146 			 */
1147 			ln->ln_state = ND6_LLINFO_NOSTATE;
1148 			nd6_llinfo_settimer(ln, 0);
1149 		}
1150 		rt->rt_flags |= RTF_LLINFO;
1151 		ln->ln_next = llinfo_nd6.ln_next;
1152 		llinfo_nd6.ln_next = ln;
1153 		ln->ln_prev = &llinfo_nd6;
1154 		ln->ln_next->ln_prev = ln;
1155 
1156 		/*
1157 		 * If we have too many cache entries, initiate immediate
1158 		 * purging for some "less recently used" entries.  Note that
1159 		 * we cannot directly call nd6_free() here because it would
1160 		 * cause re-entering rtable related routines triggering an LOR
1161 		 * problem for FreeBSD.
1162 		 */
1163 		if (ip6_neighborgcthresh >= 0 &&
1164 		    nd6_inuse >= ip6_neighborgcthresh) {
1165 			int i;
1166 
1167 			for (i = 0; i < 10 && llinfo_nd6.ln_prev != ln; i++) {
1168 				struct llinfo_nd6 *ln_end = llinfo_nd6.ln_prev;
1169 
1170 				/* Move this entry to the head */
1171 				LN_DEQUEUE(ln_end);
1172 				LN_INSERTHEAD(ln_end);
1173 
1174 				if (ND6_LLINFO_PERMANENT(ln_end))
1175 					continue;
1176 
1177 				if (ln_end->ln_state > ND6_LLINFO_INCOMPLETE)
1178 					ln_end->ln_state = ND6_LLINFO_STALE;
1179 				else
1180 					ln_end->ln_state = ND6_LLINFO_PURGE;
1181 				nd6_llinfo_settimer(ln_end, 0);
1182 			}
1183 		}
1184 
1185 		/*
1186 		 * check if rt_key(rt) is one of my address assigned
1187 		 * to the interface.
1188 		 */
1189 		ifa = (struct ifaddr *)in6ifa_ifpwithaddr(rt->rt_ifp,
1190 		    &SIN6(rt_key(rt))->sin6_addr);
1191 		if (ifa) {
1192 			caddr_t macp = nd6_ifptomac(ifp);
1193 			nd6_llinfo_settimer(ln, -1);
1194 			ln->ln_state = ND6_LLINFO_REACHABLE;
1195 			ln->ln_byhint = 0;
1196 			if (macp) {
1197 				Bcopy(macp, LLADDR(SDL(gate)), ifp->if_addrlen);
1198 				SDL(gate)->sdl_alen = ifp->if_addrlen;
1199 			}
1200 			if (nd6_useloopback) {
1201 				rt->rt_ifp = lo0ifp;	/*XXX*/
1202 				/*
1203 				 * Make sure rt_ifa be equal to the ifaddr
1204 				 * corresponding to the address.
1205 				 * We need this because when we refer
1206 				 * rt_ifa->ia6_flags in ip6_input, we assume
1207 				 * that the rt_ifa points to the address instead
1208 				 * of the loopback address.
1209 				 */
1210 				if (ifa != rt->rt_ifa) {
1211 					IFAFREE(rt->rt_ifa);
1212 					ifa->ifa_refcnt++;
1213 					rt->rt_ifa = ifa;
1214 				}
1215 			}
1216 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
1217 			nd6_llinfo_settimer(ln, -1);
1218 			ln->ln_state = ND6_LLINFO_REACHABLE;
1219 			ln->ln_byhint = 0;
1220 
1221 			/* join solicited node multicast for proxy ND */
1222 			if (ifp->if_flags & IFF_MULTICAST) {
1223 				struct in6_addr llsol;
1224 				int error;
1225 
1226 				llsol = SIN6(rt_key(rt))->sin6_addr;
1227 				llsol.s6_addr16[0] = htons(0xff02);
1228 				llsol.s6_addr16[1] = htons(ifp->if_index);
1229 				llsol.s6_addr32[1] = 0;
1230 				llsol.s6_addr32[2] = htonl(1);
1231 				llsol.s6_addr8[12] = 0xff;
1232 
1233 				if (in6_addmulti(&llsol, ifp, &error)) {
1234 					nd6log((LOG_ERR, "%s: failed to join "
1235 					    "%s (errno=%d)\n", ifp->if_xname,
1236 					    ip6_sprintf(&llsol), error));
1237 				}
1238 			}
1239 		}
1240 		break;
1241 
1242 	case RTM_DELETE:
1243 		if (!ln)
1244 			break;
1245 		/* leave from solicited node multicast for proxy ND */
1246 		if ((rt->rt_flags & RTF_ANNOUNCE) != 0 &&
1247 		    (ifp->if_flags & IFF_MULTICAST) != 0) {
1248 			struct in6_addr llsol;
1249 			struct in6_multi *in6m;
1250 
1251 			llsol = SIN6(rt_key(rt))->sin6_addr;
1252 			llsol.s6_addr16[0] = htons(0xff02);
1253 			llsol.s6_addr16[1] = htons(ifp->if_index);
1254 			llsol.s6_addr32[1] = 0;
1255 			llsol.s6_addr32[2] = htonl(1);
1256 			llsol.s6_addr8[12] = 0xff;
1257 
1258 			IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1259 			if (in6m)
1260 				in6_delmulti(in6m);
1261 		}
1262 		nd6_inuse--;
1263 		ln->ln_next->ln_prev = ln->ln_prev;
1264 		ln->ln_prev->ln_next = ln->ln_next;
1265 		ln->ln_prev = NULL;
1266 		nd6_llinfo_settimer(ln, -1);
1267 		rt->rt_llinfo = 0;
1268 		rt->rt_flags &= ~RTF_LLINFO;
1269 		if (ln->ln_hold)
1270 			m_freem(ln->ln_hold);
1271 		Free((caddr_t)ln);
1272 	}
1273 }
1274 
1275 int
1276 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1277 {
1278 	struct in6_drlist *drl = (struct in6_drlist *)data;
1279 	struct in6_oprlist *oprl = (struct in6_oprlist *)data;
1280 	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1281 	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1282 	struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1283 	struct nd_defrouter *dr;
1284 	struct nd_prefix *pr;
1285 	struct rtentry *rt;
1286 	int i = 0, error = 0;
1287 	int s;
1288 
1289 	switch (cmd) {
1290 	case SIOCGDRLST_IN6:
1291 		/*
1292 		 * obsolete API, use sysctl under net.inet6.icmp6
1293 		 */
1294 		bzero(drl, sizeof(*drl));
1295 		s = splsoftnet();
1296 		dr = TAILQ_FIRST(&nd_defrouter);
1297 		while (dr && i < DRLSTSIZ) {
1298 			drl->defrouter[i].rtaddr = dr->rtaddr;
1299 			if (IN6_IS_ADDR_LINKLOCAL(&drl->defrouter[i].rtaddr)) {
1300 				/* XXX: need to this hack for KAME stack */
1301 				drl->defrouter[i].rtaddr.s6_addr16[1] = 0;
1302 			} else
1303 				log(LOG_ERR,
1304 				    "default router list contains a "
1305 				    "non-linklocal address(%s)\n",
1306 				    ip6_sprintf(&drl->defrouter[i].rtaddr));
1307 
1308 			drl->defrouter[i].flags = dr->flags;
1309 			drl->defrouter[i].rtlifetime = dr->rtlifetime;
1310 			drl->defrouter[i].expire = dr->expire;
1311 			drl->defrouter[i].if_index = dr->ifp->if_index;
1312 			i++;
1313 			dr = TAILQ_NEXT(dr, dr_entry);
1314 		}
1315 		splx(s);
1316 		break;
1317 	case SIOCGPRLST_IN6:
1318 		/*
1319 		 * obsolete API, use sysctl under net.inet6.icmp6
1320 		 *
1321 		 * XXX the structure in6_prlist was changed in backward-
1322 		 * incompatible manner.  in6_oprlist is used for SIOCGPRLST_IN6,
1323 		 * in6_prlist is used for nd6_sysctl() - fill_prlist().
1324 		 */
1325 		/*
1326 		 * XXX meaning of fields, especially "raflags", is very
1327 		 * different between RA prefix list and RR/static prefix list.
1328 		 * how about separating ioctls into two?
1329 		 */
1330 		bzero(oprl, sizeof(*oprl));
1331 		s = splsoftnet();
1332 		pr = LIST_FIRST(&nd_prefix);
1333 		while (pr && i < PRLSTSIZ) {
1334 			struct nd_pfxrouter *pfr;
1335 			int j;
1336 
1337 			oprl->prefix[i].prefix = pr->ndpr_prefix.sin6_addr;
1338 			oprl->prefix[i].raflags = pr->ndpr_raf;
1339 			oprl->prefix[i].prefixlen = pr->ndpr_plen;
1340 			oprl->prefix[i].vltime = pr->ndpr_vltime;
1341 			oprl->prefix[i].pltime = pr->ndpr_pltime;
1342 			oprl->prefix[i].if_index = pr->ndpr_ifp->if_index;
1343 			oprl->prefix[i].expire = pr->ndpr_expire;
1344 
1345 			pfr = LIST_FIRST(&pr->ndpr_advrtrs);
1346 			j = 0;
1347 			while(pfr) {
1348 				if (j < DRLSTSIZ) {
1349 #define RTRADDR oprl->prefix[i].advrtr[j]
1350 					RTRADDR = pfr->router->rtaddr;
1351 					if (IN6_IS_ADDR_LINKLOCAL(&RTRADDR)) {
1352 						/* XXX: hack for KAME */
1353 						RTRADDR.s6_addr16[1] = 0;
1354 					} else
1355 						log(LOG_ERR,
1356 						    "a router(%s) advertises "
1357 						    "a prefix with "
1358 						    "non-link local address\n",
1359 						    ip6_sprintf(&RTRADDR));
1360 #undef RTRADDR
1361 				}
1362 				j++;
1363 				pfr = LIST_NEXT(pfr, pfr_entry);
1364 			}
1365 			oprl->prefix[i].advrtrs = j;
1366 			oprl->prefix[i].origin = PR_ORIG_RA;
1367 
1368 			i++;
1369 			pr = LIST_NEXT(pr, ndpr_entry);
1370 		}
1371 		splx(s);
1372 
1373 		break;
1374 	case OSIOCGIFINFO_IN6:
1375 		/* XXX: old ndp(8) assumes a positive value for linkmtu. */
1376 		bzero(&ndi->ndi, sizeof(ndi->ndi));
1377 		ndi->ndi.linkmtu = IN6_LINKMTU(ifp);
1378 		ndi->ndi.maxmtu = ND_IFINFO(ifp)->maxmtu;
1379 		ndi->ndi.basereachable = ND_IFINFO(ifp)->basereachable;
1380 		ndi->ndi.reachable = ND_IFINFO(ifp)->reachable;
1381 		ndi->ndi.retrans = ND_IFINFO(ifp)->retrans;
1382 		ndi->ndi.flags = ND_IFINFO(ifp)->flags;
1383 		ndi->ndi.recalctm = ND_IFINFO(ifp)->recalctm;
1384 		ndi->ndi.chlim = ND_IFINFO(ifp)->chlim;
1385 		break;
1386 	case SIOCGIFINFO_IN6:
1387 		ndi->ndi = *ND_IFINFO(ifp);
1388 		break;
1389 	case SIOCSIFINFO_FLAGS:
1390 		ND_IFINFO(ifp)->flags = ndi->ndi.flags;
1391 		break;
1392 	case SIOCSNDFLUSH_IN6:	/* XXX: the ioctl name is confusing... */
1393 		/* sync kernel routing table with the default router list */
1394 		defrouter_reset();
1395 		defrouter_select();
1396 		break;
1397 	case SIOCSPFXFLUSH_IN6:
1398 	{
1399 		/* flush all the prefix advertised by routers */
1400 		struct nd_prefix *pr, *next;
1401 
1402 		s = splsoftnet();
1403 		for (pr = LIST_FIRST(&nd_prefix); pr; pr = next) {
1404 			struct in6_ifaddr *ia, *ia_next;
1405 
1406 			next = LIST_NEXT(pr, ndpr_entry);
1407 
1408 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1409 				continue; /* XXX */
1410 
1411 			/* do we really have to remove addresses as well? */
1412 			for (ia = in6_ifaddr; ia; ia = ia_next) {
1413 				/* ia might be removed.  keep the next ptr. */
1414 				ia_next = ia->ia_next;
1415 
1416 				if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1417 					continue;
1418 
1419 				if (ia->ia6_ndpr == pr)
1420 					in6_purgeaddr(&ia->ia_ifa);
1421 			}
1422 			prelist_remove(pr);
1423 		}
1424 		splx(s);
1425 		break;
1426 	}
1427 	case SIOCSRTRFLUSH_IN6:
1428 	{
1429 		/* flush all the default routers */
1430 		struct nd_defrouter *dr, *next;
1431 
1432 		s = splsoftnet();
1433 		defrouter_reset();
1434 		for (dr = TAILQ_FIRST(&nd_defrouter); dr; dr = next) {
1435 			next = TAILQ_NEXT(dr, dr_entry);
1436 			defrtrlist_del(dr);
1437 		}
1438 		defrouter_select();
1439 		splx(s);
1440 		break;
1441 	}
1442 	case SIOCGNBRINFO_IN6:
1443 	{
1444 		struct llinfo_nd6 *ln;
1445 		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1446 
1447 		/*
1448 		 * XXX: KAME specific hack for scoped addresses
1449 		 *      XXXX: for other scopes than link-local?
1450 		 */
1451 		if (IN6_IS_ADDR_LINKLOCAL(&nbi->addr) ||
1452 		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi->addr)) {
1453 			u_int16_t *idp = (u_int16_t *)&nb_addr.s6_addr[2];
1454 
1455 			if (*idp == 0)
1456 				*idp = htons(ifp->if_index);
1457 		}
1458 
1459 		s = splsoftnet();
1460 		if ((rt = nd6_lookup(&nb_addr, 0, ifp)) == NULL ||
1461 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) == NULL) {
1462 			error = EINVAL;
1463 			splx(s);
1464 			break;
1465 		}
1466 		nbi->state = ln->ln_state;
1467 		nbi->asked = ln->ln_asked;
1468 		nbi->isrouter = ln->ln_router;
1469 		nbi->expire = ln->ln_expire;
1470 		splx(s);
1471 
1472 		break;
1473 	}
1474 	case SIOCGDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1475 		ndif->ifindex = nd6_defifindex;
1476 		break;
1477 	case SIOCSDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1478 		return (nd6_setdefaultiface(ndif->ifindex));
1479 		break;
1480 	}
1481 	return (error);
1482 }
1483 
1484 /*
1485  * Create neighbor cache entry and cache link-layer address,
1486  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1487  *
1488  * type - ICMP6 type
1489  * code - type dependent information
1490  */
1491 struct rtentry *
1492 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1493 	int lladdrlen, int type, int code)
1494 {
1495 	struct rtentry *rt = NULL;
1496 	struct llinfo_nd6 *ln = NULL;
1497 	int is_newentry;
1498 	struct sockaddr_dl *sdl = NULL;
1499 	int do_update;
1500 	int olladdr;
1501 	int llchange;
1502 	int newstate = 0;
1503 
1504 	if (!ifp)
1505 		panic("ifp == NULL in nd6_cache_lladdr");
1506 	if (!from)
1507 		panic("from == NULL in nd6_cache_lladdr");
1508 
1509 	/* nothing must be updated for unspecified address */
1510 	if (IN6_IS_ADDR_UNSPECIFIED(from))
1511 		return NULL;
1512 
1513 	/*
1514 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
1515 	 * the caller.
1516 	 *
1517 	 * XXX If the link does not have link-layer address, what should
1518 	 * we do? (ifp->if_addrlen == 0)
1519 	 * Spec says nothing in sections for RA, RS and NA.  There's small
1520 	 * description on it in NS section (RFC 2461 7.2.3).
1521 	 */
1522 
1523 	rt = nd6_lookup(from, 0, ifp);
1524 	if (!rt) {
1525 #if 0
1526 		/* nothing must be done if there's no lladdr */
1527 		if (!lladdr || !lladdrlen)
1528 			return NULL;
1529 #endif
1530 
1531 		rt = nd6_lookup(from, 1, ifp);
1532 		is_newentry = 1;
1533 	} else {
1534 		/* do nothing if static ndp is set */
1535 		if (rt->rt_flags & RTF_STATIC)
1536 			return NULL;
1537 		is_newentry = 0;
1538 	}
1539 
1540 	if (!rt)
1541 		return NULL;
1542 	if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
1543 fail:
1544 		(void)nd6_free(rt, 0);
1545 		return NULL;
1546 	}
1547 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1548 	if (!ln)
1549 		goto fail;
1550 	if (!rt->rt_gateway)
1551 		goto fail;
1552 	if (rt->rt_gateway->sa_family != AF_LINK)
1553 		goto fail;
1554 	sdl = SDL(rt->rt_gateway);
1555 
1556 	olladdr = (sdl->sdl_alen) ? 1 : 0;
1557 	if (olladdr && lladdr) {
1558 		if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen))
1559 			llchange = 1;
1560 		else
1561 			llchange = 0;
1562 	} else
1563 		llchange = 0;
1564 
1565 	/*
1566 	 * newentry olladdr  lladdr  llchange	(*=record)
1567 	 *	0	n	n	--	(1)
1568 	 *	0	y	n	--	(2)
1569 	 *	0	n	y	--	(3) * STALE
1570 	 *	0	y	y	n	(4) *
1571 	 *	0	y	y	y	(5) * STALE
1572 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
1573 	 *	1	--	y	--	(7) * STALE
1574 	 */
1575 
1576 	if (lladdr) {		/* (3-5) and (7) */
1577 		/*
1578 		 * Record source link-layer address
1579 		 * XXX is it dependent to ifp->if_type?
1580 		 */
1581 		sdl->sdl_alen = ifp->if_addrlen;
1582 		bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
1583 	}
1584 
1585 	if (!is_newentry) {
1586 		if ((!olladdr && lladdr) ||		/* (3) */
1587 		    (olladdr && lladdr && llchange)) {	/* (5) */
1588 			do_update = 1;
1589 			newstate = ND6_LLINFO_STALE;
1590 		} else					/* (1-2,4) */
1591 			do_update = 0;
1592 	} else {
1593 		do_update = 1;
1594 		if (!lladdr)				/* (6) */
1595 			newstate = ND6_LLINFO_NOSTATE;
1596 		else					/* (7) */
1597 			newstate = ND6_LLINFO_STALE;
1598 	}
1599 
1600 	if (do_update) {
1601 		/*
1602 		 * Update the state of the neighbor cache.
1603 		 */
1604 		ln->ln_state = newstate;
1605 
1606 		if (ln->ln_state == ND6_LLINFO_STALE) {
1607 			/*
1608 			 * XXX: since nd6_output() below will cause
1609 			 * state transition to DELAY and reset the timer,
1610 			 * we must set the timer now, although it is actually
1611 			 * meaningless.
1612 			 */
1613 			nd6_llinfo_settimer(ln, (long)nd6_gctimer * hz);
1614 
1615 			if (ln->ln_hold) {
1616 				struct mbuf *n = ln->ln_hold;
1617 				ln->ln_hold = NULL;
1618 				/*
1619 				 * we assume ifp is not a p2p here, so just
1620 				 * set the 2nd argument as the 1st one.
1621 				 */
1622 				nd6_output(ifp, ifp, n,
1623 				    (struct sockaddr_in6 *)rt_key(rt), rt);
1624 				if (ln->ln_hold == n) {
1625 					/* n is back in ln_hold. Discard. */
1626 					m_freem(ln->ln_hold);
1627 					ln->ln_hold = NULL;
1628 				}
1629 			}
1630 		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1631 			/* probe right away */
1632 			nd6_llinfo_settimer((void *)ln, 0);
1633 		}
1634 	}
1635 
1636 	/*
1637 	 * ICMP6 type dependent behavior.
1638 	 *
1639 	 * NS: clear IsRouter if new entry
1640 	 * RS: clear IsRouter
1641 	 * RA: set IsRouter if there's lladdr
1642 	 * redir: clear IsRouter if new entry
1643 	 *
1644 	 * RA case, (1):
1645 	 * The spec says that we must set IsRouter in the following cases:
1646 	 * - If lladdr exist, set IsRouter.  This means (1-5).
1647 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
1648 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1649 	 * A question arises for (1) case.  (1) case has no lladdr in the
1650 	 * neighbor cache, this is similar to (6).
1651 	 * This case is rare but we figured that we MUST NOT set IsRouter.
1652 	 *
1653 	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
1654 	 *							D R
1655 	 *	0	n	n	--	(1)	c   ?     s
1656 	 *	0	y	n	--	(2)	c   s     s
1657 	 *	0	n	y	--	(3)	c   s     s
1658 	 *	0	y	y	n	(4)	c   s     s
1659 	 *	0	y	y	y	(5)	c   s     s
1660 	 *	1	--	n	--	(6) c	c 	c s
1661 	 *	1	--	y	--	(7) c	c   s	c s
1662 	 *
1663 	 *					(c=clear s=set)
1664 	 */
1665 	switch (type & 0xff) {
1666 	case ND_NEIGHBOR_SOLICIT:
1667 		/*
1668 		 * New entry must have is_router flag cleared.
1669 		 */
1670 		if (is_newentry)	/* (6-7) */
1671 			ln->ln_router = 0;
1672 		break;
1673 	case ND_REDIRECT:
1674 		/*
1675 		 * If the icmp is a redirect to a better router, always set the
1676 		 * is_router flag.  Otherwise, if the entry is newly created,
1677 		 * clear the flag.  [RFC 2461, sec 8.3]
1678 		 */
1679 		if (code == ND_REDIRECT_ROUTER)
1680 			ln->ln_router = 1;
1681 		else if (is_newentry) /* (6-7) */
1682 			ln->ln_router = 0;
1683 		break;
1684 	case ND_ROUTER_SOLICIT:
1685 		/*
1686 		 * is_router flag must always be cleared.
1687 		 */
1688 		ln->ln_router = 0;
1689 		break;
1690 	case ND_ROUTER_ADVERT:
1691 		/*
1692 		 * Mark an entry with lladdr as a router.
1693 		 */
1694 		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
1695 		    (is_newentry && lladdr)) {			/* (7) */
1696 			ln->ln_router = 1;
1697 		}
1698 		break;
1699 	}
1700 
1701 	/*
1702 	 * When the link-layer address of a router changes, select the
1703 	 * best router again.  In particular, when the neighbor entry is newly
1704 	 * created, it might affect the selection policy.
1705 	 * Question: can we restrict the first condition to the "is_newentry"
1706 	 * case?
1707 	 * XXX: when we hear an RA from a new router with the link-layer
1708 	 * address option, defrouter_select() is called twice, since
1709 	 * defrtrlist_update called the function as well.  However, I believe
1710 	 * we can compromise the overhead, since it only happens the first
1711 	 * time.
1712 	 * XXX: although defrouter_select() should not have a bad effect
1713 	 * for those are not autoconfigured hosts, we explicitly avoid such
1714 	 * cases for safety.
1715 	 */
1716 	if (do_update && ln->ln_router && !ip6_forwarding && ip6_accept_rtadv)
1717 		defrouter_select();
1718 
1719 	return rt;
1720 }
1721 
1722 static void
1723 nd6_slowtimo(void *ignored_arg)
1724 {
1725 	int s = splsoftnet();
1726 	struct nd_ifinfo *nd6if;
1727 	struct ifnet *ifp;
1728 
1729 	timeout_set(&nd6_slowtimo_ch, nd6_slowtimo, NULL);
1730 	timeout_add_sec(&nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL);
1731 	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
1732 	{
1733 		nd6if = ND_IFINFO(ifp);
1734 		if (nd6if->basereachable && /* already initialized */
1735 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1736 			/*
1737 			 * Since reachable time rarely changes by router
1738 			 * advertisements, we SHOULD insure that a new random
1739 			 * value gets recomputed at least once every few hours.
1740 			 * (RFC 2461, 6.3.4)
1741 			 */
1742 			nd6if->recalctm = nd6_recalc_reachtm_interval;
1743 			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1744 		}
1745 	}
1746 	splx(s);
1747 }
1748 
1749 #define senderr(e) { error = (e); goto bad;}
1750 int
1751 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
1752 	struct sockaddr_in6 *dst, struct rtentry *rt0)
1753 {
1754 	struct mbuf *m = m0;
1755 	struct rtentry *rt = rt0;
1756 	struct sockaddr_in6 *gw6 = NULL;
1757 	struct llinfo_nd6 *ln = NULL;
1758 	int error = 0;
1759 #ifdef IPSEC
1760 	struct m_tag *mtag;
1761 #endif /* IPSEC */
1762 
1763 	if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1764 		goto sendpkt;
1765 
1766 	if (nd6_need_cache(ifp) == 0)
1767 		goto sendpkt;
1768 
1769 	/*
1770 	 * next hop determination.  This routine is derived from ether_output.
1771 	 */
1772 	if (rt) {
1773 		if ((rt->rt_flags & RTF_UP) == 0) {
1774 			if ((rt0 = rt = rtalloc1((struct sockaddr *)dst,
1775 			    1, 0)) != NULL)
1776 			{
1777 				rt->rt_refcnt--;
1778 				if (rt->rt_ifp != ifp)
1779 					senderr(EHOSTUNREACH);
1780 			} else
1781 				senderr(EHOSTUNREACH);
1782 		}
1783 
1784 		if (rt->rt_flags & RTF_GATEWAY) {
1785 			gw6 = (struct sockaddr_in6 *)rt->rt_gateway;
1786 
1787 			/*
1788 			 * We skip link-layer address resolution and NUD
1789 			 * if the gateway is not a neighbor from ND point
1790 			 * of view, regardless of the value of nd_ifinfo.flags.
1791 			 * The second condition is a bit tricky; we skip
1792 			 * if the gateway is our own address, which is
1793 			 * sometimes used to install a route to a p2p link.
1794 			 */
1795 			if (!nd6_is_addr_neighbor(gw6, ifp) ||
1796 			    in6ifa_ifpwithaddr(ifp, &gw6->sin6_addr)) {
1797 				/*
1798 				 * We allow this kind of tricky route only
1799 				 * when the outgoing interface is p2p.
1800 				 * XXX: we may need a more generic rule here.
1801 				 */
1802 				if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
1803 					senderr(EHOSTUNREACH);
1804 
1805 				goto sendpkt;
1806 			}
1807 
1808 			if (rt->rt_gwroute == 0)
1809 				goto lookup;
1810 			if (((rt = rt->rt_gwroute)->rt_flags & RTF_UP) == 0) {
1811 				rtfree(rt); rt = rt0;
1812 			lookup:
1813 				rt->rt_gwroute = rtalloc1(rt->rt_gateway, 1, 0);
1814 				if ((rt = rt->rt_gwroute) == 0)
1815 					senderr(EHOSTUNREACH);
1816 			}
1817 		}
1818 	}
1819 
1820 	/*
1821 	 * Address resolution or Neighbor Unreachability Detection
1822 	 * for the next hop.
1823 	 * At this point, the destination of the packet must be a unicast
1824 	 * or an anycast address(i.e. not a multicast).
1825 	 */
1826 
1827 	/* Look up the neighbor cache for the nexthop */
1828 	if (rt && (rt->rt_flags & RTF_LLINFO) != 0)
1829 		ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1830 	else {
1831 		/*
1832 		 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
1833 		 * the condition below is not very efficient.  But we believe
1834 		 * it is tolerable, because this should be a rare case.
1835 		 */
1836 		if (nd6_is_addr_neighbor(dst, ifp) &&
1837 		    (rt = nd6_lookup(&dst->sin6_addr, 1, ifp)) != NULL)
1838 			ln = (struct llinfo_nd6 *)rt->rt_llinfo;
1839 	}
1840 	if (!ln || !rt) {
1841 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
1842 		    !(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
1843 			log(LOG_DEBUG,
1844 			    "nd6_output: can't allocate llinfo for %s "
1845 			    "(ln=%p, rt=%p)\n",
1846 			    ip6_sprintf(&dst->sin6_addr), ln, rt);
1847 			senderr(EIO);	/* XXX: good error? */
1848 		}
1849 
1850 		goto sendpkt;	/* send anyway */
1851 	}
1852 
1853 	/*
1854 	 * Move this entry to the head of the queue so that it is less likely
1855 	 * for this entry to be a target of forced garbage collection (see
1856 	 * nd6_rtrequest()).
1857 	 */
1858 	LN_DEQUEUE(ln);
1859 	LN_INSERTHEAD(ln);
1860 
1861 	/* We don't have to do link-layer address resolution on a p2p link. */
1862 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
1863 	    ln->ln_state < ND6_LLINFO_REACHABLE) {
1864 		ln->ln_state = ND6_LLINFO_STALE;
1865 		nd6_llinfo_settimer(ln, (long)nd6_gctimer * hz);
1866 	}
1867 
1868 	/*
1869 	 * The first time we send a packet to a neighbor whose entry is
1870 	 * STALE, we have to change the state to DELAY and a sets a timer to
1871 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
1872 	 * neighbor unreachability detection on expiration.
1873 	 * (RFC 2461 7.3.3)
1874 	 */
1875 	if (ln->ln_state == ND6_LLINFO_STALE) {
1876 		ln->ln_asked = 0;
1877 		ln->ln_state = ND6_LLINFO_DELAY;
1878 		nd6_llinfo_settimer(ln, nd6_delay * hz);
1879 	}
1880 
1881 	/*
1882 	 * If the neighbor cache entry has a state other than INCOMPLETE
1883 	 * (i.e. its link-layer address is already resolved), just
1884 	 * send the packet.
1885 	 */
1886 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE)
1887 		goto sendpkt;
1888 
1889 	/*
1890 	 * There is a neighbor cache entry, but no ethernet address
1891 	 * response yet.  Replace the held mbuf (if any) with this
1892 	 * latest one.
1893 	 */
1894 	if (ln->ln_state == ND6_LLINFO_NOSTATE)
1895 		ln->ln_state = ND6_LLINFO_INCOMPLETE;
1896 	if (ln->ln_hold)
1897 		m_freem(ln->ln_hold);
1898 	ln->ln_hold = m;
1899 	/*
1900 	 * If there has been no NS for the neighbor after entering the
1901 	 * INCOMPLETE state, send the first solicitation.
1902 	 */
1903 	if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
1904 		ln->ln_asked++;
1905 		nd6_llinfo_settimer(ln,
1906 		    (long)ND_IFINFO(ifp)->retrans * hz / 1000);
1907 		nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, 0);
1908 	}
1909 	return (0);
1910 
1911   sendpkt:
1912 #ifdef IPSEC
1913 	/*
1914 	 * If the packet needs outgoing IPsec crypto processing and the
1915 	 * interface doesn't support it, drop it.
1916 	 */
1917 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
1918 #endif /* IPSEC */
1919 
1920 	if ((ifp->if_flags & IFF_LOOPBACK) != 0) {
1921 #ifdef IPSEC
1922 		if (mtag != NULL &&
1923 		    (origifp->if_capabilities & IFCAP_IPSEC) == 0) {
1924 			/* Tell IPsec to do its own crypto. */
1925 			ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
1926 			error = EACCES;
1927 			goto bad;
1928 		}
1929 #endif /* IPSEC */
1930 		return ((*ifp->if_output)(origifp, m, (struct sockaddr *)dst,
1931 		    rt));
1932 	}
1933 #ifdef IPSEC
1934 	if (mtag != NULL &&
1935 	    (ifp->if_capabilities & IFCAP_IPSEC) == 0) {
1936 		/* Tell IPsec to do its own crypto. */
1937 		ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
1938 		error = EACCES;
1939 		goto bad;
1940 	}
1941 #endif /* IPSEC */
1942 	return ((*ifp->if_output)(ifp, m, (struct sockaddr *)dst, rt));
1943 
1944   bad:
1945 	if (m)
1946 		m_freem(m);
1947 	return (error);
1948 }
1949 #undef senderr
1950 
1951 int
1952 nd6_need_cache(struct ifnet *ifp)
1953 {
1954 	/*
1955 	 * XXX: we currently do not make neighbor cache on any interface
1956 	 * other than Ethernet, FDDI and GIF.
1957 	 *
1958 	 * RFC2893 says:
1959 	 * - unidirectional tunnels needs no ND
1960 	 */
1961 	switch (ifp->if_type) {
1962 	case IFT_ETHER:
1963 	case IFT_FDDI:
1964 	case IFT_IEEE1394:
1965 	case IFT_PROPVIRTUAL:
1966 	case IFT_L2VLAN:
1967 	case IFT_IEEE80211:
1968 	case IFT_CARP:
1969 	case IFT_GIF:		/* XXX need more cases? */
1970 		return (1);
1971 	default:
1972 		return (0);
1973 	}
1974 }
1975 
1976 int
1977 nd6_storelladdr(struct ifnet *ifp, struct rtentry *rt, struct mbuf *m,
1978 	struct sockaddr *dst, u_char *desten)
1979 {
1980 	struct sockaddr_dl *sdl;
1981 
1982 	if (m->m_flags & M_MCAST) {
1983 		switch (ifp->if_type) {
1984 		case IFT_ETHER:
1985 		case IFT_FDDI:
1986 			ETHER_MAP_IPV6_MULTICAST(&SIN6(dst)->sin6_addr,
1987 						 desten);
1988 			return (1);
1989 			break;
1990 		default:
1991 			m_freem(m);
1992 			return (0);
1993 		}
1994 	}
1995 
1996 	if (rt == NULL) {
1997 		/* this could happen, if we could not allocate memory */
1998 		m_freem(m);
1999 		return (0);
2000 	}
2001 	if (rt->rt_gateway->sa_family != AF_LINK) {
2002 		printf("nd6_storelladdr: something odd happens\n");
2003 		m_freem(m);
2004 		return (0);
2005 	}
2006 	sdl = SDL(rt->rt_gateway);
2007 	if (sdl->sdl_alen == 0) {
2008 		/* this should be impossible, but we bark here for debugging */
2009 		printf("nd6_storelladdr: sdl_alen == 0, dst=%s, if=%s\n",
2010 		    ip6_sprintf(&SIN6(dst)->sin6_addr), ifp->if_xname);
2011 		m_freem(m);
2012 		return (0);
2013 	}
2014 
2015 	bcopy(LLADDR(sdl), desten, sdl->sdl_alen);
2016 	return (1);
2017 }
2018 
2019 /*
2020  * oldp - syscall arg, need copyout
2021  * newp - syscall arg, need copyin
2022  */
2023 
2024 int
2025 nd6_sysctl(int name, void *oldp, size_t *oldlenp, void *newp,
2026 	size_t newlen)
2027 {
2028 	void *p;
2029 	size_t ol;
2030 	int error;
2031 
2032 	error = 0;
2033 
2034 	if (newp)
2035 		return EPERM;
2036 	if (oldp && !oldlenp)
2037 		return EINVAL;
2038 	ol = oldlenp ? *oldlenp : 0;
2039 
2040 	if (oldp) {
2041 		p = malloc(*oldlenp, M_TEMP, M_WAITOK);
2042 		if (!p)
2043 			return ENOMEM;
2044 	} else
2045 		p = NULL;
2046 	switch (name) {
2047 	case ICMPV6CTL_ND6_DRLIST:
2048 		error = fill_drlist(p, oldlenp, ol);
2049 		if (!error && p && oldp)
2050 			error = copyout(p, oldp, *oldlenp);
2051 		break;
2052 
2053 	case ICMPV6CTL_ND6_PRLIST:
2054 		error = fill_prlist(p, oldlenp, ol);
2055 		if (!error && p && oldp)
2056 			error = copyout(p, oldp, *oldlenp);
2057 		break;
2058 
2059 	default:
2060 		error = ENOPROTOOPT;
2061 		break;
2062 	}
2063 	if (p)
2064 		free(p, M_TEMP);
2065 
2066 	return (error);
2067 }
2068 
2069 static int
2070 fill_drlist(void *oldp, size_t *oldlenp, size_t ol)
2071 {
2072 	int error = 0, s;
2073 	struct in6_defrouter *d = NULL, *de = NULL;
2074 	struct nd_defrouter *dr;
2075 	size_t l;
2076 
2077 	s = splsoftnet();
2078 
2079 	if (oldp) {
2080 		d = (struct in6_defrouter *)oldp;
2081 		de = (struct in6_defrouter *)((caddr_t)oldp + *oldlenp);
2082 	}
2083 	l = 0;
2084 
2085 	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
2086 	     dr = TAILQ_NEXT(dr, dr_entry)) {
2087 
2088 		if (oldp && d + 1 <= de) {
2089 			bzero(d, sizeof(*d));
2090 			d->rtaddr.sin6_family = AF_INET6;
2091 			d->rtaddr.sin6_len = sizeof(struct sockaddr_in6);
2092 			d->rtaddr.sin6_addr = dr->rtaddr;
2093 			in6_recoverscope(&d->rtaddr, &d->rtaddr.sin6_addr,
2094 			    dr->ifp);
2095 			d->flags = dr->flags;
2096 			d->rtlifetime = dr->rtlifetime;
2097 			d->expire = dr->expire;
2098 			d->if_index = dr->ifp->if_index;
2099 		}
2100 
2101 		l += sizeof(*d);
2102 		if (d)
2103 			d++;
2104 	}
2105 
2106 	if (oldp) {
2107 		*oldlenp = l;	/* (caddr_t)d - (caddr_t)oldp */
2108 		if (l > ol)
2109 			error = ENOMEM;
2110 	} else
2111 		*oldlenp = l;
2112 
2113 	splx(s);
2114 
2115 	return (error);
2116 }
2117 
2118 static int
2119 fill_prlist(void *oldp, size_t *oldlenp, size_t ol)
2120 {
2121 	int error = 0, s;
2122 	struct nd_prefix *pr;
2123 	struct in6_prefix *p = NULL;
2124 	struct in6_prefix *pe = NULL;
2125 	size_t l;
2126 
2127 	s = splsoftnet();
2128 
2129 	if (oldp) {
2130 		p = (struct in6_prefix *)oldp;
2131 		pe = (struct in6_prefix *)((caddr_t)oldp + *oldlenp);
2132 	}
2133 	l = 0;
2134 
2135 	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
2136 		u_short advrtrs;
2137 		size_t advance;
2138 		struct sockaddr_in6 *sin6;
2139 		struct sockaddr_in6 *s6;
2140 		struct nd_pfxrouter *pfr;
2141 
2142 		if (oldp && p + 1 <= pe)
2143 		{
2144 			bzero(p, sizeof(*p));
2145 			sin6 = (struct sockaddr_in6 *)(p + 1);
2146 
2147 			p->prefix = pr->ndpr_prefix;
2148 			if (in6_recoverscope(&p->prefix,
2149 			    &p->prefix.sin6_addr, pr->ndpr_ifp) != 0)
2150 				log(LOG_ERR,
2151 				    "scope error in prefix list (%s)\n",
2152 				    ip6_sprintf(&p->prefix.sin6_addr));
2153 			p->raflags = pr->ndpr_raf;
2154 			p->prefixlen = pr->ndpr_plen;
2155 			p->vltime = pr->ndpr_vltime;
2156 			p->pltime = pr->ndpr_pltime;
2157 			p->if_index = pr->ndpr_ifp->if_index;
2158 			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2159 				p->expire = 0;
2160 			else {
2161 				time_t maxexpire;
2162 
2163 				/* XXX: we assume time_t is signed. */
2164 				maxexpire = (-1) &
2165 					~(1 << ((sizeof(maxexpire) * 8) - 1));
2166 				if (pr->ndpr_vltime <
2167 				    maxexpire - pr->ndpr_lastupdate) {
2168 					p->expire = pr->ndpr_lastupdate +
2169 						pr->ndpr_vltime;
2170 				} else
2171 					p->expire = maxexpire;
2172 			}
2173 			p->refcnt = pr->ndpr_refcnt;
2174 			p->flags = pr->ndpr_stateflags;
2175 			p->origin = PR_ORIG_RA;
2176 			advrtrs = 0;
2177 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
2178 				if ((void *)&sin6[advrtrs + 1] > (void *)pe) {
2179 					advrtrs++;
2180 					continue;
2181 				}
2182 				s6 = &sin6[advrtrs];
2183 				s6->sin6_family = AF_INET6;
2184 				s6->sin6_len = sizeof(struct sockaddr_in6);
2185 				s6->sin6_addr = pfr->router->rtaddr;
2186 				in6_recoverscope(s6, &pfr->router->rtaddr,
2187 				    pfr->router->ifp);
2188 				advrtrs++;
2189 			}
2190 			p->advrtrs = advrtrs;
2191 		}
2192 		else {
2193 			advrtrs = 0;
2194 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
2195 				advrtrs++;
2196 		}
2197 
2198 		advance = sizeof(*p) + sizeof(*sin6) * advrtrs;
2199 		l += advance;
2200 		if (p)
2201 			p = (struct in6_prefix *)((caddr_t)p + advance);
2202 	}
2203 
2204 	if (oldp) {
2205 		*oldlenp = l;	/* (caddr_t)d - (caddr_t)oldp */
2206 		if (l > ol)
2207 			error = ENOMEM;
2208 	} else
2209 		*oldlenp = l;
2210 
2211 	splx(s);
2212 
2213 	return (error);
2214 }
2215