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