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