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