nd6.c revision 299145
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: stable/10/sys/netinet6/nd6.c 299145 2016-05-05 23:06:39Z markj $");
34
35#include "opt_inet.h"
36#include "opt_inet6.h"
37#include "opt_kdtrace.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/lock.h>
52#include <sys/rwlock.h>
53#include <sys/queue.h>
54#include <sys/sdt.h>
55#include <sys/sysctl.h>
56
57#include <net/if.h>
58#include <net/if_arc.h>
59#include <net/if_dl.h>
60#include <net/if_types.h>
61#include <net/iso88025.h>
62#include <net/fddi.h>
63#include <net/route.h>
64#include <net/vnet.h>
65
66#include <netinet/in.h>
67#include <netinet/in_kdtrace.h>
68#include <net/if_llatbl.h>
69#define	L3_ADDR_SIN6(le)	((struct sockaddr_in6 *) L3_ADDR(le))
70#include <netinet/if_ether.h>
71#include <netinet6/in6_var.h>
72#include <netinet/ip6.h>
73#include <netinet6/ip6_var.h>
74#include <netinet6/scope6_var.h>
75#include <netinet6/nd6.h>
76#include <netinet6/in6_ifattach.h>
77#include <netinet/icmp6.h>
78#include <netinet6/send.h>
79
80#include <sys/limits.h>
81
82#include <security/mac/mac_framework.h>
83
84#define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
85#define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
86
87#define SIN6(s) ((const struct sockaddr_in6 *)(s))
88
89/* timer values */
90VNET_DEFINE(int, nd6_prune)	= 1;	/* walk list every 1 seconds */
91VNET_DEFINE(int, nd6_delay)	= 5;	/* delay first probe time 5 second */
92VNET_DEFINE(int, nd6_umaxtries)	= 3;	/* maximum unicast query */
93VNET_DEFINE(int, nd6_mmaxtries)	= 3;	/* maximum multicast query */
94VNET_DEFINE(int, nd6_useloopback) = 1;	/* use loopback interface for
95					 * local traffic */
96VNET_DEFINE(int, nd6_gctimer)	= (60 * 60 * 24); /* 1 day: garbage
97					 * collection timer */
98
99/* preventing too many loops in ND option parsing */
100static VNET_DEFINE(int, nd6_maxndopt) = 10; /* max # of ND options allowed */
101
102VNET_DEFINE(int, nd6_maxnudhint) = 0;	/* max # of subsequent upper
103					 * layer hints */
104static VNET_DEFINE(int, nd6_maxqueuelen) = 1; /* max pkts cached in unresolved
105					 * ND entries */
106#define	V_nd6_maxndopt			VNET(nd6_maxndopt)
107#define	V_nd6_maxqueuelen		VNET(nd6_maxqueuelen)
108
109#ifdef ND6_DEBUG
110VNET_DEFINE(int, nd6_debug) = 1;
111#else
112VNET_DEFINE(int, nd6_debug) = 0;
113#endif
114
115VNET_DEFINE(struct nd_drhead, nd_defrouter);
116VNET_DEFINE(struct nd_prhead, nd_prefix);
117
118VNET_DEFINE(int, nd6_recalc_reachtm_interval) = ND6_RECALC_REACHTM_INTERVAL;
119#define	V_nd6_recalc_reachtm_interval	VNET(nd6_recalc_reachtm_interval)
120
121int	(*send_sendso_input_hook)(struct mbuf *, struct ifnet *, int, int);
122
123static int nd6_is_new_addr_neighbor(struct sockaddr_in6 *,
124	struct ifnet *);
125static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
126static void nd6_slowtimo(void *);
127static int regen_tmpaddr(struct in6_ifaddr *);
128static struct llentry *nd6_free(struct llentry *, int);
129static void nd6_llinfo_timer(void *);
130static void clear_llinfo_pqueue(struct llentry *);
131static int nd6_output_lle(struct ifnet *, struct ifnet *, struct mbuf *,
132	struct sockaddr_in6 *);
133static int nd6_output_ifp(struct ifnet *, struct ifnet *, struct mbuf *,
134    struct sockaddr_in6 *);
135
136static VNET_DEFINE(struct callout, nd6_slowtimo_ch);
137#define	V_nd6_slowtimo_ch		VNET(nd6_slowtimo_ch)
138
139VNET_DEFINE(struct callout, nd6_timer_ch);
140
141void
142nd6_init(void)
143{
144
145	LIST_INIT(&V_nd_prefix);
146
147	/* initialization of the default router list */
148	TAILQ_INIT(&V_nd_defrouter);
149
150	/* start timer */
151	callout_init(&V_nd6_slowtimo_ch, 0);
152	callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
153	    nd6_slowtimo, curvnet);
154
155	nd6_dad_init();
156}
157
158#ifdef VIMAGE
159void
160nd6_destroy()
161{
162
163	callout_drain(&V_nd6_slowtimo_ch);
164	callout_drain(&V_nd6_timer_ch);
165}
166#endif
167
168struct nd_ifinfo *
169nd6_ifattach(struct ifnet *ifp)
170{
171	struct nd_ifinfo *nd;
172
173	nd = malloc(sizeof(*nd), M_IP6NDP, M_WAITOK | M_ZERO);
174	nd->initialized = 1;
175
176	nd->chlim = IPV6_DEFHLIM;
177	nd->basereachable = REACHABLE_TIME;
178	nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
179	nd->retrans = RETRANS_TIMER;
180
181	nd->flags = ND6_IFF_PERFORMNUD;
182
183	/* A loopback interface always has ND6_IFF_AUTO_LINKLOCAL.
184	 * XXXHRS: Clear ND6_IFF_AUTO_LINKLOCAL on an IFT_BRIDGE interface by
185	 * default regardless of the V_ip6_auto_linklocal configuration to
186	 * give a reasonable default behavior.
187	 */
188	if ((V_ip6_auto_linklocal && ifp->if_type != IFT_BRIDGE) ||
189	    (ifp->if_flags & IFF_LOOPBACK))
190		nd->flags |= ND6_IFF_AUTO_LINKLOCAL;
191	/*
192	 * A loopback interface does not need to accept RTADV.
193	 * XXXHRS: Clear ND6_IFF_ACCEPT_RTADV on an IFT_BRIDGE interface by
194	 * default regardless of the V_ip6_accept_rtadv configuration to
195	 * prevent the interface from accepting RA messages arrived
196	 * on one of the member interfaces with ND6_IFF_ACCEPT_RTADV.
197	 */
198	if (V_ip6_accept_rtadv &&
199	    !(ifp->if_flags & IFF_LOOPBACK) &&
200	    (ifp->if_type != IFT_BRIDGE))
201			nd->flags |= ND6_IFF_ACCEPT_RTADV;
202	if (V_ip6_no_radr && !(ifp->if_flags & IFF_LOOPBACK))
203		nd->flags |= ND6_IFF_NO_RADR;
204
205	/* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
206	nd6_setmtu0(ifp, nd);
207
208	return nd;
209}
210
211void
212nd6_ifdetach(struct nd_ifinfo *nd)
213{
214
215	free(nd, M_IP6NDP);
216}
217
218/*
219 * Reset ND level link MTU. This function is called when the physical MTU
220 * changes, which means we might have to adjust the ND level MTU.
221 */
222void
223nd6_setmtu(struct ifnet *ifp)
224{
225	if (ifp->if_afdata[AF_INET6] == NULL)
226		return;
227
228	nd6_setmtu0(ifp, ND_IFINFO(ifp));
229}
230
231/* XXX todo: do not maintain copy of ifp->if_mtu in ndi->maxmtu */
232void
233nd6_setmtu0(struct ifnet *ifp, struct nd_ifinfo *ndi)
234{
235	u_int32_t omaxmtu;
236
237	omaxmtu = ndi->maxmtu;
238
239	switch (ifp->if_type) {
240	case IFT_ARCNET:
241		ndi->maxmtu = MIN(ARC_PHDS_MAXMTU, ifp->if_mtu); /* RFC2497 */
242		break;
243	case IFT_FDDI:
244		ndi->maxmtu = MIN(FDDIIPMTU, ifp->if_mtu); /* RFC2467 */
245		break;
246	case IFT_ISO88025:
247		 ndi->maxmtu = MIN(ISO88025_MAX_MTU, ifp->if_mtu);
248		 break;
249	default:
250		ndi->maxmtu = ifp->if_mtu;
251		break;
252	}
253
254	/*
255	 * Decreasing the interface MTU under IPV6 minimum MTU may cause
256	 * undesirable situation.  We thus notify the operator of the change
257	 * explicitly.  The check for omaxmtu is necessary to restrict the
258	 * log to the case of changing the MTU, not initializing it.
259	 */
260	if (omaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
261		log(LOG_NOTICE, "nd6_setmtu0: "
262		    "new link MTU on %s (%lu) is too small for IPv6\n",
263		    if_name(ifp), (unsigned long)ndi->maxmtu);
264	}
265
266	if (ndi->maxmtu > V_in6_maxmtu)
267		in6_setmaxmtu(); /* check all interfaces just in case */
268
269}
270
271void
272nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
273{
274
275	bzero(ndopts, sizeof(*ndopts));
276	ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
277	ndopts->nd_opts_last
278		= (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
279
280	if (icmp6len == 0) {
281		ndopts->nd_opts_done = 1;
282		ndopts->nd_opts_search = NULL;
283	}
284}
285
286/*
287 * Take one ND option.
288 */
289struct nd_opt_hdr *
290nd6_option(union nd_opts *ndopts)
291{
292	struct nd_opt_hdr *nd_opt;
293	int olen;
294
295	KASSERT(ndopts != NULL, ("%s: ndopts == NULL", __func__));
296	KASSERT(ndopts->nd_opts_last != NULL, ("%s: uninitialized ndopts",
297	    __func__));
298	if (ndopts->nd_opts_search == NULL)
299		return NULL;
300	if (ndopts->nd_opts_done)
301		return NULL;
302
303	nd_opt = ndopts->nd_opts_search;
304
305	/* make sure nd_opt_len is inside the buffer */
306	if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
307		bzero(ndopts, sizeof(*ndopts));
308		return NULL;
309	}
310
311	olen = nd_opt->nd_opt_len << 3;
312	if (olen == 0) {
313		/*
314		 * Message validation requires that all included
315		 * options have a length that is greater than zero.
316		 */
317		bzero(ndopts, sizeof(*ndopts));
318		return NULL;
319	}
320
321	ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
322	if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
323		/* option overruns the end of buffer, invalid */
324		bzero(ndopts, sizeof(*ndopts));
325		return NULL;
326	} else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
327		/* reached the end of options chain */
328		ndopts->nd_opts_done = 1;
329		ndopts->nd_opts_search = NULL;
330	}
331	return nd_opt;
332}
333
334/*
335 * Parse multiple ND options.
336 * This function is much easier to use, for ND routines that do not need
337 * multiple options of the same type.
338 */
339int
340nd6_options(union nd_opts *ndopts)
341{
342	struct nd_opt_hdr *nd_opt;
343	int i = 0;
344
345	KASSERT(ndopts != NULL, ("%s: ndopts == NULL", __func__));
346	KASSERT(ndopts->nd_opts_last != NULL, ("%s: uninitialized ndopts",
347	    __func__));
348	if (ndopts->nd_opts_search == NULL)
349		return 0;
350
351	while (1) {
352		nd_opt = nd6_option(ndopts);
353		if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
354			/*
355			 * Message validation requires that all included
356			 * options have a length that is greater than zero.
357			 */
358			ICMP6STAT_INC(icp6s_nd_badopt);
359			bzero(ndopts, sizeof(*ndopts));
360			return -1;
361		}
362
363		if (nd_opt == NULL)
364			goto skip1;
365
366		switch (nd_opt->nd_opt_type) {
367		case ND_OPT_SOURCE_LINKADDR:
368		case ND_OPT_TARGET_LINKADDR:
369		case ND_OPT_MTU:
370		case ND_OPT_REDIRECTED_HEADER:
371		case ND_OPT_NONCE:
372			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
373				nd6log((LOG_INFO,
374				    "duplicated ND6 option found (type=%d)\n",
375				    nd_opt->nd_opt_type));
376				/* XXX bark? */
377			} else {
378				ndopts->nd_opt_array[nd_opt->nd_opt_type]
379					= nd_opt;
380			}
381			break;
382		case ND_OPT_PREFIX_INFORMATION:
383			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
384				ndopts->nd_opt_array[nd_opt->nd_opt_type]
385					= nd_opt;
386			}
387			ndopts->nd_opts_pi_end =
388				(struct nd_opt_prefix_info *)nd_opt;
389			break;
390		/* What about ND_OPT_ROUTE_INFO? RFC 4191 */
391		case ND_OPT_RDNSS:	/* RFC 6106 */
392		case ND_OPT_DNSSL:	/* RFC 6106 */
393			/*
394			 * Silently ignore options we know and do not care about
395			 * in the kernel.
396			 */
397			break;
398		default:
399			/*
400			 * Unknown options must be silently ignored,
401			 * to accomodate future extension to the protocol.
402			 */
403			nd6log((LOG_DEBUG,
404			    "nd6_options: unsupported option %d - "
405			    "option ignored\n", nd_opt->nd_opt_type));
406		}
407
408skip1:
409		i++;
410		if (i > V_nd6_maxndopt) {
411			ICMP6STAT_INC(icp6s_nd_toomanyopt);
412			nd6log((LOG_INFO, "too many loop in nd opt\n"));
413			break;
414		}
415
416		if (ndopts->nd_opts_done)
417			break;
418	}
419
420	return 0;
421}
422
423/*
424 * ND6 timer routine to handle ND6 entries
425 */
426void
427nd6_llinfo_settimer_locked(struct llentry *ln, long tick)
428{
429	int canceled;
430
431	LLE_WLOCK_ASSERT(ln);
432
433	if (tick < 0) {
434		ln->la_expire = 0;
435		ln->ln_ntick = 0;
436		canceled = callout_stop(&ln->ln_timer_ch);
437	} else {
438		ln->la_expire = time_uptime + tick / hz;
439		LLE_ADDREF(ln);
440		if (tick > INT_MAX) {
441			ln->ln_ntick = tick - INT_MAX;
442			canceled = callout_reset(&ln->ln_timer_ch, INT_MAX,
443			    nd6_llinfo_timer, ln);
444		} else {
445			ln->ln_ntick = 0;
446			canceled = callout_reset(&ln->ln_timer_ch, tick,
447			    nd6_llinfo_timer, ln);
448		}
449	}
450	if (canceled)
451		LLE_REMREF(ln);
452}
453
454void
455nd6_llinfo_settimer(struct llentry *ln, long tick)
456{
457
458	LLE_WLOCK(ln);
459	nd6_llinfo_settimer_locked(ln, tick);
460	LLE_WUNLOCK(ln);
461}
462
463static void
464nd6_llinfo_timer(void *arg)
465{
466	struct llentry *ln;
467	struct in6_addr *dst;
468	struct ifnet *ifp;
469	struct nd_ifinfo *ndi = NULL;
470
471	KASSERT(arg != NULL, ("%s: arg NULL", __func__));
472	ln = (struct llentry *)arg;
473	LLE_WLOCK(ln);
474	if (callout_pending(&ln->la_timer)) {
475		/*
476		 * Here we are a bit odd here in the treatment of
477		 * active/pending. If the pending bit is set, it got
478		 * rescheduled before I ran. The active
479		 * bit we ignore, since if it was stopped
480		 * in ll_tablefree() and was currently running
481		 * it would have return 0 so the code would
482		 * not have deleted it since the callout could
483		 * not be stopped so we want to go through
484		 * with the delete here now. If the callout
485		 * was restarted, the pending bit will be back on and
486		 * we just want to bail since the callout_reset would
487		 * return 1 and our reference would have been removed
488		 * by nd6_llinfo_settimer_locked above since canceled
489		 * would have been 1.
490		 */
491		LLE_WUNLOCK(ln);
492		return;
493	}
494	ifp = ln->lle_tbl->llt_ifp;
495	CURVNET_SET(ifp->if_vnet);
496
497	if (ln->ln_ntick > 0) {
498		if (ln->ln_ntick > INT_MAX) {
499			ln->ln_ntick -= INT_MAX;
500			nd6_llinfo_settimer_locked(ln, INT_MAX);
501		} else {
502			ln->ln_ntick = 0;
503			nd6_llinfo_settimer_locked(ln, ln->ln_ntick);
504		}
505		goto done;
506	}
507
508	ndi = ND_IFINFO(ifp);
509	dst = &L3_ADDR_SIN6(ln)->sin6_addr;
510	if (ln->la_flags & LLE_STATIC) {
511		goto done;
512	}
513
514	if (ln->la_flags & LLE_DELETED) {
515		(void)nd6_free(ln, 0);
516		ln = NULL;
517		goto done;
518	}
519
520	switch (ln->ln_state) {
521	case ND6_LLINFO_INCOMPLETE:
522		if (ln->la_asked < V_nd6_mmaxtries) {
523			ln->la_asked++;
524			nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
525			LLE_WUNLOCK(ln);
526			nd6_ns_output(ifp, NULL, dst, ln, NULL);
527			LLE_WLOCK(ln);
528		} else {
529			struct mbuf *m = ln->la_hold;
530			if (m) {
531				struct mbuf *m0;
532
533				/*
534				 * assuming every packet in la_hold has the
535				 * same IP header.  Send error after unlock.
536				 */
537				m0 = m->m_nextpkt;
538				m->m_nextpkt = NULL;
539				ln->la_hold = m0;
540				clear_llinfo_pqueue(ln);
541			}
542			EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_TIMEDOUT);
543			(void)nd6_free(ln, 0);
544			ln = NULL;
545			if (m != NULL)
546				icmp6_error2(m, ICMP6_DST_UNREACH,
547				    ICMP6_DST_UNREACH_ADDR, 0, ifp);
548		}
549		break;
550	case ND6_LLINFO_REACHABLE:
551		if (!ND6_LLINFO_PERMANENT(ln)) {
552			ln->ln_state = ND6_LLINFO_STALE;
553			nd6_llinfo_settimer_locked(ln, (long)V_nd6_gctimer * hz);
554		}
555		break;
556
557	case ND6_LLINFO_STALE:
558		/* Garbage Collection(RFC 2461 5.3) */
559		if (!ND6_LLINFO_PERMANENT(ln)) {
560			EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_EXPIRED);
561			(void)nd6_free(ln, 1);
562			ln = NULL;
563		}
564		break;
565
566	case ND6_LLINFO_DELAY:
567		if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
568			/* We need NUD */
569			ln->la_asked = 1;
570			ln->ln_state = ND6_LLINFO_PROBE;
571			nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
572			LLE_WUNLOCK(ln);
573			nd6_ns_output(ifp, dst, dst, ln, NULL);
574			LLE_WLOCK(ln);
575		} else {
576			ln->ln_state = ND6_LLINFO_STALE; /* XXX */
577			nd6_llinfo_settimer_locked(ln, (long)V_nd6_gctimer * hz);
578		}
579		break;
580	case ND6_LLINFO_PROBE:
581		if (ln->la_asked < V_nd6_umaxtries) {
582			ln->la_asked++;
583			nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
584			LLE_WUNLOCK(ln);
585			nd6_ns_output(ifp, dst, dst, ln, NULL);
586			LLE_WLOCK(ln);
587		} else {
588			EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_EXPIRED);
589			(void)nd6_free(ln, 0);
590			ln = NULL;
591		}
592		break;
593	default:
594		panic("%s: paths in a dark night can be confusing: %d",
595		    __func__, ln->ln_state);
596	}
597done:
598	if (ln != NULL)
599		LLE_FREE_LOCKED(ln);
600	CURVNET_RESTORE();
601}
602
603
604/*
605 * ND6 timer routine to expire default route list and prefix list
606 */
607void
608nd6_timer(void *arg)
609{
610	CURVNET_SET((struct vnet *) arg);
611	struct nd_defrouter *dr, *ndr;
612	struct nd_prefix *pr, *npr;
613	struct in6_ifaddr *ia6, *nia6;
614
615	callout_reset(&V_nd6_timer_ch, V_nd6_prune * hz,
616	    nd6_timer, curvnet);
617
618	/* expire default router list */
619	TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr) {
620		if (dr->expire && dr->expire < time_uptime)
621			defrtrlist_del(dr);
622	}
623
624	/*
625	 * expire interface addresses.
626	 * in the past the loop was inside prefix expiry processing.
627	 * However, from a stricter speci-confrmance standpoint, we should
628	 * rather separate address lifetimes and prefix lifetimes.
629	 *
630	 * XXXRW: in6_ifaddrhead locking.
631	 */
632  addrloop:
633	TAILQ_FOREACH_SAFE(ia6, &V_in6_ifaddrhead, ia_link, nia6) {
634		/* check address lifetime */
635		if (IFA6_IS_INVALID(ia6)) {
636			int regen = 0;
637
638			/*
639			 * If the expiring address is temporary, try
640			 * regenerating a new one.  This would be useful when
641			 * we suspended a laptop PC, then turned it on after a
642			 * period that could invalidate all temporary
643			 * addresses.  Although we may have to restart the
644			 * loop (see below), it must be after purging the
645			 * address.  Otherwise, we'd see an infinite loop of
646			 * regeneration.
647			 */
648			if (V_ip6_use_tempaddr &&
649			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
650				if (regen_tmpaddr(ia6) == 0)
651					regen = 1;
652			}
653
654			in6_purgeaddr(&ia6->ia_ifa);
655
656			if (regen)
657				goto addrloop; /* XXX: see below */
658		} else if (IFA6_IS_DEPRECATED(ia6)) {
659			int oldflags = ia6->ia6_flags;
660
661			ia6->ia6_flags |= IN6_IFF_DEPRECATED;
662
663			/*
664			 * If a temporary address has just become deprecated,
665			 * regenerate a new one if possible.
666			 */
667			if (V_ip6_use_tempaddr &&
668			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
669			    (oldflags & IN6_IFF_DEPRECATED) == 0) {
670
671				if (regen_tmpaddr(ia6) == 0) {
672					/*
673					 * A new temporary address is
674					 * generated.
675					 * XXX: this means the address chain
676					 * has changed while we are still in
677					 * the loop.  Although the change
678					 * would not cause disaster (because
679					 * it's not a deletion, but an
680					 * addition,) we'd rather restart the
681					 * loop just for safety.  Or does this
682					 * significantly reduce performance??
683					 */
684					goto addrloop;
685				}
686			}
687		} else if ((ia6->ia6_flags & IN6_IFF_TENTATIVE) != 0) {
688			/*
689			 * Schedule DAD for a tentative address.  This happens
690			 * if the interface was down or not running
691			 * when the address was configured.
692			 */
693			int delay;
694
695			delay = arc4random() %
696			    (MAX_RTR_SOLICITATION_DELAY * hz);
697			nd6_dad_start((struct ifaddr *)ia6, delay);
698		} else {
699			/*
700			 * Check status of the interface.  If it is down,
701			 * mark the address as tentative for future DAD.
702			 */
703			if ((ia6->ia_ifp->if_flags & IFF_UP) == 0 ||
704			    (ia6->ia_ifp->if_drv_flags & IFF_DRV_RUNNING)
705				== 0 ||
706			    (ND_IFINFO(ia6->ia_ifp)->flags &
707				ND6_IFF_IFDISABLED) != 0) {
708				ia6->ia6_flags &= ~IN6_IFF_DUPLICATED;
709				ia6->ia6_flags |= IN6_IFF_TENTATIVE;
710			}
711			/*
712			 * A new RA might have made a deprecated address
713			 * preferred.
714			 */
715			ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
716		}
717	}
718
719	/* expire prefix list */
720	LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
721		/*
722		 * check prefix lifetime.
723		 * since pltime is just for autoconf, pltime processing for
724		 * prefix is not necessary.
725		 */
726		if (pr->ndpr_vltime != ND6_INFINITE_LIFETIME &&
727		    time_uptime - pr->ndpr_lastupdate > pr->ndpr_vltime) {
728
729			/*
730			 * address expiration and prefix expiration are
731			 * separate.  NEVER perform in6_purgeaddr here.
732			 */
733			prelist_remove(pr);
734		}
735	}
736	CURVNET_RESTORE();
737}
738
739/*
740 * ia6 - deprecated/invalidated temporary address
741 */
742static int
743regen_tmpaddr(struct in6_ifaddr *ia6)
744{
745	struct ifaddr *ifa;
746	struct ifnet *ifp;
747	struct in6_ifaddr *public_ifa6 = NULL;
748
749	ifp = ia6->ia_ifa.ifa_ifp;
750	IF_ADDR_RLOCK(ifp);
751	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
752		struct in6_ifaddr *it6;
753
754		if (ifa->ifa_addr->sa_family != AF_INET6)
755			continue;
756
757		it6 = (struct in6_ifaddr *)ifa;
758
759		/* ignore no autoconf addresses. */
760		if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
761			continue;
762
763		/* ignore autoconf addresses with different prefixes. */
764		if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
765			continue;
766
767		/*
768		 * Now we are looking at an autoconf address with the same
769		 * prefix as ours.  If the address is temporary and is still
770		 * preferred, do not create another one.  It would be rare, but
771		 * could happen, for example, when we resume a laptop PC after
772		 * a long period.
773		 */
774		if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
775		    !IFA6_IS_DEPRECATED(it6)) {
776			public_ifa6 = NULL;
777			break;
778		}
779
780		/*
781		 * This is a public autoconf address that has the same prefix
782		 * as ours.  If it is preferred, keep it.  We can't break the
783		 * loop here, because there may be a still-preferred temporary
784		 * address with the prefix.
785		 */
786		if (!IFA6_IS_DEPRECATED(it6))
787			public_ifa6 = it6;
788	}
789	if (public_ifa6 != NULL)
790		ifa_ref(&public_ifa6->ia_ifa);
791	IF_ADDR_RUNLOCK(ifp);
792
793	if (public_ifa6 != NULL) {
794		int e;
795
796		if ((e = in6_tmpifadd(public_ifa6, 0, 0)) != 0) {
797			ifa_free(&public_ifa6->ia_ifa);
798			log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
799			    " tmp addr,errno=%d\n", e);
800			return (-1);
801		}
802		ifa_free(&public_ifa6->ia_ifa);
803		return (0);
804	}
805
806	return (-1);
807}
808
809/*
810 * Nuke neighbor cache/prefix/default router management table, right before
811 * ifp goes away.
812 */
813void
814nd6_purge(struct ifnet *ifp)
815{
816	struct nd_defrouter *dr, *ndr;
817	struct nd_prefix *pr, *npr;
818
819	/*
820	 * Nuke default router list entries toward ifp.
821	 * We defer removal of default router list entries that is installed
822	 * in the routing table, in order to keep additional side effects as
823	 * small as possible.
824	 */
825	TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr) {
826		if (dr->installed)
827			continue;
828
829		if (dr->ifp == ifp)
830			defrtrlist_del(dr);
831	}
832
833	TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr) {
834		if (!dr->installed)
835			continue;
836
837		if (dr->ifp == ifp)
838			defrtrlist_del(dr);
839	}
840
841	/* Nuke prefix list entries toward ifp */
842	LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
843		if (pr->ndpr_ifp == ifp) {
844			/*
845			 * Because if_detach() does *not* release prefixes
846			 * while purging addresses the reference count will
847			 * still be above zero. We therefore reset it to
848			 * make sure that the prefix really gets purged.
849			 */
850			pr->ndpr_refcnt = 0;
851
852			/*
853			 * Previously, pr->ndpr_addr is removed as well,
854			 * but I strongly believe we don't have to do it.
855			 * nd6_purge() is only called from in6_ifdetach(),
856			 * which removes all the associated interface addresses
857			 * by itself.
858			 * (jinmei@kame.net 20010129)
859			 */
860			prelist_remove(pr);
861		}
862	}
863
864	/* cancel default outgoing interface setting */
865	if (V_nd6_defifindex == ifp->if_index)
866		nd6_setdefaultiface(0);
867
868	if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
869		/* Refresh default router list. */
870		defrouter_select();
871	}
872
873	/* XXXXX
874	 * We do not nuke the neighbor cache entries here any more
875	 * because the neighbor cache is kept in if_afdata[AF_INET6].
876	 * nd6_purge() is invoked by in6_ifdetach() which is called
877	 * from if_detach() where everything gets purged. So let
878	 * in6_domifdetach() do the actual L2 table purging work.
879	 */
880}
881
882/*
883 * the caller acquires and releases the lock on the lltbls
884 * Returns the llentry locked
885 */
886struct llentry *
887nd6_lookup(struct in6_addr *addr6, int flags, struct ifnet *ifp)
888{
889	struct sockaddr_in6 sin6;
890	struct llentry *ln;
891	int llflags;
892
893	bzero(&sin6, sizeof(sin6));
894	sin6.sin6_len = sizeof(struct sockaddr_in6);
895	sin6.sin6_family = AF_INET6;
896	sin6.sin6_addr = *addr6;
897
898	IF_AFDATA_LOCK_ASSERT(ifp);
899
900	llflags = 0;
901	if (flags & ND6_CREATE)
902	    llflags |= LLE_CREATE;
903	if (flags & ND6_EXCLUSIVE)
904	    llflags |= LLE_EXCLUSIVE;
905
906	ln = lla_lookup(LLTABLE6(ifp), llflags, (struct sockaddr *)&sin6);
907	if ((ln != NULL) && (llflags & LLE_CREATE))
908		ln->ln_state = ND6_LLINFO_NOSTATE;
909
910	return (ln);
911}
912
913/*
914 * Test whether a given IPv6 address is a neighbor or not, ignoring
915 * the actual neighbor cache.  The neighbor cache is ignored in order
916 * to not reenter the routing code from within itself.
917 */
918static int
919nd6_is_new_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
920{
921	struct nd_prefix *pr;
922	struct ifaddr *dstaddr;
923
924	/*
925	 * A link-local address is always a neighbor.
926	 * XXX: a link does not necessarily specify a single interface.
927	 */
928	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
929		struct sockaddr_in6 sin6_copy;
930		u_int32_t zone;
931
932		/*
933		 * We need sin6_copy since sa6_recoverscope() may modify the
934		 * content (XXX).
935		 */
936		sin6_copy = *addr;
937		if (sa6_recoverscope(&sin6_copy))
938			return (0); /* XXX: should be impossible */
939		if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
940			return (0);
941		if (sin6_copy.sin6_scope_id == zone)
942			return (1);
943		else
944			return (0);
945	}
946
947	/*
948	 * If the address matches one of our addresses,
949	 * it should be a neighbor.
950	 * If the address matches one of our on-link prefixes, it should be a
951	 * neighbor.
952	 */
953	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
954		if (pr->ndpr_ifp != ifp)
955			continue;
956
957		if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
958			struct rtentry *rt;
959
960			/* Always use the default FIB here. */
961			rt = in6_rtalloc1((struct sockaddr *)&pr->ndpr_prefix,
962			    0, 0, RT_DEFAULT_FIB);
963			if (rt == NULL)
964				continue;
965			/*
966			 * This is the case where multiple interfaces
967			 * have the same prefix, but only one is installed
968			 * into the routing table and that prefix entry
969			 * is not the one being examined here. In the case
970			 * where RADIX_MPATH is enabled, multiple route
971			 * entries (of the same rt_key value) will be
972			 * installed because the interface addresses all
973			 * differ.
974			 */
975			if (!IN6_ARE_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
976			       &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr)) {
977				RTFREE_LOCKED(rt);
978				continue;
979			}
980			RTFREE_LOCKED(rt);
981		}
982
983		if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
984		    &addr->sin6_addr, &pr->ndpr_mask))
985			return (1);
986	}
987
988	/*
989	 * If the address is assigned on the node of the other side of
990	 * a p2p interface, the address should be a neighbor.
991	 */
992	dstaddr = ifa_ifwithdstaddr((struct sockaddr *)addr);
993	if (dstaddr != NULL) {
994		if (dstaddr->ifa_ifp == ifp) {
995			ifa_free(dstaddr);
996			return (1);
997		}
998		ifa_free(dstaddr);
999	}
1000
1001	/*
1002	 * If the default router list is empty, all addresses are regarded
1003	 * as on-link, and thus, as a neighbor.
1004	 */
1005	if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV &&
1006	    TAILQ_EMPTY(&V_nd_defrouter) &&
1007	    V_nd6_defifindex == ifp->if_index) {
1008		return (1);
1009	}
1010
1011	return (0);
1012}
1013
1014
1015/*
1016 * Detect if a given IPv6 address identifies a neighbor on a given link.
1017 * XXX: should take care of the destination of a p2p link?
1018 */
1019int
1020nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
1021{
1022	struct llentry *lle;
1023	int rc = 0;
1024
1025	IF_AFDATA_UNLOCK_ASSERT(ifp);
1026	if (nd6_is_new_addr_neighbor(addr, ifp))
1027		return (1);
1028
1029	/*
1030	 * Even if the address matches none of our addresses, it might be
1031	 * in the neighbor cache.
1032	 */
1033	IF_AFDATA_RLOCK(ifp);
1034	if ((lle = nd6_lookup(&addr->sin6_addr, 0, ifp)) != NULL) {
1035		LLE_RUNLOCK(lle);
1036		rc = 1;
1037	}
1038	IF_AFDATA_RUNLOCK(ifp);
1039	return (rc);
1040}
1041
1042/*
1043 * Free an nd6 llinfo entry.
1044 * Since the function would cause significant changes in the kernel, DO NOT
1045 * make it global, unless you have a strong reason for the change, and are sure
1046 * that the change is safe.
1047 */
1048static struct llentry *
1049nd6_free(struct llentry *ln, int gc)
1050{
1051        struct llentry *next;
1052	struct nd_defrouter *dr;
1053	struct ifnet *ifp;
1054
1055	LLE_WLOCK_ASSERT(ln);
1056
1057	/*
1058	 * we used to have pfctlinput(PRC_HOSTDEAD) here.
1059	 * even though it is not harmful, it was not really necessary.
1060	 */
1061
1062	/* cancel timer */
1063	nd6_llinfo_settimer_locked(ln, -1);
1064
1065	ifp = ln->lle_tbl->llt_ifp;
1066
1067	if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1068		dr = defrouter_lookup(&L3_ADDR_SIN6(ln)->sin6_addr, ifp);
1069
1070		if (dr != NULL && dr->expire &&
1071		    ln->ln_state == ND6_LLINFO_STALE && gc) {
1072			/*
1073			 * If the reason for the deletion is just garbage
1074			 * collection, and the neighbor is an active default
1075			 * router, do not delete it.  Instead, reset the GC
1076			 * timer using the router's lifetime.
1077			 * Simply deleting the entry would affect default
1078			 * router selection, which is not necessarily a good
1079			 * thing, especially when we're using router preference
1080			 * values.
1081			 * XXX: the check for ln_state would be redundant,
1082			 *      but we intentionally keep it just in case.
1083			 */
1084			if (dr->expire > time_uptime)
1085				nd6_llinfo_settimer_locked(ln,
1086				    (dr->expire - time_uptime) * hz);
1087			else
1088				nd6_llinfo_settimer_locked(ln,
1089				    (long)V_nd6_gctimer * hz);
1090
1091			next = LIST_NEXT(ln, lle_next);
1092			LLE_REMREF(ln);
1093			LLE_WUNLOCK(ln);
1094			return (next);
1095		}
1096
1097		if (dr) {
1098			/*
1099			 * Unreachablity of a router might affect the default
1100			 * router selection and on-link detection of advertised
1101			 * prefixes.
1102			 */
1103
1104			/*
1105			 * Temporarily fake the state to choose a new default
1106			 * router and to perform on-link determination of
1107			 * prefixes correctly.
1108			 * Below the state will be set correctly,
1109			 * or the entry itself will be deleted.
1110			 */
1111			ln->ln_state = ND6_LLINFO_INCOMPLETE;
1112		}
1113
1114		if (ln->ln_router || dr) {
1115
1116			/*
1117			 * We need to unlock to avoid a LOR with rt6_flush() with the
1118			 * rnh and for the calls to pfxlist_onlink_check() and
1119			 * defrouter_select() in the block further down for calls
1120			 * into nd6_lookup().  We still hold a ref.
1121			 */
1122			LLE_WUNLOCK(ln);
1123
1124			/*
1125			 * rt6_flush must be called whether or not the neighbor
1126			 * is in the Default Router List.
1127			 * See a corresponding comment in nd6_na_input().
1128			 */
1129			rt6_flush(&L3_ADDR_SIN6(ln)->sin6_addr, ifp);
1130		}
1131
1132		if (dr) {
1133			/*
1134			 * Since defrouter_select() does not affect the
1135			 * on-link determination and MIP6 needs the check
1136			 * before the default router selection, we perform
1137			 * the check now.
1138			 */
1139			pfxlist_onlink_check();
1140
1141			/*
1142			 * Refresh default router list.
1143			 */
1144			defrouter_select();
1145		}
1146
1147		if (ln->ln_router || dr)
1148			LLE_WLOCK(ln);
1149	}
1150
1151	/*
1152	 * Before deleting the entry, remember the next entry as the
1153	 * return value.  We need this because pfxlist_onlink_check() above
1154	 * might have freed other entries (particularly the old next entry) as
1155	 * a side effect (XXX).
1156	 */
1157	next = LIST_NEXT(ln, lle_next);
1158
1159	/*
1160	 * Save to unlock. We still hold an extra reference and will not
1161	 * free(9) in llentry_free() if someone else holds one as well.
1162	 */
1163	LLE_WUNLOCK(ln);
1164	IF_AFDATA_LOCK(ifp);
1165	LLE_WLOCK(ln);
1166
1167	/* Guard against race with other llentry_free(). */
1168	if (ln->la_flags & LLE_LINKED) {
1169		LLE_REMREF(ln);
1170		llentry_free(ln);
1171	} else
1172		LLE_FREE_LOCKED(ln);
1173
1174	IF_AFDATA_UNLOCK(ifp);
1175
1176	return (next);
1177}
1178
1179/*
1180 * Upper-layer reachability hint for Neighbor Unreachability Detection.
1181 *
1182 * XXX cost-effective methods?
1183 */
1184void
1185nd6_nud_hint(struct rtentry *rt, struct in6_addr *dst6, int force)
1186{
1187	struct llentry *ln;
1188	struct ifnet *ifp;
1189
1190	if ((dst6 == NULL) || (rt == NULL))
1191		return;
1192
1193	ifp = rt->rt_ifp;
1194	IF_AFDATA_RLOCK(ifp);
1195	ln = nd6_lookup(dst6, ND6_EXCLUSIVE, NULL);
1196	IF_AFDATA_RUNLOCK(ifp);
1197	if (ln == NULL)
1198		return;
1199
1200	if (ln->ln_state < ND6_LLINFO_REACHABLE)
1201		goto done;
1202
1203	/*
1204	 * if we get upper-layer reachability confirmation many times,
1205	 * it is possible we have false information.
1206	 */
1207	if (!force) {
1208		ln->ln_byhint++;
1209		if (ln->ln_byhint > V_nd6_maxnudhint) {
1210			goto done;
1211		}
1212	}
1213
1214 	ln->ln_state = ND6_LLINFO_REACHABLE;
1215	if (!ND6_LLINFO_PERMANENT(ln)) {
1216		nd6_llinfo_settimer_locked(ln,
1217		    (long)ND_IFINFO(rt->rt_ifp)->reachable * hz);
1218	}
1219done:
1220	LLE_WUNLOCK(ln);
1221}
1222
1223
1224/*
1225 * Rejuvenate this function for routing operations related
1226 * processing.
1227 */
1228void
1229nd6_rtrequest(int req, struct rtentry *rt, struct rt_addrinfo *info)
1230{
1231	struct sockaddr_in6 *gateway;
1232	struct nd_defrouter *dr;
1233	struct ifnet *ifp;
1234
1235	RT_LOCK_ASSERT(rt);
1236	gateway = (struct sockaddr_in6 *)rt->rt_gateway;
1237	ifp = rt->rt_ifp;
1238
1239	switch (req) {
1240	case RTM_ADD:
1241		break;
1242
1243	case RTM_DELETE:
1244		if (!ifp)
1245			return;
1246		/*
1247		 * Only indirect routes are interesting.
1248		 */
1249		if ((rt->rt_flags & RTF_GATEWAY) == 0)
1250			return;
1251		/*
1252		 * check for default route
1253		 */
1254		if (IN6_ARE_ADDR_EQUAL(&in6addr_any,
1255				       &SIN6(rt_key(rt))->sin6_addr)) {
1256
1257			dr = defrouter_lookup(&gateway->sin6_addr, ifp);
1258			if (dr != NULL)
1259				dr->installed = 0;
1260		}
1261		break;
1262	}
1263}
1264
1265
1266int
1267nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1268{
1269	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1270	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1271	struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1272	int error = 0;
1273
1274	if (ifp->if_afdata[AF_INET6] == NULL)
1275		return (EPFNOSUPPORT);
1276	switch (cmd) {
1277	case OSIOCGIFINFO_IN6:
1278#define ND	ndi->ndi
1279		/* XXX: old ndp(8) assumes a positive value for linkmtu. */
1280		bzero(&ND, sizeof(ND));
1281		ND.linkmtu = IN6_LINKMTU(ifp);
1282		ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
1283		ND.basereachable = ND_IFINFO(ifp)->basereachable;
1284		ND.reachable = ND_IFINFO(ifp)->reachable;
1285		ND.retrans = ND_IFINFO(ifp)->retrans;
1286		ND.flags = ND_IFINFO(ifp)->flags;
1287		ND.recalctm = ND_IFINFO(ifp)->recalctm;
1288		ND.chlim = ND_IFINFO(ifp)->chlim;
1289		break;
1290	case SIOCGIFINFO_IN6:
1291		ND = *ND_IFINFO(ifp);
1292		break;
1293	case SIOCSIFINFO_IN6:
1294		/*
1295		 * used to change host variables from userland.
1296		 * intented for a use on router to reflect RA configurations.
1297		 */
1298		/* 0 means 'unspecified' */
1299		if (ND.linkmtu != 0) {
1300			if (ND.linkmtu < IPV6_MMTU ||
1301			    ND.linkmtu > IN6_LINKMTU(ifp)) {
1302				error = EINVAL;
1303				break;
1304			}
1305			ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
1306		}
1307
1308		if (ND.basereachable != 0) {
1309			int obasereachable = ND_IFINFO(ifp)->basereachable;
1310
1311			ND_IFINFO(ifp)->basereachable = ND.basereachable;
1312			if (ND.basereachable != obasereachable)
1313				ND_IFINFO(ifp)->reachable =
1314				    ND_COMPUTE_RTIME(ND.basereachable);
1315		}
1316		if (ND.retrans != 0)
1317			ND_IFINFO(ifp)->retrans = ND.retrans;
1318		if (ND.chlim != 0)
1319			ND_IFINFO(ifp)->chlim = ND.chlim;
1320		/* FALLTHROUGH */
1321	case SIOCSIFINFO_FLAGS:
1322	{
1323		struct ifaddr *ifa;
1324		struct in6_ifaddr *ia;
1325
1326		if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1327		    !(ND.flags & ND6_IFF_IFDISABLED)) {
1328			/* ifdisabled 1->0 transision */
1329
1330			/*
1331			 * If the interface is marked as ND6_IFF_IFDISABLED and
1332			 * has an link-local address with IN6_IFF_DUPLICATED,
1333			 * do not clear ND6_IFF_IFDISABLED.
1334			 * See RFC 4862, Section 5.4.5.
1335			 */
1336			IF_ADDR_RLOCK(ifp);
1337			TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1338				if (ifa->ifa_addr->sa_family != AF_INET6)
1339					continue;
1340				ia = (struct in6_ifaddr *)ifa;
1341				if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
1342				    IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1343					break;
1344			}
1345			IF_ADDR_RUNLOCK(ifp);
1346
1347			if (ifa != NULL) {
1348				/* LLA is duplicated. */
1349				ND.flags |= ND6_IFF_IFDISABLED;
1350				log(LOG_ERR, "Cannot enable an interface"
1351				    " with a link-local address marked"
1352				    " duplicate.\n");
1353			} else {
1354				ND_IFINFO(ifp)->flags &= ~ND6_IFF_IFDISABLED;
1355				if (ifp->if_flags & IFF_UP)
1356					in6_if_up(ifp);
1357			}
1358		} else if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1359			    (ND.flags & ND6_IFF_IFDISABLED)) {
1360			/* ifdisabled 0->1 transision */
1361			/* Mark all IPv6 address as tentative. */
1362
1363			ND_IFINFO(ifp)->flags |= ND6_IFF_IFDISABLED;
1364			if (V_ip6_dad_count > 0 &&
1365			    (ND_IFINFO(ifp)->flags & ND6_IFF_NO_DAD) == 0) {
1366				IF_ADDR_RLOCK(ifp);
1367				TAILQ_FOREACH(ifa, &ifp->if_addrhead,
1368				    ifa_link) {
1369					if (ifa->ifa_addr->sa_family !=
1370					    AF_INET6)
1371						continue;
1372					ia = (struct in6_ifaddr *)ifa;
1373					ia->ia6_flags |= IN6_IFF_TENTATIVE;
1374				}
1375				IF_ADDR_RUNLOCK(ifp);
1376			}
1377		}
1378
1379		if (ND.flags & ND6_IFF_AUTO_LINKLOCAL) {
1380			if (!(ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL)) {
1381				/* auto_linklocal 0->1 transision */
1382
1383				/* If no link-local address on ifp, configure */
1384				ND_IFINFO(ifp)->flags |= ND6_IFF_AUTO_LINKLOCAL;
1385				in6_ifattach(ifp, NULL);
1386			} else if (!(ND.flags & ND6_IFF_IFDISABLED) &&
1387			    ifp->if_flags & IFF_UP) {
1388				/*
1389				 * When the IF already has
1390				 * ND6_IFF_AUTO_LINKLOCAL, no link-local
1391				 * address is assigned, and IFF_UP, try to
1392				 * assign one.
1393				 */
1394				IF_ADDR_RLOCK(ifp);
1395				TAILQ_FOREACH(ifa, &ifp->if_addrhead,
1396				    ifa_link) {
1397					if (ifa->ifa_addr->sa_family !=
1398					    AF_INET6)
1399						continue;
1400					ia = (struct in6_ifaddr *)ifa;
1401					if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1402						break;
1403				}
1404				IF_ADDR_RUNLOCK(ifp);
1405				if (ifa != NULL)
1406					/* No LLA is configured. */
1407					in6_ifattach(ifp, NULL);
1408			}
1409		}
1410	}
1411		ND_IFINFO(ifp)->flags = ND.flags;
1412		break;
1413#undef ND
1414	case SIOCSNDFLUSH_IN6:	/* XXX: the ioctl name is confusing... */
1415		/* sync kernel routing table with the default router list */
1416		defrouter_reset();
1417		defrouter_select();
1418		break;
1419	case SIOCSPFXFLUSH_IN6:
1420	{
1421		/* flush all the prefix advertised by routers */
1422		struct nd_prefix *pr, *next;
1423
1424		LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, next) {
1425			struct in6_ifaddr *ia, *ia_next;
1426
1427			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1428				continue; /* XXX */
1429
1430			/* do we really have to remove addresses as well? */
1431			/* XXXRW: in6_ifaddrhead locking. */
1432			TAILQ_FOREACH_SAFE(ia, &V_in6_ifaddrhead, ia_link,
1433			    ia_next) {
1434				if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1435					continue;
1436
1437				if (ia->ia6_ndpr == pr)
1438					in6_purgeaddr(&ia->ia_ifa);
1439			}
1440			prelist_remove(pr);
1441		}
1442		break;
1443	}
1444	case SIOCSRTRFLUSH_IN6:
1445	{
1446		/* flush all the default routers */
1447		struct nd_defrouter *dr, *next;
1448
1449		defrouter_reset();
1450		TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, next) {
1451			defrtrlist_del(dr);
1452		}
1453		defrouter_select();
1454		break;
1455	}
1456	case SIOCGNBRINFO_IN6:
1457	{
1458		struct llentry *ln;
1459		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1460
1461		if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
1462			return (error);
1463
1464		IF_AFDATA_RLOCK(ifp);
1465		ln = nd6_lookup(&nb_addr, 0, ifp);
1466		IF_AFDATA_RUNLOCK(ifp);
1467
1468		if (ln == NULL) {
1469			error = EINVAL;
1470			break;
1471		}
1472		nbi->state = ln->ln_state;
1473		nbi->asked = ln->la_asked;
1474		nbi->isrouter = ln->ln_router;
1475		if (ln->la_expire == 0)
1476			nbi->expire = 0;
1477		else
1478			nbi->expire = ln->la_expire +
1479			    (time_second - time_uptime);
1480		LLE_RUNLOCK(ln);
1481		break;
1482	}
1483	case SIOCGDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1484		ndif->ifindex = V_nd6_defifindex;
1485		break;
1486	case SIOCSDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1487		return (nd6_setdefaultiface(ndif->ifindex));
1488	}
1489	return (error);
1490}
1491
1492/*
1493 * Create neighbor cache entry and cache link-layer address,
1494 * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1495 *
1496 * type - ICMP6 type
1497 * code - type dependent information
1498 *
1499 * XXXXX
1500 *  The caller of this function already acquired the ndp
1501 *  cache table lock because the cache entry is returned.
1502 */
1503struct llentry *
1504nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1505    int lladdrlen, int type, int code)
1506{
1507	struct llentry *ln = NULL;
1508	int is_newentry;
1509	int do_update;
1510	int olladdr;
1511	int llchange;
1512	int flags;
1513	int newstate = 0;
1514	uint16_t router = 0;
1515	struct sockaddr_in6 sin6;
1516	struct mbuf *chain = NULL;
1517	int static_route = 0;
1518
1519	IF_AFDATA_UNLOCK_ASSERT(ifp);
1520
1521	KASSERT(ifp != NULL, ("%s: ifp == NULL", __func__));
1522	KASSERT(from != NULL, ("%s: from == NULL", __func__));
1523
1524	/* nothing must be updated for unspecified address */
1525	if (IN6_IS_ADDR_UNSPECIFIED(from))
1526		return NULL;
1527
1528	/*
1529	 * Validation about ifp->if_addrlen and lladdrlen must be done in
1530	 * the caller.
1531	 *
1532	 * XXX If the link does not have link-layer adderss, what should
1533	 * we do? (ifp->if_addrlen == 0)
1534	 * Spec says nothing in sections for RA, RS and NA.  There's small
1535	 * description on it in NS section (RFC 2461 7.2.3).
1536	 */
1537	flags = lladdr ? ND6_EXCLUSIVE : 0;
1538	IF_AFDATA_RLOCK(ifp);
1539	ln = nd6_lookup(from, flags, ifp);
1540	IF_AFDATA_RUNLOCK(ifp);
1541	if (ln == NULL) {
1542		flags |= ND6_EXCLUSIVE;
1543		IF_AFDATA_LOCK(ifp);
1544		ln = nd6_lookup(from, flags | ND6_CREATE, ifp);
1545		IF_AFDATA_UNLOCK(ifp);
1546		is_newentry = 1;
1547	} else {
1548		/* do nothing if static ndp is set */
1549		if (ln->la_flags & LLE_STATIC) {
1550			static_route = 1;
1551			goto done;
1552		}
1553		is_newentry = 0;
1554	}
1555	if (ln == NULL)
1556		return (NULL);
1557
1558	olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
1559	if (olladdr && lladdr) {
1560		llchange = bcmp(lladdr, &ln->ll_addr,
1561		    ifp->if_addrlen);
1562	} else
1563		llchange = 0;
1564
1565	/*
1566	 * newentry olladdr  lladdr  llchange	(*=record)
1567	 *	0	n	n	--	(1)
1568	 *	0	y	n	--	(2)
1569	 *	0	n	y	--	(3) * STALE
1570	 *	0	y	y	n	(4) *
1571	 *	0	y	y	y	(5) * STALE
1572	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
1573	 *	1	--	y	--	(7) * STALE
1574	 */
1575
1576	if (lladdr) {		/* (3-5) and (7) */
1577		/*
1578		 * Record source link-layer address
1579		 * XXX is it dependent to ifp->if_type?
1580		 */
1581		bcopy(lladdr, &ln->ll_addr, ifp->if_addrlen);
1582		ln->la_flags |= LLE_VALID;
1583		EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
1584	}
1585
1586	if (!is_newentry) {
1587		if ((!olladdr && lladdr != NULL) ||	/* (3) */
1588		    (olladdr && lladdr != NULL && llchange)) {	/* (5) */
1589			do_update = 1;
1590			newstate = ND6_LLINFO_STALE;
1591		} else					/* (1-2,4) */
1592			do_update = 0;
1593	} else {
1594		do_update = 1;
1595		if (lladdr == NULL)			/* (6) */
1596			newstate = ND6_LLINFO_NOSTATE;
1597		else					/* (7) */
1598			newstate = ND6_LLINFO_STALE;
1599	}
1600
1601	if (do_update) {
1602		/*
1603		 * Update the state of the neighbor cache.
1604		 */
1605		ln->ln_state = newstate;
1606
1607		if (ln->ln_state == ND6_LLINFO_STALE) {
1608			if (ln->la_hold != NULL)
1609				nd6_grab_holdchain(ln, &chain, &sin6);
1610		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
1611			/* probe right away */
1612			nd6_llinfo_settimer_locked((void *)ln, 0);
1613		}
1614	}
1615
1616	/*
1617	 * ICMP6 type dependent behavior.
1618	 *
1619	 * NS: clear IsRouter if new entry
1620	 * RS: clear IsRouter
1621	 * RA: set IsRouter if there's lladdr
1622	 * redir: clear IsRouter if new entry
1623	 *
1624	 * RA case, (1):
1625	 * The spec says that we must set IsRouter in the following cases:
1626	 * - If lladdr exist, set IsRouter.  This means (1-5).
1627	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
1628	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1629	 * A quetion arises for (1) case.  (1) case has no lladdr in the
1630	 * neighbor cache, this is similar to (6).
1631	 * This case is rare but we figured that we MUST NOT set IsRouter.
1632	 *
1633	 * newentry olladdr  lladdr  llchange	    NS  RS  RA	redir
1634	 *							D R
1635	 *	0	n	n	--	(1)	c   ?     s
1636	 *	0	y	n	--	(2)	c   s     s
1637	 *	0	n	y	--	(3)	c   s     s
1638	 *	0	y	y	n	(4)	c   s     s
1639	 *	0	y	y	y	(5)	c   s     s
1640	 *	1	--	n	--	(6) c	c	c s
1641	 *	1	--	y	--	(7) c	c   s	c s
1642	 *
1643	 *					(c=clear s=set)
1644	 */
1645	switch (type & 0xff) {
1646	case ND_NEIGHBOR_SOLICIT:
1647		/*
1648		 * New entry must have is_router flag cleared.
1649		 */
1650		if (is_newentry)	/* (6-7) */
1651			ln->ln_router = 0;
1652		break;
1653	case ND_REDIRECT:
1654		/*
1655		 * If the icmp is a redirect to a better router, always set the
1656		 * is_router flag.  Otherwise, if the entry is newly created,
1657		 * clear the flag.  [RFC 2461, sec 8.3]
1658		 */
1659		if (code == ND_REDIRECT_ROUTER)
1660			ln->ln_router = 1;
1661		else if (is_newentry) /* (6-7) */
1662			ln->ln_router = 0;
1663		break;
1664	case ND_ROUTER_SOLICIT:
1665		/*
1666		 * is_router flag must always be cleared.
1667		 */
1668		ln->ln_router = 0;
1669		break;
1670	case ND_ROUTER_ADVERT:
1671		/*
1672		 * Mark an entry with lladdr as a router.
1673		 */
1674		if ((!is_newentry && (olladdr || lladdr)) ||	/* (2-5) */
1675		    (is_newentry && lladdr)) {			/* (7) */
1676			ln->ln_router = 1;
1677		}
1678		break;
1679	}
1680
1681	if (ln != NULL) {
1682		static_route = (ln->la_flags & LLE_STATIC);
1683		router = ln->ln_router;
1684
1685		if (flags & ND6_EXCLUSIVE)
1686			LLE_WUNLOCK(ln);
1687		else
1688			LLE_RUNLOCK(ln);
1689		if (static_route)
1690			ln = NULL;
1691	}
1692	if (chain != NULL)
1693		nd6_flush_holdchain(ifp, ifp, chain, &sin6);
1694
1695	/*
1696	 * When the link-layer address of a router changes, select the
1697	 * best router again.  In particular, when the neighbor entry is newly
1698	 * created, it might affect the selection policy.
1699	 * Question: can we restrict the first condition to the "is_newentry"
1700	 * case?
1701	 * XXX: when we hear an RA from a new router with the link-layer
1702	 * address option, defrouter_select() is called twice, since
1703	 * defrtrlist_update called the function as well.  However, I believe
1704	 * we can compromise the overhead, since it only happens the first
1705	 * time.
1706	 * XXX: although defrouter_select() should not have a bad effect
1707	 * for those are not autoconfigured hosts, we explicitly avoid such
1708	 * cases for safety.
1709	 */
1710	if (do_update && router &&
1711	    ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1712		/*
1713		 * guaranteed recursion
1714		 */
1715		defrouter_select();
1716	}
1717
1718	return (ln);
1719done:
1720	if (ln != NULL) {
1721		if (flags & ND6_EXCLUSIVE)
1722			LLE_WUNLOCK(ln);
1723		else
1724			LLE_RUNLOCK(ln);
1725		if (static_route)
1726			ln = NULL;
1727	}
1728	return (ln);
1729}
1730
1731static void
1732nd6_slowtimo(void *arg)
1733{
1734	CURVNET_SET((struct vnet *) arg);
1735	struct nd_ifinfo *nd6if;
1736	struct ifnet *ifp;
1737
1738	callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
1739	    nd6_slowtimo, curvnet);
1740	IFNET_RLOCK_NOSLEEP();
1741	TAILQ_FOREACH(ifp, &V_ifnet, if_list) {
1742		if (ifp->if_afdata[AF_INET6] == NULL)
1743			continue;
1744		nd6if = ND_IFINFO(ifp);
1745		if (nd6if->basereachable && /* already initialized */
1746		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
1747			/*
1748			 * Since reachable time rarely changes by router
1749			 * advertisements, we SHOULD insure that a new random
1750			 * value gets recomputed at least once every few hours.
1751			 * (RFC 2461, 6.3.4)
1752			 */
1753			nd6if->recalctm = V_nd6_recalc_reachtm_interval;
1754			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
1755		}
1756	}
1757	IFNET_RUNLOCK_NOSLEEP();
1758	CURVNET_RESTORE();
1759}
1760
1761void
1762nd6_grab_holdchain(struct llentry *ln, struct mbuf **chain,
1763    struct sockaddr_in6 *sin6)
1764{
1765
1766	LLE_WLOCK_ASSERT(ln);
1767
1768	*chain = ln->la_hold;
1769	ln->la_hold = NULL;
1770	memcpy(sin6, L3_ADDR_SIN6(ln), sizeof(*sin6));
1771
1772	if (ln->ln_state == ND6_LLINFO_STALE) {
1773
1774		/*
1775		 * The first time we send a packet to a
1776		 * neighbor whose entry is STALE, we have
1777		 * to change the state to DELAY and a sets
1778		 * a timer to expire in DELAY_FIRST_PROBE_TIME
1779		 * seconds to ensure do neighbor unreachability
1780		 * detection on expiration.
1781		 * (RFC 2461 7.3.3)
1782		 */
1783		ln->la_asked = 0;
1784		ln->ln_state = ND6_LLINFO_DELAY;
1785		nd6_llinfo_settimer_locked(ln, (long)V_nd6_delay * hz);
1786	}
1787}
1788
1789static int
1790nd6_output_ifp(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
1791    struct sockaddr_in6 *dst)
1792{
1793	int error;
1794	int ip6len;
1795	struct ip6_hdr *ip6;
1796	struct m_tag *mtag;
1797
1798#ifdef MAC
1799	mac_netinet6_nd6_send(ifp, m);
1800#endif
1801
1802	/*
1803	 * If called from nd6_ns_output() (NS), nd6_na_output() (NA),
1804	 * icmp6_redirect_output() (REDIRECT) or from rip6_output() (RS, RA
1805	 * as handled by rtsol and rtadvd), mbufs will be tagged for SeND
1806	 * to be diverted to user space.  When re-injected into the kernel,
1807	 * send_output() will directly dispatch them to the outgoing interface.
1808	 */
1809	if (send_sendso_input_hook != NULL) {
1810		mtag = m_tag_find(m, PACKET_TAG_ND_OUTGOING, NULL);
1811		if (mtag != NULL) {
1812			ip6 = mtod(m, struct ip6_hdr *);
1813			ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
1814			/* Use the SEND socket */
1815			error = send_sendso_input_hook(m, ifp, SND_OUT,
1816			    ip6len);
1817			/* -1 == no app on SEND socket */
1818			if (error == 0 || error != -1)
1819			    return (error);
1820		}
1821	}
1822
1823	m_clrprotoflags(m);	/* Avoid confusing lower layers. */
1824	IP_PROBE(send, NULL, NULL, mtod(m, struct ip6_hdr *), ifp, NULL,
1825	    mtod(m, struct ip6_hdr *));
1826
1827	if ((ifp->if_flags & IFF_LOOPBACK) == 0)
1828		origifp = ifp;
1829
1830	error = (*ifp->if_output)(origifp, m, (struct sockaddr *)dst, NULL);
1831	return (error);
1832}
1833
1834/*
1835 * IPv6 packet output - light version.
1836 * Checks if destination LLE exists and is in proper state
1837 * (e.g no modification required). If not true, fall back to
1838 * "heavy" version.
1839 */
1840int
1841nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
1842    struct sockaddr_in6 *dst, struct rtentry *rt0)
1843{
1844	struct llentry *ln = NULL;
1845
1846	/* discard the packet if IPv6 operation is disabled on the interface */
1847	if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
1848		m_freem(m);
1849		return (ENETDOWN); /* better error? */
1850	}
1851
1852	if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1853		goto sendpkt;
1854
1855	if (nd6_need_cache(ifp) == 0)
1856		goto sendpkt;
1857
1858	IF_AFDATA_RLOCK(ifp);
1859	ln = nd6_lookup(&dst->sin6_addr, 0, ifp);
1860	IF_AFDATA_RUNLOCK(ifp);
1861
1862	/*
1863	 * Perform fast path for the following cases:
1864	 * 1) lle state is REACHABLE
1865	 * 2) lle state is DELAY (NS message sentNS message sent)
1866	 *
1867	 * Every other case involves lle modification, so we handle
1868	 * them separately.
1869	 */
1870	if (ln == NULL || (ln->ln_state != ND6_LLINFO_REACHABLE &&
1871	    ln->ln_state != ND6_LLINFO_DELAY)) {
1872		/* Fall back to slow processing path */
1873		if (ln != NULL)
1874			LLE_RUNLOCK(ln);
1875		return (nd6_output_lle(ifp, origifp, m, dst));
1876	}
1877
1878sendpkt:
1879	if (ln != NULL)
1880		LLE_RUNLOCK(ln);
1881
1882	return (nd6_output_ifp(ifp, origifp, m, dst));
1883}
1884
1885
1886/*
1887 * Output IPv6 packet - heavy version.
1888 * Function assume that either
1889 * 1) destination LLE does not exist, is invalid or stale, so
1890 *   ND6_EXCLUSIVE lock needs to be acquired
1891 * 2) destination lle is provided (with ND6_EXCLUSIVE lock),
1892 *   in that case packets are queued in &chain.
1893 *
1894 */
1895static int
1896nd6_output_lle(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
1897    struct sockaddr_in6 *dst)
1898{
1899	struct llentry *lle = NULL;
1900	int flags = 0;
1901
1902	KASSERT(m != NULL, ("NULL mbuf, nothing to send"));
1903	/* discard the packet if IPv6 operation is disabled on the interface */
1904	if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
1905		m_freem(m);
1906		return (ENETDOWN); /* better error? */
1907	}
1908
1909	if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr))
1910		goto sendpkt;
1911
1912	if (nd6_need_cache(ifp) == 0)
1913		goto sendpkt;
1914
1915	/*
1916	 * Address resolution or Neighbor Unreachability Detection
1917	 * for the next hop.
1918	 * At this point, the destination of the packet must be a unicast
1919	 * or an anycast address(i.e. not a multicast).
1920	 */
1921	if (lle == NULL) {
1922		IF_AFDATA_RLOCK(ifp);
1923		lle = nd6_lookup(&dst->sin6_addr, ND6_EXCLUSIVE, ifp);
1924		IF_AFDATA_RUNLOCK(ifp);
1925		if ((lle == NULL) && nd6_is_addr_neighbor(dst, ifp))  {
1926			/*
1927			 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
1928			 * the condition below is not very efficient.  But we believe
1929			 * it is tolerable, because this should be a rare case.
1930			 */
1931			flags = ND6_CREATE | ND6_EXCLUSIVE;
1932			IF_AFDATA_LOCK(ifp);
1933			lle = nd6_lookup(&dst->sin6_addr, flags, ifp);
1934			IF_AFDATA_UNLOCK(ifp);
1935		}
1936	}
1937	if (lle == NULL) {
1938		if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
1939		    !(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
1940			char ip6buf[INET6_ADDRSTRLEN];
1941			log(LOG_DEBUG,
1942			    "nd6_output: can't allocate llinfo for %s "
1943			    "(ln=%p)\n",
1944			    ip6_sprintf(ip6buf, &dst->sin6_addr), lle);
1945			m_freem(m);
1946			return (ENOBUFS);
1947		}
1948		goto sendpkt;	/* send anyway */
1949	}
1950
1951	LLE_WLOCK_ASSERT(lle);
1952
1953	/* We don't have to do link-layer address resolution on a p2p link. */
1954	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
1955	    lle->ln_state < ND6_LLINFO_REACHABLE) {
1956		lle->ln_state = ND6_LLINFO_STALE;
1957		nd6_llinfo_settimer_locked(lle, (long)V_nd6_gctimer * hz);
1958	}
1959
1960	/*
1961	 * The first time we send a packet to a neighbor whose entry is
1962	 * STALE, we have to change the state to DELAY and a sets a timer to
1963	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
1964	 * neighbor unreachability detection on expiration.
1965	 * (RFC 2461 7.3.3)
1966	 */
1967	if (lle->ln_state == ND6_LLINFO_STALE) {
1968		lle->la_asked = 0;
1969		lle->ln_state = ND6_LLINFO_DELAY;
1970		nd6_llinfo_settimer_locked(lle, (long)V_nd6_delay * hz);
1971	}
1972
1973	/*
1974	 * If the neighbor cache entry has a state other than INCOMPLETE
1975	 * (i.e. its link-layer address is already resolved), just
1976	 * send the packet.
1977	 */
1978	if (lle->ln_state > ND6_LLINFO_INCOMPLETE)
1979		goto sendpkt;
1980
1981	/*
1982	 * There is a neighbor cache entry, but no ethernet address
1983	 * response yet.  Append this latest packet to the end of the
1984	 * packet queue in the mbuf, unless the number of the packet
1985	 * does not exceed nd6_maxqueuelen.  When it exceeds nd6_maxqueuelen,
1986	 * the oldest packet in the queue will be removed.
1987	 */
1988	if (lle->ln_state == ND6_LLINFO_NOSTATE)
1989		lle->ln_state = ND6_LLINFO_INCOMPLETE;
1990
1991	if (lle->la_hold != NULL) {
1992		struct mbuf *m_hold;
1993		int i;
1994
1995		i = 0;
1996		for (m_hold = lle->la_hold; m_hold; m_hold = m_hold->m_nextpkt){
1997			i++;
1998			if (m_hold->m_nextpkt == NULL) {
1999				m_hold->m_nextpkt = m;
2000				break;
2001			}
2002		}
2003		while (i >= V_nd6_maxqueuelen) {
2004			m_hold = lle->la_hold;
2005			lle->la_hold = lle->la_hold->m_nextpkt;
2006			m_freem(m_hold);
2007			i--;
2008		}
2009	} else {
2010		lle->la_hold = m;
2011	}
2012
2013	/*
2014	 * If there has been no NS for the neighbor after entering the
2015	 * INCOMPLETE state, send the first solicitation.
2016	 */
2017	if (!ND6_LLINFO_PERMANENT(lle) && lle->la_asked == 0) {
2018		lle->la_asked++;
2019
2020		nd6_llinfo_settimer_locked(lle,
2021		    (long)ND_IFINFO(ifp)->retrans * hz / 1000);
2022		LLE_WUNLOCK(lle);
2023		nd6_ns_output(ifp, NULL, &dst->sin6_addr, lle, NULL);
2024	} else {
2025		/* We did the lookup so we need to do the unlock here. */
2026		LLE_WUNLOCK(lle);
2027	}
2028
2029	return (0);
2030
2031  sendpkt:
2032	if (lle != NULL)
2033		LLE_WUNLOCK(lle);
2034
2035	return (nd6_output_ifp(ifp, origifp, m, dst));
2036}
2037
2038
2039int
2040nd6_flush_holdchain(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *chain,
2041    struct sockaddr_in6 *dst)
2042{
2043	struct mbuf *m, *m_head;
2044	struct ifnet *outifp;
2045	int error = 0;
2046
2047	m_head = chain;
2048	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2049		outifp = origifp;
2050	else
2051		outifp = ifp;
2052
2053	while (m_head) {
2054		m = m_head;
2055		m_head = m_head->m_nextpkt;
2056		error = nd6_output_ifp(ifp, origifp, m, dst);
2057	}
2058
2059	/*
2060	 * XXX
2061	 * note that intermediate errors are blindly ignored - but this is
2062	 * the same convention as used with nd6_output when called by
2063	 * nd6_cache_lladdr
2064	 */
2065	return (error);
2066}
2067
2068
2069int
2070nd6_need_cache(struct ifnet *ifp)
2071{
2072	/*
2073	 * XXX: we currently do not make neighbor cache on any interface
2074	 * other than ARCnet, Ethernet, FDDI and GIF.
2075	 *
2076	 * RFC2893 says:
2077	 * - unidirectional tunnels needs no ND
2078	 */
2079	switch (ifp->if_type) {
2080	case IFT_ARCNET:
2081	case IFT_ETHER:
2082	case IFT_FDDI:
2083	case IFT_IEEE1394:
2084#ifdef IFT_L2VLAN
2085	case IFT_L2VLAN:
2086#endif
2087#ifdef IFT_IEEE80211
2088	case IFT_IEEE80211:
2089#endif
2090	case IFT_INFINIBAND:
2091	case IFT_BRIDGE:
2092	case IFT_PROPVIRTUAL:
2093		return (1);
2094	default:
2095		return (0);
2096	}
2097}
2098
2099/*
2100 * the callers of this function need to be re-worked to drop
2101 * the lle lock, drop here for now
2102 */
2103int
2104nd6_storelladdr(struct ifnet *ifp, struct mbuf *m,
2105    const struct sockaddr *dst, u_char *desten, struct llentry **lle)
2106{
2107	struct llentry *ln;
2108
2109	*lle = NULL;
2110	IF_AFDATA_UNLOCK_ASSERT(ifp);
2111	if (m != NULL && m->m_flags & M_MCAST) {
2112		int i;
2113
2114		switch (ifp->if_type) {
2115		case IFT_ETHER:
2116		case IFT_FDDI:
2117#ifdef IFT_L2VLAN
2118		case IFT_L2VLAN:
2119#endif
2120#ifdef IFT_IEEE80211
2121		case IFT_IEEE80211:
2122#endif
2123		case IFT_BRIDGE:
2124		case IFT_ISO88025:
2125			ETHER_MAP_IPV6_MULTICAST(&SIN6(dst)->sin6_addr,
2126						 desten);
2127			return (0);
2128		case IFT_IEEE1394:
2129			/*
2130			 * netbsd can use if_broadcastaddr, but we don't do so
2131			 * to reduce # of ifdef.
2132			 */
2133			for (i = 0; i < ifp->if_addrlen; i++)
2134				desten[i] = ~0;
2135			return (0);
2136		case IFT_ARCNET:
2137			*desten = 0;
2138			return (0);
2139		default:
2140			m_freem(m);
2141			return (EAFNOSUPPORT);
2142		}
2143	}
2144
2145
2146	/*
2147	 * the entry should have been created in nd6_store_lladdr
2148	 */
2149	IF_AFDATA_RLOCK(ifp);
2150	ln = lla_lookup(LLTABLE6(ifp), 0, dst);
2151	IF_AFDATA_RUNLOCK(ifp);
2152	if ((ln == NULL) || !(ln->la_flags & LLE_VALID)) {
2153		if (ln != NULL)
2154			LLE_RUNLOCK(ln);
2155		/* this could happen, if we could not allocate memory */
2156		m_freem(m);
2157		return (1);
2158	}
2159
2160	bcopy(&ln->ll_addr, desten, ifp->if_addrlen);
2161	*lle = ln;
2162	LLE_RUNLOCK(ln);
2163	/*
2164	 * A *small* use after free race exists here
2165	 */
2166	return (0);
2167}
2168
2169static void
2170clear_llinfo_pqueue(struct llentry *ln)
2171{
2172	struct mbuf *m_hold, *m_hold_next;
2173
2174	for (m_hold = ln->la_hold; m_hold; m_hold = m_hold_next) {
2175		m_hold_next = m_hold->m_nextpkt;
2176		m_freem(m_hold);
2177	}
2178
2179	ln->la_hold = NULL;
2180}
2181
2182static int nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS);
2183static int nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS);
2184#ifdef SYSCTL_DECL
2185SYSCTL_DECL(_net_inet6_icmp6);
2186#endif
2187SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2188	CTLFLAG_RD, nd6_sysctl_drlist, "");
2189SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2190	CTLFLAG_RD, nd6_sysctl_prlist, "");
2191SYSCTL_VNET_INT(_net_inet6_icmp6, ICMPV6CTL_ND6_MAXQLEN, nd6_maxqueuelen,
2192	CTLFLAG_RW, &VNET_NAME(nd6_maxqueuelen), 1, "");
2193SYSCTL_VNET_INT(_net_inet6_icmp6, OID_AUTO, nd6_gctimer,
2194	CTLFLAG_RW, &VNET_NAME(nd6_gctimer), (60 * 60 * 24), "");
2195
2196static int
2197nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2198{
2199	struct in6_defrouter d;
2200	struct nd_defrouter *dr;
2201	int error;
2202
2203	if (req->newptr)
2204		return (EPERM);
2205
2206	bzero(&d, sizeof(d));
2207	d.rtaddr.sin6_family = AF_INET6;
2208	d.rtaddr.sin6_len = sizeof(d.rtaddr);
2209
2210	/*
2211	 * XXX locking
2212	 */
2213	TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry) {
2214		d.rtaddr.sin6_addr = dr->rtaddr;
2215		error = sa6_recoverscope(&d.rtaddr);
2216		if (error != 0)
2217			return (error);
2218		d.flags = dr->raflags;
2219		d.rtlifetime = dr->rtlifetime;
2220		d.expire = dr->expire + (time_second - time_uptime);
2221		d.if_index = dr->ifp->if_index;
2222		error = SYSCTL_OUT(req, &d, sizeof(d));
2223		if (error != 0)
2224			return (error);
2225	}
2226	return (0);
2227}
2228
2229static int
2230nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2231{
2232	struct in6_prefix p;
2233	struct sockaddr_in6 s6;
2234	struct nd_prefix *pr;
2235	struct nd_pfxrouter *pfr;
2236	time_t maxexpire;
2237	int error;
2238	char ip6buf[INET6_ADDRSTRLEN];
2239
2240	if (req->newptr)
2241		return (EPERM);
2242
2243	bzero(&p, sizeof(p));
2244	p.origin = PR_ORIG_RA;
2245	bzero(&s6, sizeof(s6));
2246	s6.sin6_family = AF_INET6;
2247	s6.sin6_len = sizeof(s6);
2248
2249	/*
2250	 * XXX locking
2251	 */
2252	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
2253		p.prefix = pr->ndpr_prefix;
2254		if (sa6_recoverscope(&p.prefix)) {
2255			log(LOG_ERR, "scope error in prefix list (%s)\n",
2256			    ip6_sprintf(ip6buf, &p.prefix.sin6_addr));
2257			/* XXX: press on... */
2258		}
2259		p.raflags = pr->ndpr_raf;
2260		p.prefixlen = pr->ndpr_plen;
2261		p.vltime = pr->ndpr_vltime;
2262		p.pltime = pr->ndpr_pltime;
2263		p.if_index = pr->ndpr_ifp->if_index;
2264		if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2265			p.expire = 0;
2266		else {
2267			/* XXX: we assume time_t is signed. */
2268			maxexpire = (-1) &
2269			    ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
2270			if (pr->ndpr_vltime < maxexpire - pr->ndpr_lastupdate)
2271				p.expire = pr->ndpr_lastupdate +
2272				    pr->ndpr_vltime +
2273				    (time_second - time_uptime);
2274			else
2275				p.expire = maxexpire;
2276		}
2277		p.refcnt = pr->ndpr_refcnt;
2278		p.flags = pr->ndpr_stateflags;
2279		p.advrtrs = 0;
2280		LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
2281			p.advrtrs++;
2282		error = SYSCTL_OUT(req, &p, sizeof(p));
2283		if (error != 0)
2284			return (error);
2285		LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
2286			s6.sin6_addr = pfr->router->rtaddr;
2287			if (sa6_recoverscope(&s6))
2288				log(LOG_ERR,
2289				    "scope error in prefix list (%s)\n",
2290				    ip6_sprintf(ip6buf, &pfr->router->rtaddr));
2291			error = SYSCTL_OUT(req, &s6, sizeof(s6));
2292			if (error != 0)
2293				return (error);
2294		}
2295	}
2296	return (0);
2297}
2298