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