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