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