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