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