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