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