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