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