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