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