xref: /freebsd/sys/netinet6/nd6.c (revision 18849b5da0c5eaa88500b457be05b038813b51b1)
1 /*-
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the project nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	$KAME: nd6.c,v 1.144 2001/05/24 07:44:00 itojun Exp $
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/callout.h>
41 #include <sys/malloc.h>
42 #include <sys/mbuf.h>
43 #include <sys/socket.h>
44 #include <sys/sockio.h>
45 #include <sys/time.h>
46 #include <sys/kernel.h>
47 #include <sys/protosw.h>
48 #include <sys/errno.h>
49 #include <sys/syslog.h>
50 #include <sys/lock.h>
51 #include <sys/rwlock.h>
52 #include <sys/queue.h>
53 #include <sys/sdt.h>
54 #include <sys/sysctl.h>
55 
56 #include <net/if.h>
57 #include <net/if_var.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 #include <netinet/if_ether.h>
70 #include <netinet6/in6_var.h>
71 #include <netinet/ip6.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/scope6_var.h>
74 #include <netinet6/nd6.h>
75 #include <netinet6/in6_ifattach.h>
76 #include <netinet/icmp6.h>
77 #include <netinet6/send.h>
78 
79 #include <sys/limits.h>
80 
81 #include <security/mac/mac_framework.h>
82 
83 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
84 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
85 
86 #define SIN6(s) ((const struct sockaddr_in6 *)(s))
87 
88 /* timer values */
89 VNET_DEFINE(int, nd6_prune)	= 1;	/* walk list every 1 seconds */
90 VNET_DEFINE(int, nd6_delay)	= 5;	/* delay first probe time 5 second */
91 VNET_DEFINE(int, nd6_umaxtries)	= 3;	/* maximum unicast query */
92 VNET_DEFINE(int, nd6_mmaxtries)	= 3;	/* maximum multicast query */
93 VNET_DEFINE(int, nd6_useloopback) = 1;	/* use loopback interface for
94 					 * local traffic */
95 VNET_DEFINE(int, nd6_gctimer)	= (60 * 60 * 24); /* 1 day: garbage
96 					 * collection timer */
97 
98 /* preventing too many loops in ND option parsing */
99 static VNET_DEFINE(int, nd6_maxndopt) = 10; /* max # of ND options allowed */
100 
101 VNET_DEFINE(int, nd6_maxnudhint) = 0;	/* max # of subsequent upper
102 					 * layer hints */
103 static VNET_DEFINE(int, nd6_maxqueuelen) = 1; /* max pkts cached in unresolved
104 					 * ND entries */
105 #define	V_nd6_maxndopt			VNET(nd6_maxndopt)
106 #define	V_nd6_maxqueuelen		VNET(nd6_maxqueuelen)
107 
108 #ifdef ND6_DEBUG
109 VNET_DEFINE(int, nd6_debug) = 1;
110 #else
111 VNET_DEFINE(int, nd6_debug) = 0;
112 #endif
113 
114 static eventhandler_tag lle_event_eh, iflladdr_event_eh;
115 
116 VNET_DEFINE(struct nd_drhead, nd_defrouter);
117 VNET_DEFINE(struct nd_prhead, nd_prefix);
118 VNET_DEFINE(struct rwlock, nd6_lock);
119 
120 VNET_DEFINE(int, nd6_recalc_reachtm_interval) = ND6_RECALC_REACHTM_INTERVAL;
121 #define	V_nd6_recalc_reachtm_interval	VNET(nd6_recalc_reachtm_interval)
122 
123 int	(*send_sendso_input_hook)(struct mbuf *, struct ifnet *, int, int);
124 
125 static int nd6_is_new_addr_neighbor(const struct sockaddr_in6 *,
126 	struct ifnet *);
127 static void nd6_setmtu0(struct ifnet *, struct nd_ifinfo *);
128 static void nd6_slowtimo(void *);
129 static int regen_tmpaddr(struct in6_ifaddr *);
130 static void nd6_free(struct llentry **, int);
131 static void nd6_free_redirect(const struct llentry *);
132 static void nd6_llinfo_timer(void *);
133 static void nd6_llinfo_settimer_locked(struct llentry *, long);
134 static void clear_llinfo_pqueue(struct llentry *);
135 static void nd6_rtrequest(int, struct rtentry *, struct rt_addrinfo *);
136 static int nd6_resolve_slow(struct ifnet *, int, struct mbuf *,
137     const struct sockaddr_in6 *, u_char *, uint32_t *);
138 static int nd6_need_cache(struct ifnet *);
139 
140 
141 static VNET_DEFINE(struct callout, nd6_slowtimo_ch);
142 #define	V_nd6_slowtimo_ch		VNET(nd6_slowtimo_ch)
143 
144 VNET_DEFINE(struct callout, nd6_timer_ch);
145 #define	V_nd6_timer_ch			VNET(nd6_timer_ch)
146 
147 static void
148 nd6_lle_event(void *arg __unused, struct llentry *lle, int evt)
149 {
150 	struct rt_addrinfo rtinfo;
151 	struct sockaddr_in6 dst;
152 	struct sockaddr_dl gw;
153 	struct ifnet *ifp;
154 	int type;
155 
156 	LLE_WLOCK_ASSERT(lle);
157 
158 	if (lltable_get_af(lle->lle_tbl) != AF_INET6)
159 		return;
160 
161 	switch (evt) {
162 	case LLENTRY_RESOLVED:
163 		type = RTM_ADD;
164 		KASSERT(lle->la_flags & LLE_VALID,
165 		    ("%s: %p resolved but not valid?", __func__, lle));
166 		break;
167 	case LLENTRY_EXPIRED:
168 		type = RTM_DELETE;
169 		break;
170 	default:
171 		return;
172 	}
173 
174 	ifp = lltable_get_ifp(lle->lle_tbl);
175 
176 	bzero(&dst, sizeof(dst));
177 	bzero(&gw, sizeof(gw));
178 	bzero(&rtinfo, sizeof(rtinfo));
179 	lltable_fill_sa_entry(lle, (struct sockaddr *)&dst);
180 	dst.sin6_scope_id = in6_getscopezone(ifp,
181 	    in6_addrscope(&dst.sin6_addr));
182 	gw.sdl_len = sizeof(struct sockaddr_dl);
183 	gw.sdl_family = AF_LINK;
184 	gw.sdl_alen = ifp->if_addrlen;
185 	gw.sdl_index = ifp->if_index;
186 	gw.sdl_type = ifp->if_type;
187 	if (evt == LLENTRY_RESOLVED)
188 		bcopy(lle->ll_addr, gw.sdl_data, ifp->if_addrlen);
189 	rtinfo.rti_info[RTAX_DST] = (struct sockaddr *)&dst;
190 	rtinfo.rti_info[RTAX_GATEWAY] = (struct sockaddr *)&gw;
191 	rtinfo.rti_addrs = RTA_DST | RTA_GATEWAY;
192 	rt_missmsg_fib(type, &rtinfo, RTF_HOST | RTF_LLDATA | (
193 	    type == RTM_ADD ? RTF_UP: 0), 0, RT_DEFAULT_FIB);
194 }
195 
196 /*
197  * A handler for interface link layer address change event.
198  */
199 static void
200 nd6_iflladdr(void *arg __unused, struct ifnet *ifp)
201 {
202 
203 	lltable_update_ifaddr(LLTABLE6(ifp));
204 }
205 
206 void
207 nd6_init(void)
208 {
209 
210 	rw_init(&V_nd6_lock, "nd6");
211 
212 	LIST_INIT(&V_nd_prefix);
213 
214 	/* initialization of the default router list */
215 	TAILQ_INIT(&V_nd_defrouter);
216 
217 	/* Start timers. */
218 	callout_init(&V_nd6_slowtimo_ch, 0);
219 	callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
220 	    nd6_slowtimo, curvnet);
221 
222 	callout_init(&V_nd6_timer_ch, 0);
223 	callout_reset(&V_nd6_timer_ch, hz, nd6_timer, curvnet);
224 
225 	nd6_dad_init();
226 	if (IS_DEFAULT_VNET(curvnet)) {
227 		lle_event_eh = EVENTHANDLER_REGISTER(lle_event, nd6_lle_event,
228 		    NULL, EVENTHANDLER_PRI_ANY);
229 		iflladdr_event_eh = EVENTHANDLER_REGISTER(iflladdr_event,
230 		    nd6_iflladdr, NULL, EVENTHANDLER_PRI_ANY);
231 	}
232 }
233 
234 #ifdef VIMAGE
235 void
236 nd6_destroy()
237 {
238 
239 	callout_drain(&V_nd6_slowtimo_ch);
240 	callout_drain(&V_nd6_timer_ch);
241 	if (IS_DEFAULT_VNET(curvnet)) {
242 		EVENTHANDLER_DEREGISTER(lle_event, lle_event_eh);
243 		EVENTHANDLER_DEREGISTER(iflladdr_event, iflladdr_event_eh);
244 	}
245 	rw_destroy(&V_nd6_lock);
246 }
247 #endif
248 
249 struct nd_ifinfo *
250 nd6_ifattach(struct ifnet *ifp)
251 {
252 	struct nd_ifinfo *nd;
253 
254 	nd = malloc(sizeof(*nd), M_IP6NDP, M_WAITOK | M_ZERO);
255 	nd->initialized = 1;
256 
257 	nd->chlim = IPV6_DEFHLIM;
258 	nd->basereachable = REACHABLE_TIME;
259 	nd->reachable = ND_COMPUTE_RTIME(nd->basereachable);
260 	nd->retrans = RETRANS_TIMER;
261 
262 	nd->flags = ND6_IFF_PERFORMNUD;
263 
264 	/* A loopback interface always has ND6_IFF_AUTO_LINKLOCAL.
265 	 * XXXHRS: Clear ND6_IFF_AUTO_LINKLOCAL on an IFT_BRIDGE interface by
266 	 * default regardless of the V_ip6_auto_linklocal configuration to
267 	 * give a reasonable default behavior.
268 	 */
269 	if ((V_ip6_auto_linklocal && ifp->if_type != IFT_BRIDGE) ||
270 	    (ifp->if_flags & IFF_LOOPBACK))
271 		nd->flags |= ND6_IFF_AUTO_LINKLOCAL;
272 	/*
273 	 * A loopback interface does not need to accept RTADV.
274 	 * XXXHRS: Clear ND6_IFF_ACCEPT_RTADV on an IFT_BRIDGE interface by
275 	 * default regardless of the V_ip6_accept_rtadv configuration to
276 	 * prevent the interface from accepting RA messages arrived
277 	 * on one of the member interfaces with ND6_IFF_ACCEPT_RTADV.
278 	 */
279 	if (V_ip6_accept_rtadv &&
280 	    !(ifp->if_flags & IFF_LOOPBACK) &&
281 	    (ifp->if_type != IFT_BRIDGE))
282 			nd->flags |= ND6_IFF_ACCEPT_RTADV;
283 	if (V_ip6_no_radr && !(ifp->if_flags & IFF_LOOPBACK))
284 		nd->flags |= ND6_IFF_NO_RADR;
285 
286 	/* XXX: we cannot call nd6_setmtu since ifp is not fully initialized */
287 	nd6_setmtu0(ifp, nd);
288 
289 	return nd;
290 }
291 
292 void
293 nd6_ifdetach(struct nd_ifinfo *nd)
294 {
295 
296 	free(nd, M_IP6NDP);
297 }
298 
299 /*
300  * Reset ND level link MTU. This function is called when the physical MTU
301  * changes, which means we might have to adjust the ND level MTU.
302  */
303 void
304 nd6_setmtu(struct ifnet *ifp)
305 {
306 	if (ifp->if_afdata[AF_INET6] == NULL)
307 		return;
308 
309 	nd6_setmtu0(ifp, ND_IFINFO(ifp));
310 }
311 
312 /* XXX todo: do not maintain copy of ifp->if_mtu in ndi->maxmtu */
313 void
314 nd6_setmtu0(struct ifnet *ifp, struct nd_ifinfo *ndi)
315 {
316 	u_int32_t omaxmtu;
317 
318 	omaxmtu = ndi->maxmtu;
319 
320 	switch (ifp->if_type) {
321 	case IFT_ARCNET:
322 		ndi->maxmtu = MIN(ARC_PHDS_MAXMTU, ifp->if_mtu); /* RFC2497 */
323 		break;
324 	case IFT_FDDI:
325 		ndi->maxmtu = MIN(FDDIIPMTU, ifp->if_mtu); /* RFC2467 */
326 		break;
327 	case IFT_ISO88025:
328 		 ndi->maxmtu = MIN(ISO88025_MAX_MTU, ifp->if_mtu);
329 		 break;
330 	default:
331 		ndi->maxmtu = ifp->if_mtu;
332 		break;
333 	}
334 
335 	/*
336 	 * Decreasing the interface MTU under IPV6 minimum MTU may cause
337 	 * undesirable situation.  We thus notify the operator of the change
338 	 * explicitly.  The check for omaxmtu is necessary to restrict the
339 	 * log to the case of changing the MTU, not initializing it.
340 	 */
341 	if (omaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
342 		log(LOG_NOTICE, "nd6_setmtu0: "
343 		    "new link MTU on %s (%lu) is too small for IPv6\n",
344 		    if_name(ifp), (unsigned long)ndi->maxmtu);
345 	}
346 
347 	if (ndi->maxmtu > V_in6_maxmtu)
348 		in6_setmaxmtu(); /* check all interfaces just in case */
349 
350 }
351 
352 void
353 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
354 {
355 
356 	bzero(ndopts, sizeof(*ndopts));
357 	ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
358 	ndopts->nd_opts_last
359 		= (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
360 
361 	if (icmp6len == 0) {
362 		ndopts->nd_opts_done = 1;
363 		ndopts->nd_opts_search = NULL;
364 	}
365 }
366 
367 /*
368  * Take one ND option.
369  */
370 struct nd_opt_hdr *
371 nd6_option(union nd_opts *ndopts)
372 {
373 	struct nd_opt_hdr *nd_opt;
374 	int olen;
375 
376 	KASSERT(ndopts != NULL, ("%s: ndopts == NULL", __func__));
377 	KASSERT(ndopts->nd_opts_last != NULL, ("%s: uninitialized ndopts",
378 	    __func__));
379 	if (ndopts->nd_opts_search == NULL)
380 		return NULL;
381 	if (ndopts->nd_opts_done)
382 		return NULL;
383 
384 	nd_opt = ndopts->nd_opts_search;
385 
386 	/* make sure nd_opt_len is inside the buffer */
387 	if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
388 		bzero(ndopts, sizeof(*ndopts));
389 		return NULL;
390 	}
391 
392 	olen = nd_opt->nd_opt_len << 3;
393 	if (olen == 0) {
394 		/*
395 		 * Message validation requires that all included
396 		 * options have a length that is greater than zero.
397 		 */
398 		bzero(ndopts, sizeof(*ndopts));
399 		return NULL;
400 	}
401 
402 	ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
403 	if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
404 		/* option overruns the end of buffer, invalid */
405 		bzero(ndopts, sizeof(*ndopts));
406 		return NULL;
407 	} else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
408 		/* reached the end of options chain */
409 		ndopts->nd_opts_done = 1;
410 		ndopts->nd_opts_search = NULL;
411 	}
412 	return nd_opt;
413 }
414 
415 /*
416  * Parse multiple ND options.
417  * This function is much easier to use, for ND routines that do not need
418  * multiple options of the same type.
419  */
420 int
421 nd6_options(union nd_opts *ndopts)
422 {
423 	struct nd_opt_hdr *nd_opt;
424 	int i = 0;
425 
426 	KASSERT(ndopts != NULL, ("%s: ndopts == NULL", __func__));
427 	KASSERT(ndopts->nd_opts_last != NULL, ("%s: uninitialized ndopts",
428 	    __func__));
429 	if (ndopts->nd_opts_search == NULL)
430 		return 0;
431 
432 	while (1) {
433 		nd_opt = nd6_option(ndopts);
434 		if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
435 			/*
436 			 * Message validation requires that all included
437 			 * options have a length that is greater than zero.
438 			 */
439 			ICMP6STAT_INC(icp6s_nd_badopt);
440 			bzero(ndopts, sizeof(*ndopts));
441 			return -1;
442 		}
443 
444 		if (nd_opt == NULL)
445 			goto skip1;
446 
447 		switch (nd_opt->nd_opt_type) {
448 		case ND_OPT_SOURCE_LINKADDR:
449 		case ND_OPT_TARGET_LINKADDR:
450 		case ND_OPT_MTU:
451 		case ND_OPT_REDIRECTED_HEADER:
452 		case ND_OPT_NONCE:
453 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
454 				nd6log((LOG_INFO,
455 				    "duplicated ND6 option found (type=%d)\n",
456 				    nd_opt->nd_opt_type));
457 				/* XXX bark? */
458 			} else {
459 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
460 					= nd_opt;
461 			}
462 			break;
463 		case ND_OPT_PREFIX_INFORMATION:
464 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
465 				ndopts->nd_opt_array[nd_opt->nd_opt_type]
466 					= nd_opt;
467 			}
468 			ndopts->nd_opts_pi_end =
469 				(struct nd_opt_prefix_info *)nd_opt;
470 			break;
471 		/* What about ND_OPT_ROUTE_INFO? RFC 4191 */
472 		case ND_OPT_RDNSS:	/* RFC 6106 */
473 		case ND_OPT_DNSSL:	/* RFC 6106 */
474 			/*
475 			 * Silently ignore options we know and do not care about
476 			 * in the kernel.
477 			 */
478 			break;
479 		default:
480 			/*
481 			 * Unknown options must be silently ignored,
482 			 * to accommodate future extension to the protocol.
483 			 */
484 			nd6log((LOG_DEBUG,
485 			    "nd6_options: unsupported option %d - "
486 			    "option ignored\n", nd_opt->nd_opt_type));
487 		}
488 
489 skip1:
490 		i++;
491 		if (i > V_nd6_maxndopt) {
492 			ICMP6STAT_INC(icp6s_nd_toomanyopt);
493 			nd6log((LOG_INFO, "too many loop in nd opt\n"));
494 			break;
495 		}
496 
497 		if (ndopts->nd_opts_done)
498 			break;
499 	}
500 
501 	return 0;
502 }
503 
504 /*
505  * ND6 timer routine to handle ND6 entries
506  */
507 static void
508 nd6_llinfo_settimer_locked(struct llentry *ln, long tick)
509 {
510 	int canceled;
511 
512 	LLE_WLOCK_ASSERT(ln);
513 
514 	if (tick < 0) {
515 		ln->la_expire = 0;
516 		ln->ln_ntick = 0;
517 		canceled = callout_stop(&ln->lle_timer);
518 	} else {
519 		ln->la_expire = time_uptime + tick / hz;
520 		LLE_ADDREF(ln);
521 		if (tick > INT_MAX) {
522 			ln->ln_ntick = tick - INT_MAX;
523 			canceled = callout_reset(&ln->lle_timer, INT_MAX,
524 			    nd6_llinfo_timer, ln);
525 		} else {
526 			ln->ln_ntick = 0;
527 			canceled = callout_reset(&ln->lle_timer, tick,
528 			    nd6_llinfo_timer, ln);
529 		}
530 	}
531 	if (canceled > 0)
532 		LLE_REMREF(ln);
533 }
534 
535 /*
536  * Gets source address of the first packet in hold queue
537  * and stores it in @src.
538  * Returns pointer to @src (if hold queue is not empty) or NULL.
539  *
540  * Set noinline to be dtrace-friendly
541  */
542 static __noinline struct in6_addr *
543 nd6_llinfo_get_holdsrc(struct llentry *ln, struct in6_addr *src)
544 {
545 	struct ip6_hdr hdr;
546 	struct mbuf *m;
547 
548 	if (ln->la_hold == NULL)
549 		return (NULL);
550 
551 	/*
552 	 * assume every packet in la_hold has the same IP header
553 	 */
554 	m = ln->la_hold;
555 	if (sizeof(hdr) > m->m_len)
556 		return (NULL);
557 
558 	m_copydata(m, 0, sizeof(hdr), (caddr_t)&hdr);
559 	*src = hdr.ip6_src;
560 
561 	return (src);
562 }
563 
564 /*
565  * Checks if we need to switch from STALE state.
566  *
567  * RFC 4861 requires switching from STALE to DELAY state
568  * on first packet matching entry, waiting V_nd6_delay and
569  * transition to PROBE state (if upper layer confirmation was
570  * not received).
571  *
572  * This code performs a bit differently:
573  * On packet hit we don't change state (but desired state
574  * can be guessed by control plane). However, after V_nd6_delay
575  * seconds code will transition to PROBE state (so DELAY state
576  * is kinda skipped in most situations).
577  *
578  * Typically, V_nd6_gctimer is bigger than V_nd6_delay, so
579  * we perform the following upon entering STALE state:
580  *
581  * 1) Arm timer to run each V_nd6_delay seconds to make sure that
582  * if packet was transmitted at the start of given interval, we
583  * would be able to switch to PROBE state in V_nd6_delay seconds
584  * as user expects.
585  *
586  * 2) Reschedule timer until original V_nd6_gctimer expires keeping
587  * lle in STALE state (remaining timer value stored in lle_remtime).
588  *
589  * 3) Reschedule timer if packet was transmitted less that V_nd6_delay
590  * seconds ago.
591  *
592  * Returns non-zero value if the entry is still STALE (storing
593  * the next timer interval in @pdelay).
594  *
595  * Returns zero value if original timer expired or we need to switch to
596  * PROBE (store that in @do_switch variable).
597  */
598 static int
599 nd6_is_stale(struct llentry *lle, long *pdelay, int *do_switch)
600 {
601 	int nd_delay, nd_gctimer, r_skip_req;
602 	time_t lle_hittime;
603 	long delay;
604 
605 	*do_switch = 0;
606 	nd_gctimer = V_nd6_gctimer;
607 	nd_delay = V_nd6_delay;
608 
609 	LLE_REQ_LOCK(lle);
610 	r_skip_req = lle->r_skip_req;
611 	lle_hittime = lle->lle_hittime;
612 	LLE_REQ_UNLOCK(lle);
613 
614 	if (r_skip_req > 0) {
615 
616 		/*
617 		 * Nonzero r_skip_req value was set upon entering
618 		 * STALE state. Since value was not changed, no
619 		 * packets were passed using this lle. Ask for
620 		 * timer reschedule and keep STALE state.
621 		 */
622 		delay = (long)(MIN(nd_gctimer, nd_delay));
623 		delay *= hz;
624 		if (lle->lle_remtime > delay)
625 			lle->lle_remtime -= delay;
626 		else {
627 			delay = lle->lle_remtime;
628 			lle->lle_remtime = 0;
629 		}
630 
631 		if (delay == 0) {
632 
633 			/*
634 			 * The original ng6_gctime timeout ended,
635 			 * no more rescheduling.
636 			 */
637 			return (0);
638 		}
639 
640 		*pdelay = delay;
641 		return (1);
642 	}
643 
644 	/*
645 	 * Packet received. Verify timestamp
646 	 */
647 	delay = (long)(time_uptime - lle_hittime);
648 	if (delay < nd_delay) {
649 
650 		/*
651 		 * V_nd6_delay still not passed since the first
652 		 * hit in STALE state.
653 		 * Reshedule timer and return.
654 		 */
655 		*pdelay = (long)(nd_delay - delay) * hz;
656 		return (1);
657 	}
658 
659 	/* Request switching to probe */
660 	*do_switch = 1;
661 	return (0);
662 }
663 
664 
665 /*
666  * Switch @lle state to new state optionally arming timers.
667  *
668  * Set noinline to be dtrace-friendly
669  */
670 __noinline void
671 nd6_llinfo_setstate(struct llentry *lle, int newstate)
672 {
673 	struct ifnet *ifp;
674 	int nd_gctimer, nd_delay;
675 	long delay, remtime;
676 
677 	delay = 0;
678 	remtime = 0;
679 
680 	switch (newstate) {
681 	case ND6_LLINFO_INCOMPLETE:
682 		ifp = lle->lle_tbl->llt_ifp;
683 		delay = (long)ND_IFINFO(ifp)->retrans * hz / 1000;
684 		break;
685 	case ND6_LLINFO_REACHABLE:
686 		if (!ND6_LLINFO_PERMANENT(lle)) {
687 			ifp = lle->lle_tbl->llt_ifp;
688 			delay = (long)ND_IFINFO(ifp)->reachable * hz;
689 		}
690 		break;
691 	case ND6_LLINFO_STALE:
692 
693 		/*
694 		 * Notify fast path that we want to know if any packet
695 		 * is transmitted by setting r_skip_req.
696 		 */
697 		LLE_REQ_LOCK(lle);
698 		lle->r_skip_req = 1;
699 		LLE_REQ_UNLOCK(lle);
700 		nd_delay = V_nd6_delay;
701 		nd_gctimer = V_nd6_gctimer;
702 
703 		delay = (long)(MIN(nd_gctimer, nd_delay)) * hz;
704 		remtime = (long)nd_gctimer * hz - delay;
705 		break;
706 	case ND6_LLINFO_DELAY:
707 		lle->la_asked = 0;
708 		delay = (long)V_nd6_delay * hz;
709 		break;
710 	}
711 
712 	if (delay > 0)
713 		nd6_llinfo_settimer_locked(lle, delay);
714 
715 	lle->lle_remtime = remtime;
716 	lle->ln_state = newstate;
717 }
718 
719 /*
720  * Timer-dependent part of nd state machine.
721  *
722  * Set noinline to be dtrace-friendly
723  */
724 static __noinline void
725 nd6_llinfo_timer(void *arg)
726 {
727 	struct llentry *ln;
728 	struct in6_addr *dst, *pdst, *psrc, src;
729 	struct ifnet *ifp;
730 	struct nd_ifinfo *ndi;
731 	int do_switch, send_ns;
732 	long delay;
733 
734 	KASSERT(arg != NULL, ("%s: arg NULL", __func__));
735 	ln = (struct llentry *)arg;
736 	ifp = lltable_get_ifp(ln->lle_tbl);
737 	CURVNET_SET(ifp->if_vnet);
738 
739 	ND6_RLOCK();
740 	LLE_WLOCK(ln);
741 	if (callout_pending(&ln->lle_timer)) {
742 		/*
743 		 * Here we are a bit odd here in the treatment of
744 		 * active/pending. If the pending bit is set, it got
745 		 * rescheduled before I ran. The active
746 		 * bit we ignore, since if it was stopped
747 		 * in ll_tablefree() and was currently running
748 		 * it would have return 0 so the code would
749 		 * not have deleted it since the callout could
750 		 * not be stopped so we want to go through
751 		 * with the delete here now. If the callout
752 		 * was restarted, the pending bit will be back on and
753 		 * we just want to bail since the callout_reset would
754 		 * return 1 and our reference would have been removed
755 		 * by nd6_llinfo_settimer_locked above since canceled
756 		 * would have been 1.
757 		 */
758 		LLE_WUNLOCK(ln);
759 		ND6_RUNLOCK();
760 		CURVNET_RESTORE();
761 		return;
762 	}
763 	ndi = ND_IFINFO(ifp);
764 	send_ns = 0;
765 	dst = &ln->r_l3addr.addr6;
766 	pdst = dst;
767 
768 	if (ln->ln_ntick > 0) {
769 		if (ln->ln_ntick > INT_MAX) {
770 			ln->ln_ntick -= INT_MAX;
771 			nd6_llinfo_settimer_locked(ln, INT_MAX);
772 		} else {
773 			ln->ln_ntick = 0;
774 			nd6_llinfo_settimer_locked(ln, ln->ln_ntick);
775 		}
776 		goto done;
777 	}
778 
779 	if (ln->la_flags & LLE_STATIC) {
780 		goto done;
781 	}
782 
783 	if (ln->la_flags & LLE_DELETED) {
784 		nd6_free(&ln, 0);
785 		goto done;
786 	}
787 
788 	switch (ln->ln_state) {
789 	case ND6_LLINFO_INCOMPLETE:
790 		if (ln->la_asked < V_nd6_mmaxtries) {
791 			ln->la_asked++;
792 			send_ns = 1;
793 			/* Send NS to multicast address */
794 			pdst = NULL;
795 		} else {
796 			struct mbuf *m = ln->la_hold;
797 			if (m) {
798 				struct mbuf *m0;
799 
800 				/*
801 				 * assuming every packet in la_hold has the
802 				 * same IP header.  Send error after unlock.
803 				 */
804 				m0 = m->m_nextpkt;
805 				m->m_nextpkt = NULL;
806 				ln->la_hold = m0;
807 				clear_llinfo_pqueue(ln);
808 			}
809 			nd6_free(&ln, 0);
810 			if (m != NULL)
811 				icmp6_error2(m, ICMP6_DST_UNREACH,
812 				    ICMP6_DST_UNREACH_ADDR, 0, ifp);
813 		}
814 		break;
815 	case ND6_LLINFO_REACHABLE:
816 		if (!ND6_LLINFO_PERMANENT(ln))
817 			nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
818 		break;
819 
820 	case ND6_LLINFO_STALE:
821 		if (nd6_is_stale(ln, &delay, &do_switch) != 0) {
822 
823 			/*
824 			 * No packet has used this entry and GC timeout
825 			 * has not been passed. Reshedule timer and
826 			 * return.
827 			 */
828 			nd6_llinfo_settimer_locked(ln, delay);
829 			break;
830 		}
831 
832 		if (do_switch == 0) {
833 
834 			/*
835 			 * GC timer has ended and entry hasn't been used.
836 			 * Run Garbage collector (RFC 4861, 5.3)
837 			 */
838 			if (!ND6_LLINFO_PERMANENT(ln))
839 				nd6_free(&ln, 1);
840 			break;
841 		}
842 
843 		/* Entry has been used AND delay timer has ended. */
844 
845 		/* FALLTHROUGH */
846 
847 	case ND6_LLINFO_DELAY:
848 		if (ndi && (ndi->flags & ND6_IFF_PERFORMNUD) != 0) {
849 			/* We need NUD */
850 			ln->la_asked = 1;
851 			nd6_llinfo_setstate(ln, ND6_LLINFO_PROBE);
852 			send_ns = 1;
853 		} else
854 			nd6_llinfo_setstate(ln, ND6_LLINFO_STALE); /* XXX */
855 		break;
856 	case ND6_LLINFO_PROBE:
857 		if (ln->la_asked < V_nd6_umaxtries) {
858 			ln->la_asked++;
859 			send_ns = 1;
860 		} else {
861 			nd6_free(&ln, 0);
862 		}
863 		break;
864 	default:
865 		panic("%s: paths in a dark night can be confusing: %d",
866 		    __func__, ln->ln_state);
867 	}
868 done:
869 	if (ln != NULL)
870 		ND6_RUNLOCK();
871 	if (send_ns != 0) {
872 		nd6_llinfo_settimer_locked(ln, (long)ndi->retrans * hz / 1000);
873 		psrc = nd6_llinfo_get_holdsrc(ln, &src);
874 		LLE_FREE_LOCKED(ln);
875 		ln = NULL;
876 		nd6_ns_output(ifp, psrc, pdst, dst, NULL);
877 	}
878 
879 	if (ln != NULL)
880 		LLE_FREE_LOCKED(ln);
881 	CURVNET_RESTORE();
882 }
883 
884 
885 /*
886  * ND6 timer routine to expire default route list and prefix list
887  */
888 void
889 nd6_timer(void *arg)
890 {
891 	CURVNET_SET((struct vnet *) arg);
892 	struct nd_drhead drq;
893 	struct nd_defrouter *dr, *ndr;
894 	struct nd_prefix *pr, *npr;
895 	struct in6_ifaddr *ia6, *nia6;
896 
897 	callout_reset(&V_nd6_timer_ch, V_nd6_prune * hz,
898 	    nd6_timer, curvnet);
899 
900 	TAILQ_INIT(&drq);
901 
902 	/* expire default router list */
903 	ND6_WLOCK();
904 	TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr)
905 		if (dr->expire && dr->expire < time_uptime)
906 			defrouter_unlink(dr, &drq);
907 	ND6_WUNLOCK();
908 
909 	while ((dr = TAILQ_FIRST(&drq)) != NULL) {
910 		TAILQ_REMOVE(&drq, dr, dr_entry);
911 		defrouter_del(dr);
912 	}
913 
914 	/*
915 	 * expire interface addresses.
916 	 * in the past the loop was inside prefix expiry processing.
917 	 * However, from a stricter speci-confrmance standpoint, we should
918 	 * rather separate address lifetimes and prefix lifetimes.
919 	 *
920 	 * XXXRW: in6_ifaddrhead locking.
921 	 */
922   addrloop:
923 	TAILQ_FOREACH_SAFE(ia6, &V_in6_ifaddrhead, ia_link, nia6) {
924 		/* check address lifetime */
925 		if (IFA6_IS_INVALID(ia6)) {
926 			int regen = 0;
927 
928 			/*
929 			 * If the expiring address is temporary, try
930 			 * regenerating a new one.  This would be useful when
931 			 * we suspended a laptop PC, then turned it on after a
932 			 * period that could invalidate all temporary
933 			 * addresses.  Although we may have to restart the
934 			 * loop (see below), it must be after purging the
935 			 * address.  Otherwise, we'd see an infinite loop of
936 			 * regeneration.
937 			 */
938 			if (V_ip6_use_tempaddr &&
939 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
940 				if (regen_tmpaddr(ia6) == 0)
941 					regen = 1;
942 			}
943 
944 			in6_purgeaddr(&ia6->ia_ifa);
945 
946 			if (regen)
947 				goto addrloop; /* XXX: see below */
948 		} else if (IFA6_IS_DEPRECATED(ia6)) {
949 			int oldflags = ia6->ia6_flags;
950 
951 			ia6->ia6_flags |= IN6_IFF_DEPRECATED;
952 
953 			/*
954 			 * If a temporary address has just become deprecated,
955 			 * regenerate a new one if possible.
956 			 */
957 			if (V_ip6_use_tempaddr &&
958 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
959 			    (oldflags & IN6_IFF_DEPRECATED) == 0) {
960 
961 				if (regen_tmpaddr(ia6) == 0) {
962 					/*
963 					 * A new temporary address is
964 					 * generated.
965 					 * XXX: this means the address chain
966 					 * has changed while we are still in
967 					 * the loop.  Although the change
968 					 * would not cause disaster (because
969 					 * it's not a deletion, but an
970 					 * addition,) we'd rather restart the
971 					 * loop just for safety.  Or does this
972 					 * significantly reduce performance??
973 					 */
974 					goto addrloop;
975 				}
976 			}
977 		} else if ((ia6->ia6_flags & IN6_IFF_TENTATIVE) != 0) {
978 			/*
979 			 * Schedule DAD for a tentative address.  This happens
980 			 * if the interface was down or not running
981 			 * when the address was configured.
982 			 */
983 			int delay;
984 
985 			delay = arc4random() %
986 			    (MAX_RTR_SOLICITATION_DELAY * hz);
987 			nd6_dad_start((struct ifaddr *)ia6, delay);
988 		} else {
989 			/*
990 			 * Check status of the interface.  If it is down,
991 			 * mark the address as tentative for future DAD.
992 			 */
993 			if ((ia6->ia_ifp->if_flags & IFF_UP) == 0 ||
994 			    (ia6->ia_ifp->if_drv_flags & IFF_DRV_RUNNING)
995 				== 0 ||
996 			    (ND_IFINFO(ia6->ia_ifp)->flags &
997 				ND6_IFF_IFDISABLED) != 0) {
998 				ia6->ia6_flags &= ~IN6_IFF_DUPLICATED;
999 				ia6->ia6_flags |= IN6_IFF_TENTATIVE;
1000 			}
1001 			/*
1002 			 * A new RA might have made a deprecated address
1003 			 * preferred.
1004 			 */
1005 			ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
1006 		}
1007 	}
1008 
1009 	/* expire prefix list */
1010 	LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
1011 		/*
1012 		 * check prefix lifetime.
1013 		 * since pltime is just for autoconf, pltime processing for
1014 		 * prefix is not necessary.
1015 		 */
1016 		if (pr->ndpr_vltime != ND6_INFINITE_LIFETIME &&
1017 		    time_uptime - pr->ndpr_lastupdate > pr->ndpr_vltime) {
1018 
1019 			/*
1020 			 * address expiration and prefix expiration are
1021 			 * separate.  NEVER perform in6_purgeaddr here.
1022 			 */
1023 			prelist_remove(pr);
1024 		}
1025 	}
1026 	CURVNET_RESTORE();
1027 }
1028 
1029 /*
1030  * ia6 - deprecated/invalidated temporary address
1031  */
1032 static int
1033 regen_tmpaddr(struct in6_ifaddr *ia6)
1034 {
1035 	struct ifaddr *ifa;
1036 	struct ifnet *ifp;
1037 	struct in6_ifaddr *public_ifa6 = NULL;
1038 
1039 	ifp = ia6->ia_ifa.ifa_ifp;
1040 	IF_ADDR_RLOCK(ifp);
1041 	TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1042 		struct in6_ifaddr *it6;
1043 
1044 		if (ifa->ifa_addr->sa_family != AF_INET6)
1045 			continue;
1046 
1047 		it6 = (struct in6_ifaddr *)ifa;
1048 
1049 		/* ignore no autoconf addresses. */
1050 		if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1051 			continue;
1052 
1053 		/* ignore autoconf addresses with different prefixes. */
1054 		if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr)
1055 			continue;
1056 
1057 		/*
1058 		 * Now we are looking at an autoconf address with the same
1059 		 * prefix as ours.  If the address is temporary and is still
1060 		 * preferred, do not create another one.  It would be rare, but
1061 		 * could happen, for example, when we resume a laptop PC after
1062 		 * a long period.
1063 		 */
1064 		if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1065 		    !IFA6_IS_DEPRECATED(it6)) {
1066 			public_ifa6 = NULL;
1067 			break;
1068 		}
1069 
1070 		/*
1071 		 * This is a public autoconf address that has the same prefix
1072 		 * as ours.  If it is preferred, keep it.  We can't break the
1073 		 * loop here, because there may be a still-preferred temporary
1074 		 * address with the prefix.
1075 		 */
1076 		if (!IFA6_IS_DEPRECATED(it6))
1077 			public_ifa6 = it6;
1078 	}
1079 	if (public_ifa6 != NULL)
1080 		ifa_ref(&public_ifa6->ia_ifa);
1081 	IF_ADDR_RUNLOCK(ifp);
1082 
1083 	if (public_ifa6 != NULL) {
1084 		int e;
1085 
1086 		if ((e = in6_tmpifadd(public_ifa6, 0, 0)) != 0) {
1087 			ifa_free(&public_ifa6->ia_ifa);
1088 			log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
1089 			    " tmp addr,errno=%d\n", e);
1090 			return (-1);
1091 		}
1092 		ifa_free(&public_ifa6->ia_ifa);
1093 		return (0);
1094 	}
1095 
1096 	return (-1);
1097 }
1098 
1099 /*
1100  * Remove prefix and default router list entries corresponding to ifp. Neighbor
1101  * cache entries are freed in in6_domifdetach().
1102  */
1103 void
1104 nd6_purge(struct ifnet *ifp)
1105 {
1106 	struct nd_drhead drq;
1107 	struct nd_defrouter *dr, *ndr;
1108 	struct nd_prefix *pr, *npr;
1109 
1110 	TAILQ_INIT(&drq);
1111 
1112 	/*
1113 	 * Nuke default router list entries toward ifp.
1114 	 * We defer removal of default router list entries that is installed
1115 	 * in the routing table, in order to keep additional side effects as
1116 	 * small as possible.
1117 	 */
1118 	ND6_WLOCK();
1119 	TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr) {
1120 		if (dr->installed)
1121 			continue;
1122 		if (dr->ifp == ifp)
1123 			defrouter_unlink(dr, &drq);
1124 	}
1125 
1126 	TAILQ_FOREACH_SAFE(dr, &V_nd_defrouter, dr_entry, ndr) {
1127 		if (!dr->installed)
1128 			continue;
1129 		if (dr->ifp == ifp)
1130 			defrouter_unlink(dr, &drq);
1131 	}
1132 	ND6_WUNLOCK();
1133 
1134 	while ((dr = TAILQ_FIRST(&drq)) != NULL) {
1135 		TAILQ_REMOVE(&drq, dr, dr_entry);
1136 		defrouter_del(dr);
1137 	}
1138 
1139 	/* Nuke prefix list entries toward ifp */
1140 	LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, npr) {
1141 		if (pr->ndpr_ifp == ifp) {
1142 			/*
1143 			 * Because if_detach() does *not* release prefixes
1144 			 * while purging addresses the reference count will
1145 			 * still be above zero. We therefore reset it to
1146 			 * make sure that the prefix really gets purged.
1147 			 */
1148 			pr->ndpr_refcnt = 0;
1149 
1150 			prelist_remove(pr);
1151 		}
1152 	}
1153 
1154 	/* cancel default outgoing interface setting */
1155 	if (V_nd6_defifindex == ifp->if_index)
1156 		nd6_setdefaultiface(0);
1157 
1158 	if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1159 		/* Refresh default router list. */
1160 		defrouter_select();
1161 	}
1162 }
1163 
1164 /*
1165  * the caller acquires and releases the lock on the lltbls
1166  * Returns the llentry locked
1167  */
1168 struct llentry *
1169 nd6_lookup(const struct in6_addr *addr6, int flags, struct ifnet *ifp)
1170 {
1171 	struct sockaddr_in6 sin6;
1172 	struct llentry *ln;
1173 
1174 	bzero(&sin6, sizeof(sin6));
1175 	sin6.sin6_len = sizeof(struct sockaddr_in6);
1176 	sin6.sin6_family = AF_INET6;
1177 	sin6.sin6_addr = *addr6;
1178 
1179 	IF_AFDATA_LOCK_ASSERT(ifp);
1180 
1181 	ln = lla_lookup(LLTABLE6(ifp), flags, (struct sockaddr *)&sin6);
1182 
1183 	return (ln);
1184 }
1185 
1186 struct llentry *
1187 nd6_alloc(const struct in6_addr *addr6, int flags, struct ifnet *ifp)
1188 {
1189 	struct sockaddr_in6 sin6;
1190 	struct llentry *ln;
1191 
1192 	bzero(&sin6, sizeof(sin6));
1193 	sin6.sin6_len = sizeof(struct sockaddr_in6);
1194 	sin6.sin6_family = AF_INET6;
1195 	sin6.sin6_addr = *addr6;
1196 
1197 	ln = lltable_alloc_entry(LLTABLE6(ifp), 0, (struct sockaddr *)&sin6);
1198 	if (ln != NULL)
1199 		ln->ln_state = ND6_LLINFO_NOSTATE;
1200 
1201 	return (ln);
1202 }
1203 
1204 /*
1205  * Test whether a given IPv6 address is a neighbor or not, ignoring
1206  * the actual neighbor cache.  The neighbor cache is ignored in order
1207  * to not reenter the routing code from within itself.
1208  */
1209 static int
1210 nd6_is_new_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
1211 {
1212 	struct nd_prefix *pr;
1213 	struct ifaddr *dstaddr;
1214 	struct rt_addrinfo info;
1215 	struct sockaddr_in6 rt_key;
1216 	struct sockaddr *dst6;
1217 	int fibnum;
1218 
1219 	/*
1220 	 * A link-local address is always a neighbor.
1221 	 * XXX: a link does not necessarily specify a single interface.
1222 	 */
1223 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
1224 		struct sockaddr_in6 sin6_copy;
1225 		u_int32_t zone;
1226 
1227 		/*
1228 		 * We need sin6_copy since sa6_recoverscope() may modify the
1229 		 * content (XXX).
1230 		 */
1231 		sin6_copy = *addr;
1232 		if (sa6_recoverscope(&sin6_copy))
1233 			return (0); /* XXX: should be impossible */
1234 		if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone))
1235 			return (0);
1236 		if (sin6_copy.sin6_scope_id == zone)
1237 			return (1);
1238 		else
1239 			return (0);
1240 	}
1241 
1242 	bzero(&rt_key, sizeof(rt_key));
1243 	bzero(&info, sizeof(info));
1244 	info.rti_info[RTAX_DST] = (struct sockaddr *)&rt_key;
1245 
1246 	/* Always use the default FIB here. XXME - why? */
1247 	fibnum = RT_DEFAULT_FIB;
1248 
1249 	/*
1250 	 * If the address matches one of our addresses,
1251 	 * it should be a neighbor.
1252 	 * If the address matches one of our on-link prefixes, it should be a
1253 	 * neighbor.
1254 	 */
1255 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1256 		if (pr->ndpr_ifp != ifp)
1257 			continue;
1258 
1259 		if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
1260 
1261 			/* Always use the default FIB here. */
1262 			dst6 = (struct sockaddr *)&pr->ndpr_prefix;
1263 
1264 			/* Restore length field before retrying lookup */
1265 			rt_key.sin6_len = sizeof(rt_key);
1266 			if (rib_lookup_info(fibnum, dst6, 0, 0, &info) != 0)
1267 				continue;
1268 			/*
1269 			 * This is the case where multiple interfaces
1270 			 * have the same prefix, but only one is installed
1271 			 * into the routing table and that prefix entry
1272 			 * is not the one being examined here. In the case
1273 			 * where RADIX_MPATH is enabled, multiple route
1274 			 * entries (of the same rt_key value) will be
1275 			 * installed because the interface addresses all
1276 			 * differ.
1277 			 */
1278 			if (!IN6_ARE_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
1279 			       &rt_key.sin6_addr))
1280 				continue;
1281 		}
1282 
1283 		if (IN6_ARE_MASKED_ADDR_EQUAL(&pr->ndpr_prefix.sin6_addr,
1284 		    &addr->sin6_addr, &pr->ndpr_mask))
1285 			return (1);
1286 	}
1287 
1288 	/*
1289 	 * If the address is assigned on the node of the other side of
1290 	 * a p2p interface, the address should be a neighbor.
1291 	 */
1292 	dstaddr = ifa_ifwithdstaddr((const struct sockaddr *)addr, RT_ALL_FIBS);
1293 	if (dstaddr != NULL) {
1294 		if (dstaddr->ifa_ifp == ifp) {
1295 			ifa_free(dstaddr);
1296 			return (1);
1297 		}
1298 		ifa_free(dstaddr);
1299 	}
1300 
1301 	/*
1302 	 * If the default router list is empty, all addresses are regarded
1303 	 * as on-link, and thus, as a neighbor.
1304 	 */
1305 	if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV &&
1306 	    TAILQ_EMPTY(&V_nd_defrouter) &&
1307 	    V_nd6_defifindex == ifp->if_index) {
1308 		return (1);
1309 	}
1310 
1311 	return (0);
1312 }
1313 
1314 
1315 /*
1316  * Detect if a given IPv6 address identifies a neighbor on a given link.
1317  * XXX: should take care of the destination of a p2p link?
1318  */
1319 int
1320 nd6_is_addr_neighbor(const struct sockaddr_in6 *addr, struct ifnet *ifp)
1321 {
1322 	struct llentry *lle;
1323 	int rc = 0;
1324 
1325 	IF_AFDATA_UNLOCK_ASSERT(ifp);
1326 	if (nd6_is_new_addr_neighbor(addr, ifp))
1327 		return (1);
1328 
1329 	/*
1330 	 * Even if the address matches none of our addresses, it might be
1331 	 * in the neighbor cache.
1332 	 */
1333 	IF_AFDATA_RLOCK(ifp);
1334 	if ((lle = nd6_lookup(&addr->sin6_addr, 0, ifp)) != NULL) {
1335 		LLE_RUNLOCK(lle);
1336 		rc = 1;
1337 	}
1338 	IF_AFDATA_RUNLOCK(ifp);
1339 	return (rc);
1340 }
1341 
1342 /*
1343  * Free an nd6 llinfo entry.
1344  * Since the function would cause significant changes in the kernel, DO NOT
1345  * make it global, unless you have a strong reason for the change, and are sure
1346  * that the change is safe.
1347  *
1348  * Set noinline to be dtrace-friendly
1349  */
1350 static __noinline void
1351 nd6_free(struct llentry **lnp, int gc)
1352 {
1353 	struct ifnet *ifp;
1354 	struct llentry *ln;
1355 	struct nd_defrouter *dr;
1356 
1357 	ln = *lnp;
1358 	*lnp = NULL;
1359 
1360 	LLE_WLOCK_ASSERT(ln);
1361 	ND6_RLOCK_ASSERT();
1362 
1363 	ifp = lltable_get_ifp(ln->lle_tbl);
1364 	if ((ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) != 0)
1365 		dr = defrouter_lookup_locked(&ln->r_l3addr.addr6, ifp);
1366 	else
1367 		dr = NULL;
1368 	ND6_RUNLOCK();
1369 
1370 	if ((ln->la_flags & LLE_DELETED) == 0)
1371 		EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_EXPIRED);
1372 
1373 	/*
1374 	 * we used to have pfctlinput(PRC_HOSTDEAD) here.
1375 	 * even though it is not harmful, it was not really necessary.
1376 	 */
1377 
1378 	/* cancel timer */
1379 	nd6_llinfo_settimer_locked(ln, -1);
1380 
1381 	if (ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
1382 		if (dr != NULL && dr->expire &&
1383 		    ln->ln_state == ND6_LLINFO_STALE && gc) {
1384 			/*
1385 			 * If the reason for the deletion is just garbage
1386 			 * collection, and the neighbor is an active default
1387 			 * router, do not delete it.  Instead, reset the GC
1388 			 * timer using the router's lifetime.
1389 			 * Simply deleting the entry would affect default
1390 			 * router selection, which is not necessarily a good
1391 			 * thing, especially when we're using router preference
1392 			 * values.
1393 			 * XXX: the check for ln_state would be redundant,
1394 			 *      but we intentionally keep it just in case.
1395 			 */
1396 			if (dr->expire > time_uptime)
1397 				nd6_llinfo_settimer_locked(ln,
1398 				    (dr->expire - time_uptime) * hz);
1399 			else
1400 				nd6_llinfo_settimer_locked(ln,
1401 				    (long)V_nd6_gctimer * hz);
1402 
1403 			LLE_REMREF(ln);
1404 			LLE_WUNLOCK(ln);
1405 			defrouter_rele(dr);
1406 			return;
1407 		}
1408 
1409 		if (dr) {
1410 			/*
1411 			 * Unreachablity of a router might affect the default
1412 			 * router selection and on-link detection of advertised
1413 			 * prefixes.
1414 			 */
1415 
1416 			/*
1417 			 * Temporarily fake the state to choose a new default
1418 			 * router and to perform on-link determination of
1419 			 * prefixes correctly.
1420 			 * Below the state will be set correctly,
1421 			 * or the entry itself will be deleted.
1422 			 */
1423 			ln->ln_state = ND6_LLINFO_INCOMPLETE;
1424 		}
1425 
1426 		if (ln->ln_router || dr) {
1427 
1428 			/*
1429 			 * We need to unlock to avoid a LOR with rt6_flush() with the
1430 			 * rnh and for the calls to pfxlist_onlink_check() and
1431 			 * defrouter_select() in the block further down for calls
1432 			 * into nd6_lookup().  We still hold a ref.
1433 			 */
1434 			LLE_WUNLOCK(ln);
1435 
1436 			/*
1437 			 * rt6_flush must be called whether or not the neighbor
1438 			 * is in the Default Router List.
1439 			 * See a corresponding comment in nd6_na_input().
1440 			 */
1441 			rt6_flush(&ln->r_l3addr.addr6, ifp);
1442 		}
1443 
1444 		if (dr) {
1445 			/*
1446 			 * Since defrouter_select() does not affect the
1447 			 * on-link determination and MIP6 needs the check
1448 			 * before the default router selection, we perform
1449 			 * the check now.
1450 			 */
1451 			pfxlist_onlink_check();
1452 
1453 			/*
1454 			 * Refresh default router list.
1455 			 */
1456 			defrouter_select();
1457 		}
1458 
1459 		/*
1460 		 * If this entry was added by an on-link redirect, remove the
1461 		 * corresponding host route.
1462 		 */
1463 		if (ln->la_flags & LLE_REDIRECT)
1464 			nd6_free_redirect(ln);
1465 
1466 		if (ln->ln_router || dr)
1467 			LLE_WLOCK(ln);
1468 	}
1469 
1470 	/*
1471 	 * Save to unlock. We still hold an extra reference and will not
1472 	 * free(9) in llentry_free() if someone else holds one as well.
1473 	 */
1474 	LLE_WUNLOCK(ln);
1475 	IF_AFDATA_LOCK(ifp);
1476 	LLE_WLOCK(ln);
1477 	/* Guard against race with other llentry_free(). */
1478 	if (ln->la_flags & LLE_LINKED) {
1479 		/* Remove callout reference */
1480 		LLE_REMREF(ln);
1481 		lltable_unlink_entry(ln->lle_tbl, ln);
1482 	}
1483 	IF_AFDATA_UNLOCK(ifp);
1484 
1485 	llentry_free(ln);
1486 	if (dr != NULL)
1487 		defrouter_rele(dr);
1488 }
1489 
1490 static int
1491 nd6_isdynrte(const struct rtentry *rt, void *xap)
1492 {
1493 
1494 	if (rt->rt_flags == (RTF_UP | RTF_HOST | RTF_DYNAMIC))
1495 		return (1);
1496 
1497 	return (0);
1498 }
1499 /*
1500  * Remove the rtentry for the given llentry,
1501  * both of which were installed by a redirect.
1502  */
1503 static void
1504 nd6_free_redirect(const struct llentry *ln)
1505 {
1506 	int fibnum;
1507 	struct sockaddr_in6 sin6;
1508 	struct rt_addrinfo info;
1509 
1510 	lltable_fill_sa_entry(ln, (struct sockaddr *)&sin6);
1511 	memset(&info, 0, sizeof(info));
1512 	info.rti_info[RTAX_DST] = (struct sockaddr *)&sin6;
1513 	info.rti_filter = nd6_isdynrte;
1514 
1515 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++)
1516 		rtrequest1_fib(RTM_DELETE, &info, NULL, fibnum);
1517 }
1518 
1519 /*
1520  * Rejuvenate this function for routing operations related
1521  * processing.
1522  */
1523 void
1524 nd6_rtrequest(int req, struct rtentry *rt, struct rt_addrinfo *info)
1525 {
1526 	struct sockaddr_in6 *gateway;
1527 	struct nd_defrouter *dr;
1528 	struct ifnet *ifp;
1529 
1530 	gateway = (struct sockaddr_in6 *)rt->rt_gateway;
1531 	ifp = rt->rt_ifp;
1532 
1533 	switch (req) {
1534 	case RTM_ADD:
1535 		break;
1536 
1537 	case RTM_DELETE:
1538 		if (!ifp)
1539 			return;
1540 		/*
1541 		 * Only indirect routes are interesting.
1542 		 */
1543 		if ((rt->rt_flags & RTF_GATEWAY) == 0)
1544 			return;
1545 		/*
1546 		 * check for default route
1547 		 */
1548 		if (IN6_ARE_ADDR_EQUAL(&in6addr_any,
1549 		    &SIN6(rt_key(rt))->sin6_addr)) {
1550 			dr = defrouter_lookup(&gateway->sin6_addr, ifp);
1551 			if (dr != NULL) {
1552 				dr->installed = 0;
1553 				defrouter_rele(dr);
1554 			}
1555 		}
1556 		break;
1557 	}
1558 }
1559 
1560 
1561 int
1562 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
1563 {
1564 	struct in6_ndireq *ndi = (struct in6_ndireq *)data;
1565 	struct in6_nbrinfo *nbi = (struct in6_nbrinfo *)data;
1566 	struct in6_ndifreq *ndif = (struct in6_ndifreq *)data;
1567 	int error = 0;
1568 
1569 	if (ifp->if_afdata[AF_INET6] == NULL)
1570 		return (EPFNOSUPPORT);
1571 	switch (cmd) {
1572 	case OSIOCGIFINFO_IN6:
1573 #define ND	ndi->ndi
1574 		/* XXX: old ndp(8) assumes a positive value for linkmtu. */
1575 		bzero(&ND, sizeof(ND));
1576 		ND.linkmtu = IN6_LINKMTU(ifp);
1577 		ND.maxmtu = ND_IFINFO(ifp)->maxmtu;
1578 		ND.basereachable = ND_IFINFO(ifp)->basereachable;
1579 		ND.reachable = ND_IFINFO(ifp)->reachable;
1580 		ND.retrans = ND_IFINFO(ifp)->retrans;
1581 		ND.flags = ND_IFINFO(ifp)->flags;
1582 		ND.recalctm = ND_IFINFO(ifp)->recalctm;
1583 		ND.chlim = ND_IFINFO(ifp)->chlim;
1584 		break;
1585 	case SIOCGIFINFO_IN6:
1586 		ND = *ND_IFINFO(ifp);
1587 		break;
1588 	case SIOCSIFINFO_IN6:
1589 		/*
1590 		 * used to change host variables from userland.
1591 		 * intended for a use on router to reflect RA configurations.
1592 		 */
1593 		/* 0 means 'unspecified' */
1594 		if (ND.linkmtu != 0) {
1595 			if (ND.linkmtu < IPV6_MMTU ||
1596 			    ND.linkmtu > IN6_LINKMTU(ifp)) {
1597 				error = EINVAL;
1598 				break;
1599 			}
1600 			ND_IFINFO(ifp)->linkmtu = ND.linkmtu;
1601 		}
1602 
1603 		if (ND.basereachable != 0) {
1604 			int obasereachable = ND_IFINFO(ifp)->basereachable;
1605 
1606 			ND_IFINFO(ifp)->basereachable = ND.basereachable;
1607 			if (ND.basereachable != obasereachable)
1608 				ND_IFINFO(ifp)->reachable =
1609 				    ND_COMPUTE_RTIME(ND.basereachable);
1610 		}
1611 		if (ND.retrans != 0)
1612 			ND_IFINFO(ifp)->retrans = ND.retrans;
1613 		if (ND.chlim != 0)
1614 			ND_IFINFO(ifp)->chlim = ND.chlim;
1615 		/* FALLTHROUGH */
1616 	case SIOCSIFINFO_FLAGS:
1617 	{
1618 		struct ifaddr *ifa;
1619 		struct in6_ifaddr *ia;
1620 
1621 		if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1622 		    !(ND.flags & ND6_IFF_IFDISABLED)) {
1623 			/* ifdisabled 1->0 transision */
1624 
1625 			/*
1626 			 * If the interface is marked as ND6_IFF_IFDISABLED and
1627 			 * has an link-local address with IN6_IFF_DUPLICATED,
1628 			 * do not clear ND6_IFF_IFDISABLED.
1629 			 * See RFC 4862, Section 5.4.5.
1630 			 */
1631 			IF_ADDR_RLOCK(ifp);
1632 			TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1633 				if (ifa->ifa_addr->sa_family != AF_INET6)
1634 					continue;
1635 				ia = (struct in6_ifaddr *)ifa;
1636 				if ((ia->ia6_flags & IN6_IFF_DUPLICATED) &&
1637 				    IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1638 					break;
1639 			}
1640 			IF_ADDR_RUNLOCK(ifp);
1641 
1642 			if (ifa != NULL) {
1643 				/* LLA is duplicated. */
1644 				ND.flags |= ND6_IFF_IFDISABLED;
1645 				log(LOG_ERR, "Cannot enable an interface"
1646 				    " with a link-local address marked"
1647 				    " duplicate.\n");
1648 			} else {
1649 				ND_IFINFO(ifp)->flags &= ~ND6_IFF_IFDISABLED;
1650 				if (ifp->if_flags & IFF_UP)
1651 					in6_if_up(ifp);
1652 			}
1653 		} else if (!(ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED) &&
1654 			    (ND.flags & ND6_IFF_IFDISABLED)) {
1655 			/* ifdisabled 0->1 transision */
1656 			/* Mark all IPv6 address as tentative. */
1657 
1658 			ND_IFINFO(ifp)->flags |= ND6_IFF_IFDISABLED;
1659 			if (V_ip6_dad_count > 0 &&
1660 			    (ND_IFINFO(ifp)->flags & ND6_IFF_NO_DAD) == 0) {
1661 				IF_ADDR_RLOCK(ifp);
1662 				TAILQ_FOREACH(ifa, &ifp->if_addrhead,
1663 				    ifa_link) {
1664 					if (ifa->ifa_addr->sa_family !=
1665 					    AF_INET6)
1666 						continue;
1667 					ia = (struct in6_ifaddr *)ifa;
1668 					ia->ia6_flags |= IN6_IFF_TENTATIVE;
1669 				}
1670 				IF_ADDR_RUNLOCK(ifp);
1671 			}
1672 		}
1673 
1674 		if (ND.flags & ND6_IFF_AUTO_LINKLOCAL) {
1675 			if (!(ND_IFINFO(ifp)->flags & ND6_IFF_AUTO_LINKLOCAL)) {
1676 				/* auto_linklocal 0->1 transision */
1677 
1678 				/* If no link-local address on ifp, configure */
1679 				ND_IFINFO(ifp)->flags |= ND6_IFF_AUTO_LINKLOCAL;
1680 				in6_ifattach(ifp, NULL);
1681 			} else if (!(ND.flags & ND6_IFF_IFDISABLED) &&
1682 			    ifp->if_flags & IFF_UP) {
1683 				/*
1684 				 * When the IF already has
1685 				 * ND6_IFF_AUTO_LINKLOCAL, no link-local
1686 				 * address is assigned, and IFF_UP, try to
1687 				 * assign one.
1688 				 */
1689 				IF_ADDR_RLOCK(ifp);
1690 				TAILQ_FOREACH(ifa, &ifp->if_addrhead,
1691 				    ifa_link) {
1692 					if (ifa->ifa_addr->sa_family !=
1693 					    AF_INET6)
1694 						continue;
1695 					ia = (struct in6_ifaddr *)ifa;
1696 					if (IN6_IS_ADDR_LINKLOCAL(IA6_IN6(ia)))
1697 						break;
1698 				}
1699 				IF_ADDR_RUNLOCK(ifp);
1700 				if (ifa != NULL)
1701 					/* No LLA is configured. */
1702 					in6_ifattach(ifp, NULL);
1703 			}
1704 		}
1705 	}
1706 		ND_IFINFO(ifp)->flags = ND.flags;
1707 		break;
1708 #undef ND
1709 	case SIOCSNDFLUSH_IN6:	/* XXX: the ioctl name is confusing... */
1710 		/* sync kernel routing table with the default router list */
1711 		defrouter_reset();
1712 		defrouter_select();
1713 		break;
1714 	case SIOCSPFXFLUSH_IN6:
1715 	{
1716 		/* flush all the prefix advertised by routers */
1717 		struct nd_prefix *pr, *next;
1718 
1719 		LIST_FOREACH_SAFE(pr, &V_nd_prefix, ndpr_entry, next) {
1720 			struct in6_ifaddr *ia, *ia_next;
1721 
1722 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
1723 				continue; /* XXX */
1724 
1725 			/* do we really have to remove addresses as well? */
1726 			/* XXXRW: in6_ifaddrhead locking. */
1727 			TAILQ_FOREACH_SAFE(ia, &V_in6_ifaddrhead, ia_link,
1728 			    ia_next) {
1729 				if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1730 					continue;
1731 
1732 				if (ia->ia6_ndpr == pr)
1733 					in6_purgeaddr(&ia->ia_ifa);
1734 			}
1735 			prelist_remove(pr);
1736 		}
1737 		break;
1738 	}
1739 	case SIOCSRTRFLUSH_IN6:
1740 	{
1741 		/* flush all the default routers */
1742 		struct nd_drhead drq;
1743 		struct nd_defrouter *dr;
1744 
1745 		TAILQ_INIT(&drq);
1746 
1747 		defrouter_reset();
1748 
1749 		ND6_WLOCK();
1750 		while ((dr = TAILQ_FIRST(&V_nd_defrouter)) != NULL)
1751 			defrouter_unlink(dr, &drq);
1752 		ND6_WUNLOCK();
1753 		while ((dr = TAILQ_FIRST(&drq)) != NULL) {
1754 			TAILQ_REMOVE(&drq, dr, dr_entry);
1755 			defrouter_del(dr);
1756 		}
1757 
1758 		defrouter_select();
1759 		break;
1760 	}
1761 	case SIOCGNBRINFO_IN6:
1762 	{
1763 		struct llentry *ln;
1764 		struct in6_addr nb_addr = nbi->addr; /* make local for safety */
1765 
1766 		if ((error = in6_setscope(&nb_addr, ifp, NULL)) != 0)
1767 			return (error);
1768 
1769 		IF_AFDATA_RLOCK(ifp);
1770 		ln = nd6_lookup(&nb_addr, 0, ifp);
1771 		IF_AFDATA_RUNLOCK(ifp);
1772 
1773 		if (ln == NULL) {
1774 			error = EINVAL;
1775 			break;
1776 		}
1777 		nbi->state = ln->ln_state;
1778 		nbi->asked = ln->la_asked;
1779 		nbi->isrouter = ln->ln_router;
1780 		if (ln->la_expire == 0)
1781 			nbi->expire = 0;
1782 		else
1783 			nbi->expire = ln->la_expire + ln->lle_remtime / hz +
1784 			    (time_second - time_uptime);
1785 		LLE_RUNLOCK(ln);
1786 		break;
1787 	}
1788 	case SIOCGDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1789 		ndif->ifindex = V_nd6_defifindex;
1790 		break;
1791 	case SIOCSDEFIFACE_IN6:	/* XXX: should be implemented as a sysctl? */
1792 		return (nd6_setdefaultiface(ndif->ifindex));
1793 	}
1794 	return (error);
1795 }
1796 
1797 /*
1798  * Calculates new isRouter value based on provided parameters and
1799  * returns it.
1800  */
1801 static int
1802 nd6_is_router(int type, int code, int is_new, int old_addr, int new_addr,
1803     int ln_router)
1804 {
1805 
1806 	/*
1807 	 * ICMP6 type dependent behavior.
1808 	 *
1809 	 * NS: clear IsRouter if new entry
1810 	 * RS: clear IsRouter
1811 	 * RA: set IsRouter if there's lladdr
1812 	 * redir: clear IsRouter if new entry
1813 	 *
1814 	 * RA case, (1):
1815 	 * The spec says that we must set IsRouter in the following cases:
1816 	 * - If lladdr exist, set IsRouter.  This means (1-5).
1817 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
1818 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
1819 	 * A quetion arises for (1) case.  (1) case has no lladdr in the
1820 	 * neighbor cache, this is similar to (6).
1821 	 * This case is rare but we figured that we MUST NOT set IsRouter.
1822 	 *
1823 	 *   is_new  old_addr new_addr 	    NS  RS  RA	redir
1824 	 *							D R
1825 	 *	0	n	n	(1)	c   ?     s
1826 	 *	0	y	n	(2)	c   s     s
1827 	 *	0	n	y	(3)	c   s     s
1828 	 *	0	y	y	(4)	c   s     s
1829 	 *	0	y	y	(5)	c   s     s
1830 	 *	1	--	n	(6) c	c	c s
1831 	 *	1	--	y	(7) c	c   s	c s
1832 	 *
1833 	 *					(c=clear s=set)
1834 	 */
1835 	switch (type & 0xff) {
1836 	case ND_NEIGHBOR_SOLICIT:
1837 		/*
1838 		 * New entry must have is_router flag cleared.
1839 		 */
1840 		if (is_new)					/* (6-7) */
1841 			ln_router = 0;
1842 		break;
1843 	case ND_REDIRECT:
1844 		/*
1845 		 * If the icmp is a redirect to a better router, always set the
1846 		 * is_router flag.  Otherwise, if the entry is newly created,
1847 		 * clear the flag.  [RFC 2461, sec 8.3]
1848 		 */
1849 		if (code == ND_REDIRECT_ROUTER)
1850 			ln_router = 1;
1851 		else {
1852 			if (is_new)				/* (6-7) */
1853 				ln_router = 0;
1854 		}
1855 		break;
1856 	case ND_ROUTER_SOLICIT:
1857 		/*
1858 		 * is_router flag must always be cleared.
1859 		 */
1860 		ln_router = 0;
1861 		break;
1862 	case ND_ROUTER_ADVERT:
1863 		/*
1864 		 * Mark an entry with lladdr as a router.
1865 		 */
1866 		if ((!is_new && (old_addr || new_addr)) ||	/* (2-5) */
1867 		    (is_new && new_addr)) {			/* (7) */
1868 			ln_router = 1;
1869 		}
1870 		break;
1871 	}
1872 
1873 	return (ln_router);
1874 }
1875 
1876 /*
1877  * Create neighbor cache entry and cache link-layer address,
1878  * on reception of inbound ND6 packets.  (RS/RA/NS/redirect)
1879  *
1880  * type - ICMP6 type
1881  * code - type dependent information
1882  *
1883  */
1884 void
1885 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
1886     int lladdrlen, int type, int code)
1887 {
1888 	struct llentry *ln = NULL, *ln_tmp;
1889 	int is_newentry;
1890 	int do_update;
1891 	int olladdr;
1892 	int llchange;
1893 	int flags;
1894 	uint16_t router = 0;
1895 	struct sockaddr_in6 sin6;
1896 	struct mbuf *chain = NULL;
1897 	u_char linkhdr[LLE_MAX_LINKHDR];
1898 	size_t linkhdrsize;
1899 	int lladdr_off;
1900 
1901 	IF_AFDATA_UNLOCK_ASSERT(ifp);
1902 
1903 	KASSERT(ifp != NULL, ("%s: ifp == NULL", __func__));
1904 	KASSERT(from != NULL, ("%s: from == NULL", __func__));
1905 
1906 	/* nothing must be updated for unspecified address */
1907 	if (IN6_IS_ADDR_UNSPECIFIED(from))
1908 		return;
1909 
1910 	/*
1911 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
1912 	 * the caller.
1913 	 *
1914 	 * XXX If the link does not have link-layer adderss, what should
1915 	 * we do? (ifp->if_addrlen == 0)
1916 	 * Spec says nothing in sections for RA, RS and NA.  There's small
1917 	 * description on it in NS section (RFC 2461 7.2.3).
1918 	 */
1919 	flags = lladdr ? LLE_EXCLUSIVE : 0;
1920 	IF_AFDATA_RLOCK(ifp);
1921 	ln = nd6_lookup(from, flags, ifp);
1922 	IF_AFDATA_RUNLOCK(ifp);
1923 	is_newentry = 0;
1924 	if (ln == NULL) {
1925 		flags |= LLE_EXCLUSIVE;
1926 		ln = nd6_alloc(from, 0, ifp);
1927 		if (ln == NULL)
1928 			return;
1929 
1930 		/*
1931 		 * Since we already know all the data for the new entry,
1932 		 * fill it before insertion.
1933 		 */
1934 		if (lladdr != NULL) {
1935 			linkhdrsize = sizeof(linkhdr);
1936 			if (lltable_calc_llheader(ifp, AF_INET6, lladdr,
1937 			    linkhdr, &linkhdrsize, &lladdr_off) != 0)
1938 				return;
1939 			lltable_set_entry_addr(ifp, ln, linkhdr, linkhdrsize,
1940 			    lladdr_off);
1941 		}
1942 
1943 		IF_AFDATA_WLOCK(ifp);
1944 		LLE_WLOCK(ln);
1945 		/* Prefer any existing lle over newly-created one */
1946 		ln_tmp = nd6_lookup(from, LLE_EXCLUSIVE, ifp);
1947 		if (ln_tmp == NULL)
1948 			lltable_link_entry(LLTABLE6(ifp), ln);
1949 		IF_AFDATA_WUNLOCK(ifp);
1950 		if (ln_tmp == NULL) {
1951 			/* No existing lle, mark as new entry (6,7) */
1952 			is_newentry = 1;
1953 			nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
1954 			if (lladdr != NULL)	/* (7) */
1955 				EVENTHANDLER_INVOKE(lle_event, ln,
1956 				    LLENTRY_RESOLVED);
1957 		} else {
1958 			lltable_free_entry(LLTABLE6(ifp), ln);
1959 			ln = ln_tmp;
1960 			ln_tmp = NULL;
1961 		}
1962 	}
1963 	/* do nothing if static ndp is set */
1964 	if ((ln->la_flags & LLE_STATIC)) {
1965 		if (flags & LLE_EXCLUSIVE)
1966 			LLE_WUNLOCK(ln);
1967 		else
1968 			LLE_RUNLOCK(ln);
1969 		return;
1970 	}
1971 
1972 	olladdr = (ln->la_flags & LLE_VALID) ? 1 : 0;
1973 	if (olladdr && lladdr) {
1974 		llchange = bcmp(lladdr, ln->ll_addr,
1975 		    ifp->if_addrlen);
1976 	} else if (!olladdr && lladdr)
1977 		llchange = 1;
1978 	else
1979 		llchange = 0;
1980 
1981 	/*
1982 	 * newentry olladdr  lladdr  llchange	(*=record)
1983 	 *	0	n	n	--	(1)
1984 	 *	0	y	n	--	(2)
1985 	 *	0	n	y	y	(3) * STALE
1986 	 *	0	y	y	n	(4) *
1987 	 *	0	y	y	y	(5) * STALE
1988 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
1989 	 *	1	--	y	--	(7) * STALE
1990 	 */
1991 
1992 	do_update = 0;
1993 	if (is_newentry == 0 && llchange != 0) {
1994 		do_update = 1;	/* (3,5) */
1995 
1996 		/*
1997 		 * Record source link-layer address
1998 		 * XXX is it dependent to ifp->if_type?
1999 		 */
2000 		linkhdrsize = sizeof(linkhdr);
2001 		if (lltable_calc_llheader(ifp, AF_INET6, lladdr,
2002 		    linkhdr, &linkhdrsize, &lladdr_off) != 0)
2003 			return;
2004 
2005 		if (lltable_try_set_entry_addr(ifp, ln, linkhdr, linkhdrsize,
2006 		    lladdr_off) == 0) {
2007 			/* Entry was deleted */
2008 			return;
2009 		}
2010 
2011 		nd6_llinfo_setstate(ln, ND6_LLINFO_STALE);
2012 
2013 		EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
2014 
2015 		if (ln->la_hold != NULL)
2016 			nd6_grab_holdchain(ln, &chain, &sin6);
2017 	}
2018 
2019 	/* Calculates new router status */
2020 	router = nd6_is_router(type, code, is_newentry, olladdr,
2021 	    lladdr != NULL ? 1 : 0, ln->ln_router);
2022 
2023 	ln->ln_router = router;
2024 	/* Mark non-router redirects with special flag */
2025 	if ((type & 0xFF) == ND_REDIRECT && code != ND_REDIRECT_ROUTER)
2026 		ln->la_flags |= LLE_REDIRECT;
2027 
2028 	if (flags & LLE_EXCLUSIVE)
2029 		LLE_WUNLOCK(ln);
2030 	else
2031 		LLE_RUNLOCK(ln);
2032 
2033 	if (chain != NULL)
2034 		nd6_flush_holdchain(ifp, ifp, chain, &sin6);
2035 
2036 	/*
2037 	 * When the link-layer address of a router changes, select the
2038 	 * best router again.  In particular, when the neighbor entry is newly
2039 	 * created, it might affect the selection policy.
2040 	 * Question: can we restrict the first condition to the "is_newentry"
2041 	 * case?
2042 	 * XXX: when we hear an RA from a new router with the link-layer
2043 	 * address option, defrouter_select() is called twice, since
2044 	 * defrtrlist_update called the function as well.  However, I believe
2045 	 * we can compromise the overhead, since it only happens the first
2046 	 * time.
2047 	 * XXX: although defrouter_select() should not have a bad effect
2048 	 * for those are not autoconfigured hosts, we explicitly avoid such
2049 	 * cases for safety.
2050 	 */
2051 	if ((do_update || is_newentry) && router &&
2052 	    ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV) {
2053 		/*
2054 		 * guaranteed recursion
2055 		 */
2056 		defrouter_select();
2057 	}
2058 }
2059 
2060 static void
2061 nd6_slowtimo(void *arg)
2062 {
2063 	CURVNET_SET((struct vnet *) arg);
2064 	struct nd_ifinfo *nd6if;
2065 	struct ifnet *ifp;
2066 
2067 	callout_reset(&V_nd6_slowtimo_ch, ND6_SLOWTIMER_INTERVAL * hz,
2068 	    nd6_slowtimo, curvnet);
2069 	IFNET_RLOCK_NOSLEEP();
2070 	TAILQ_FOREACH(ifp, &V_ifnet, if_link) {
2071 		if (ifp->if_afdata[AF_INET6] == NULL)
2072 			continue;
2073 		nd6if = ND_IFINFO(ifp);
2074 		if (nd6if->basereachable && /* already initialized */
2075 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
2076 			/*
2077 			 * Since reachable time rarely changes by router
2078 			 * advertisements, we SHOULD insure that a new random
2079 			 * value gets recomputed at least once every few hours.
2080 			 * (RFC 2461, 6.3.4)
2081 			 */
2082 			nd6if->recalctm = V_nd6_recalc_reachtm_interval;
2083 			nd6if->reachable = ND_COMPUTE_RTIME(nd6if->basereachable);
2084 		}
2085 	}
2086 	IFNET_RUNLOCK_NOSLEEP();
2087 	CURVNET_RESTORE();
2088 }
2089 
2090 void
2091 nd6_grab_holdchain(struct llentry *ln, struct mbuf **chain,
2092     struct sockaddr_in6 *sin6)
2093 {
2094 
2095 	LLE_WLOCK_ASSERT(ln);
2096 
2097 	*chain = ln->la_hold;
2098 	ln->la_hold = NULL;
2099 	lltable_fill_sa_entry(ln, (struct sockaddr *)sin6);
2100 
2101 	if (ln->ln_state == ND6_LLINFO_STALE) {
2102 
2103 		/*
2104 		 * The first time we send a packet to a
2105 		 * neighbor whose entry is STALE, we have
2106 		 * to change the state to DELAY and a sets
2107 		 * a timer to expire in DELAY_FIRST_PROBE_TIME
2108 		 * seconds to ensure do neighbor unreachability
2109 		 * detection on expiration.
2110 		 * (RFC 2461 7.3.3)
2111 		 */
2112 		nd6_llinfo_setstate(ln, ND6_LLINFO_DELAY);
2113 	}
2114 }
2115 
2116 int
2117 nd6_output_ifp(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m,
2118     struct sockaddr_in6 *dst, struct route *ro)
2119 {
2120 	int error;
2121 	int ip6len;
2122 	struct ip6_hdr *ip6;
2123 	struct m_tag *mtag;
2124 
2125 #ifdef MAC
2126 	mac_netinet6_nd6_send(ifp, m);
2127 #endif
2128 
2129 	/*
2130 	 * If called from nd6_ns_output() (NS), nd6_na_output() (NA),
2131 	 * icmp6_redirect_output() (REDIRECT) or from rip6_output() (RS, RA
2132 	 * as handled by rtsol and rtadvd), mbufs will be tagged for SeND
2133 	 * to be diverted to user space.  When re-injected into the kernel,
2134 	 * send_output() will directly dispatch them to the outgoing interface.
2135 	 */
2136 	if (send_sendso_input_hook != NULL) {
2137 		mtag = m_tag_find(m, PACKET_TAG_ND_OUTGOING, NULL);
2138 		if (mtag != NULL) {
2139 			ip6 = mtod(m, struct ip6_hdr *);
2140 			ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
2141 			/* Use the SEND socket */
2142 			error = send_sendso_input_hook(m, ifp, SND_OUT,
2143 			    ip6len);
2144 			/* -1 == no app on SEND socket */
2145 			if (error == 0 || error != -1)
2146 			    return (error);
2147 		}
2148 	}
2149 
2150 	m_clrprotoflags(m);	/* Avoid confusing lower layers. */
2151 	IP_PROBE(send, NULL, NULL, mtod(m, struct ip6_hdr *), ifp, NULL,
2152 	    mtod(m, struct ip6_hdr *));
2153 
2154 	if ((ifp->if_flags & IFF_LOOPBACK) == 0)
2155 		origifp = ifp;
2156 
2157 	error = (*ifp->if_output)(origifp, m, (struct sockaddr *)dst, ro);
2158 	return (error);
2159 }
2160 
2161 /*
2162  * Lookup link headerfor @sa_dst address. Stores found
2163  * data in @desten buffer. Copy of lle ln_flags can be also
2164  * saved in @pflags if @pflags is non-NULL.
2165  *
2166  * If destination LLE does not exists or lle state modification
2167  * is required, call "slow" version.
2168  *
2169  * Return values:
2170  * - 0 on success (address copied to buffer).
2171  * - EWOULDBLOCK (no local error, but address is still unresolved)
2172  * - other errors (alloc failure, etc)
2173  */
2174 int
2175 nd6_resolve(struct ifnet *ifp, int is_gw, struct mbuf *m,
2176     const struct sockaddr *sa_dst, u_char *desten, uint32_t *pflags)
2177 {
2178 	struct llentry *ln = NULL;
2179 	const struct sockaddr_in6 *dst6;
2180 
2181 	if (pflags != NULL)
2182 		*pflags = 0;
2183 
2184 	dst6 = (const struct sockaddr_in6 *)sa_dst;
2185 
2186 	/* discard the packet if IPv6 operation is disabled on the interface */
2187 	if ((ND_IFINFO(ifp)->flags & ND6_IFF_IFDISABLED)) {
2188 		m_freem(m);
2189 		return (ENETDOWN); /* better error? */
2190 	}
2191 
2192 	if (m != NULL && m->m_flags & M_MCAST) {
2193 		switch (ifp->if_type) {
2194 		case IFT_ETHER:
2195 		case IFT_FDDI:
2196 		case IFT_L2VLAN:
2197 		case IFT_IEEE80211:
2198 		case IFT_BRIDGE:
2199 		case IFT_ISO88025:
2200 			ETHER_MAP_IPV6_MULTICAST(&dst6->sin6_addr,
2201 						 desten);
2202 			return (0);
2203 		default:
2204 			m_freem(m);
2205 			return (EAFNOSUPPORT);
2206 		}
2207 	}
2208 
2209 	IF_AFDATA_RLOCK(ifp);
2210 	ln = nd6_lookup(&dst6->sin6_addr, LLE_UNLOCKED, ifp);
2211 	if (ln != NULL && (ln->r_flags & RLLE_VALID) != 0) {
2212 		/* Entry found, let's copy lle info */
2213 		bcopy(ln->r_linkdata, desten, ln->r_hdrlen);
2214 		if (pflags != NULL)
2215 			*pflags = LLE_VALID | (ln->r_flags & RLLE_IFADDR);
2216 		/* Check if we have feedback request from nd6 timer */
2217 		if (ln->r_skip_req != 0) {
2218 			LLE_REQ_LOCK(ln);
2219 			ln->r_skip_req = 0; /* Notify that entry was used */
2220 			ln->lle_hittime = time_uptime;
2221 			LLE_REQ_UNLOCK(ln);
2222 		}
2223 		IF_AFDATA_RUNLOCK(ifp);
2224 		return (0);
2225 	}
2226 	IF_AFDATA_RUNLOCK(ifp);
2227 
2228 	return (nd6_resolve_slow(ifp, 0, m, dst6, desten, pflags));
2229 }
2230 
2231 
2232 /*
2233  * Do L2 address resolution for @sa_dst address. Stores found
2234  * address in @desten buffer. Copy of lle ln_flags can be also
2235  * saved in @pflags if @pflags is non-NULL.
2236  *
2237  * Heavy version.
2238  * Function assume that destination LLE does not exist,
2239  * is invalid or stale, so LLE_EXCLUSIVE lock needs to be acquired.
2240  *
2241  * Set noinline to be dtrace-friendly
2242  */
2243 static __noinline int
2244 nd6_resolve_slow(struct ifnet *ifp, int flags, struct mbuf *m,
2245     const struct sockaddr_in6 *dst, u_char *desten, uint32_t *pflags)
2246 {
2247 	struct llentry *lle = NULL, *lle_tmp;
2248 	struct in6_addr *psrc, src;
2249 	int send_ns, ll_len;
2250 	char *lladdr;
2251 
2252 	/*
2253 	 * Address resolution or Neighbor Unreachability Detection
2254 	 * for the next hop.
2255 	 * At this point, the destination of the packet must be a unicast
2256 	 * or an anycast address(i.e. not a multicast).
2257 	 */
2258 	if (lle == NULL) {
2259 		IF_AFDATA_RLOCK(ifp);
2260 		lle = nd6_lookup(&dst->sin6_addr, LLE_EXCLUSIVE, ifp);
2261 		IF_AFDATA_RUNLOCK(ifp);
2262 		if ((lle == NULL) && nd6_is_addr_neighbor(dst, ifp))  {
2263 			/*
2264 			 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
2265 			 * the condition below is not very efficient.  But we believe
2266 			 * it is tolerable, because this should be a rare case.
2267 			 */
2268 			lle = nd6_alloc(&dst->sin6_addr, 0, ifp);
2269 			if (lle == NULL) {
2270 				char ip6buf[INET6_ADDRSTRLEN];
2271 				log(LOG_DEBUG,
2272 				    "nd6_output: can't allocate llinfo for %s "
2273 				    "(ln=%p)\n",
2274 				    ip6_sprintf(ip6buf, &dst->sin6_addr), lle);
2275 				m_freem(m);
2276 				return (ENOBUFS);
2277 			}
2278 
2279 			IF_AFDATA_WLOCK(ifp);
2280 			LLE_WLOCK(lle);
2281 			/* Prefer any existing entry over newly-created one */
2282 			lle_tmp = nd6_lookup(&dst->sin6_addr, LLE_EXCLUSIVE, ifp);
2283 			if (lle_tmp == NULL)
2284 				lltable_link_entry(LLTABLE6(ifp), lle);
2285 			IF_AFDATA_WUNLOCK(ifp);
2286 			if (lle_tmp != NULL) {
2287 				lltable_free_entry(LLTABLE6(ifp), lle);
2288 				lle = lle_tmp;
2289 				lle_tmp = NULL;
2290 			}
2291 		}
2292 	}
2293 	if (lle == NULL) {
2294 		if (!(ND_IFINFO(ifp)->flags & ND6_IFF_PERFORMNUD)) {
2295 			m_freem(m);
2296 			return (ENOBUFS);
2297 		}
2298 
2299 		if (m != NULL)
2300 			m_freem(m);
2301 		return (ENOBUFS);
2302 	}
2303 
2304 	LLE_WLOCK_ASSERT(lle);
2305 
2306 	/*
2307 	 * The first time we send a packet to a neighbor whose entry is
2308 	 * STALE, we have to change the state to DELAY and a sets a timer to
2309 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
2310 	 * neighbor unreachability detection on expiration.
2311 	 * (RFC 2461 7.3.3)
2312 	 */
2313 	if (lle->ln_state == ND6_LLINFO_STALE)
2314 		nd6_llinfo_setstate(lle, ND6_LLINFO_DELAY);
2315 
2316 	/*
2317 	 * If the neighbor cache entry has a state other than INCOMPLETE
2318 	 * (i.e. its link-layer address is already resolved), just
2319 	 * send the packet.
2320 	 */
2321 	if (lle->ln_state > ND6_LLINFO_INCOMPLETE) {
2322 		if (flags & LLE_ADDRONLY) {
2323 			lladdr = lle->ll_addr;
2324 			ll_len = ifp->if_addrlen;
2325 		} else {
2326 			lladdr = lle->r_linkdata;
2327 			ll_len = lle->r_hdrlen;
2328 		}
2329 		bcopy(lladdr, desten, ll_len);
2330 		if (pflags != NULL)
2331 			*pflags = lle->la_flags;
2332 		LLE_WUNLOCK(lle);
2333 		return (0);
2334 	}
2335 
2336 	/*
2337 	 * There is a neighbor cache entry, but no ethernet address
2338 	 * response yet.  Append this latest packet to the end of the
2339 	 * packet queue in the mbuf.  When it exceeds nd6_maxqueuelen,
2340 	 * the oldest packet in the queue will be removed.
2341 	 */
2342 
2343 	if (lle->la_hold != NULL) {
2344 		struct mbuf *m_hold;
2345 		int i;
2346 
2347 		i = 0;
2348 		for (m_hold = lle->la_hold; m_hold; m_hold = m_hold->m_nextpkt){
2349 			i++;
2350 			if (m_hold->m_nextpkt == NULL) {
2351 				m_hold->m_nextpkt = m;
2352 				break;
2353 			}
2354 		}
2355 		while (i >= V_nd6_maxqueuelen) {
2356 			m_hold = lle->la_hold;
2357 			lle->la_hold = lle->la_hold->m_nextpkt;
2358 			m_freem(m_hold);
2359 			i--;
2360 		}
2361 	} else {
2362 		lle->la_hold = m;
2363 	}
2364 
2365 	/*
2366 	 * If there has been no NS for the neighbor after entering the
2367 	 * INCOMPLETE state, send the first solicitation.
2368 	 * Note that for newly-created lle la_asked will be 0,
2369 	 * so we will transition from ND6_LLINFO_NOSTATE to
2370 	 * ND6_LLINFO_INCOMPLETE state here.
2371 	 */
2372 	psrc = NULL;
2373 	send_ns = 0;
2374 	if (lle->la_asked == 0) {
2375 		lle->la_asked++;
2376 		send_ns = 1;
2377 		psrc = nd6_llinfo_get_holdsrc(lle, &src);
2378 
2379 		nd6_llinfo_setstate(lle, ND6_LLINFO_INCOMPLETE);
2380 	}
2381 	LLE_WUNLOCK(lle);
2382 	if (send_ns != 0)
2383 		nd6_ns_output(ifp, psrc, NULL, &dst->sin6_addr, NULL);
2384 
2385 	return (EWOULDBLOCK);
2386 }
2387 
2388 /*
2389  * Do L2 address resolution for @sa_dst address. Stores found
2390  * address in @desten buffer. Copy of lle ln_flags can be also
2391  * saved in @pflags if @pflags is non-NULL.
2392  *
2393  * Return values:
2394  * - 0 on success (address copied to buffer).
2395  * - EWOULDBLOCK (no local error, but address is still unresolved)
2396  * - other errors (alloc failure, etc)
2397  */
2398 int
2399 nd6_resolve_addr(struct ifnet *ifp, int flags, const struct sockaddr *dst,
2400     char *desten, uint32_t *pflags)
2401 {
2402 	int error;
2403 
2404 	flags |= LLE_ADDRONLY;
2405 	error = nd6_resolve_slow(ifp, flags, NULL,
2406 	    (const struct sockaddr_in6 *)dst, desten, pflags);
2407 	return (error);
2408 }
2409 
2410 int
2411 nd6_flush_holdchain(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *chain,
2412     struct sockaddr_in6 *dst)
2413 {
2414 	struct mbuf *m, *m_head;
2415 	struct ifnet *outifp;
2416 	int error = 0;
2417 
2418 	m_head = chain;
2419 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2420 		outifp = origifp;
2421 	else
2422 		outifp = ifp;
2423 
2424 	while (m_head) {
2425 		m = m_head;
2426 		m_head = m_head->m_nextpkt;
2427 		error = nd6_output_ifp(ifp, origifp, m, dst, NULL);
2428 	}
2429 
2430 	/*
2431 	 * XXX
2432 	 * note that intermediate errors are blindly ignored
2433 	 */
2434 	return (error);
2435 }
2436 
2437 static int
2438 nd6_need_cache(struct ifnet *ifp)
2439 {
2440 	/*
2441 	 * XXX: we currently do not make neighbor cache on any interface
2442 	 * other than ARCnet, Ethernet, FDDI and GIF.
2443 	 *
2444 	 * RFC2893 says:
2445 	 * - unidirectional tunnels needs no ND
2446 	 */
2447 	switch (ifp->if_type) {
2448 	case IFT_ARCNET:
2449 	case IFT_ETHER:
2450 	case IFT_FDDI:
2451 	case IFT_IEEE1394:
2452 	case IFT_L2VLAN:
2453 	case IFT_IEEE80211:
2454 	case IFT_INFINIBAND:
2455 	case IFT_BRIDGE:
2456 	case IFT_PROPVIRTUAL:
2457 		return (1);
2458 	default:
2459 		return (0);
2460 	}
2461 }
2462 
2463 /*
2464  * Add pernament ND6 link-layer record for given
2465  * interface address.
2466  *
2467  * Very similar to IPv4 arp_ifinit(), but:
2468  * 1) IPv6 DAD is performed in different place
2469  * 2) It is called by IPv6 protocol stack in contrast to
2470  * arp_ifinit() which is typically called in SIOCSIFADDR
2471  * driver ioctl handler.
2472  *
2473  */
2474 int
2475 nd6_add_ifa_lle(struct in6_ifaddr *ia)
2476 {
2477 	struct ifnet *ifp;
2478 	struct llentry *ln, *ln_tmp;
2479 	struct sockaddr *dst;
2480 
2481 	ifp = ia->ia_ifa.ifa_ifp;
2482 	if (nd6_need_cache(ifp) == 0)
2483 		return (0);
2484 
2485 	ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
2486 	dst = (struct sockaddr *)&ia->ia_addr;
2487 	ln = lltable_alloc_entry(LLTABLE6(ifp), LLE_IFADDR, dst);
2488 	if (ln == NULL)
2489 		return (ENOBUFS);
2490 
2491 	IF_AFDATA_WLOCK(ifp);
2492 	LLE_WLOCK(ln);
2493 	/* Unlink any entry if exists */
2494 	ln_tmp = lla_lookup(LLTABLE6(ifp), LLE_EXCLUSIVE, dst);
2495 	if (ln_tmp != NULL)
2496 		lltable_unlink_entry(LLTABLE6(ifp), ln_tmp);
2497 	lltable_link_entry(LLTABLE6(ifp), ln);
2498 	IF_AFDATA_WUNLOCK(ifp);
2499 
2500 	if (ln_tmp != NULL)
2501 		EVENTHANDLER_INVOKE(lle_event, ln_tmp, LLENTRY_EXPIRED);
2502 	EVENTHANDLER_INVOKE(lle_event, ln, LLENTRY_RESOLVED);
2503 
2504 	LLE_WUNLOCK(ln);
2505 	if (ln_tmp != NULL)
2506 		llentry_free(ln_tmp);
2507 
2508 	return (0);
2509 }
2510 
2511 /*
2512  * Removes either all lle entries for given @ia, or lle
2513  * corresponding to @ia address.
2514  */
2515 void
2516 nd6_rem_ifa_lle(struct in6_ifaddr *ia, int all)
2517 {
2518 	struct sockaddr_in6 mask, addr;
2519 	struct sockaddr *saddr, *smask;
2520 	struct ifnet *ifp;
2521 
2522 	ifp = ia->ia_ifa.ifa_ifp;
2523 	memcpy(&addr, &ia->ia_addr, sizeof(ia->ia_addr));
2524 	memcpy(&mask, &ia->ia_prefixmask, sizeof(ia->ia_prefixmask));
2525 	saddr = (struct sockaddr *)&addr;
2526 	smask = (struct sockaddr *)&mask;
2527 
2528 	if (all != 0)
2529 		lltable_prefix_free(AF_INET6, saddr, smask, LLE_STATIC);
2530 	else
2531 		lltable_delete_addr(LLTABLE6(ifp), LLE_IFADDR, saddr);
2532 }
2533 
2534 static void
2535 clear_llinfo_pqueue(struct llentry *ln)
2536 {
2537 	struct mbuf *m_hold, *m_hold_next;
2538 
2539 	for (m_hold = ln->la_hold; m_hold; m_hold = m_hold_next) {
2540 		m_hold_next = m_hold->m_nextpkt;
2541 		m_freem(m_hold);
2542 	}
2543 
2544 	ln->la_hold = NULL;
2545 }
2546 
2547 static int nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS);
2548 static int nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS);
2549 #ifdef SYSCTL_DECL
2550 SYSCTL_DECL(_net_inet6_icmp6);
2551 #endif
2552 SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2553 	CTLFLAG_RD, nd6_sysctl_drlist, "");
2554 SYSCTL_NODE(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
2555 	CTLFLAG_RD, nd6_sysctl_prlist, "");
2556 SYSCTL_INT(_net_inet6_icmp6, ICMPV6CTL_ND6_MAXQLEN, nd6_maxqueuelen,
2557 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_maxqueuelen), 1, "");
2558 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, nd6_gctimer,
2559 	CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(nd6_gctimer), (60 * 60 * 24), "");
2560 
2561 static int
2562 nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2563 {
2564 	struct in6_defrouter d;
2565 	struct nd_defrouter *dr;
2566 	int error;
2567 
2568 	if (req->newptr != NULL)
2569 		return (EPERM);
2570 
2571 	error = sysctl_wire_old_buffer(req, 0);
2572 	if (error != 0)
2573 		return (error);
2574 
2575 	bzero(&d, sizeof(d));
2576 	d.rtaddr.sin6_family = AF_INET6;
2577 	d.rtaddr.sin6_len = sizeof(d.rtaddr);
2578 
2579 	ND6_RLOCK();
2580 	TAILQ_FOREACH(dr, &V_nd_defrouter, dr_entry) {
2581 		d.rtaddr.sin6_addr = dr->rtaddr;
2582 		error = sa6_recoverscope(&d.rtaddr);
2583 		if (error != 0)
2584 			break;
2585 		d.flags = dr->raflags;
2586 		d.rtlifetime = dr->rtlifetime;
2587 		d.expire = dr->expire + (time_second - time_uptime);
2588 		d.if_index = dr->ifp->if_index;
2589 		error = SYSCTL_OUT(req, &d, sizeof(d));
2590 		if (error != 0)
2591 			break;
2592 	}
2593 	ND6_RUNLOCK();
2594 	return (error);
2595 }
2596 
2597 static int
2598 nd6_sysctl_prlist(SYSCTL_HANDLER_ARGS)
2599 {
2600 	struct in6_prefix p;
2601 	struct sockaddr_in6 s6;
2602 	struct nd_prefix *pr;
2603 	struct nd_pfxrouter *pfr;
2604 	time_t maxexpire;
2605 	int error;
2606 	char ip6buf[INET6_ADDRSTRLEN];
2607 
2608 	if (req->newptr)
2609 		return (EPERM);
2610 
2611 	bzero(&p, sizeof(p));
2612 	p.origin = PR_ORIG_RA;
2613 	bzero(&s6, sizeof(s6));
2614 	s6.sin6_family = AF_INET6;
2615 	s6.sin6_len = sizeof(s6);
2616 
2617 	/*
2618 	 * XXX locking
2619 	 */
2620 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
2621 		p.prefix = pr->ndpr_prefix;
2622 		if (sa6_recoverscope(&p.prefix)) {
2623 			log(LOG_ERR, "scope error in prefix list (%s)\n",
2624 			    ip6_sprintf(ip6buf, &p.prefix.sin6_addr));
2625 			/* XXX: press on... */
2626 		}
2627 		p.raflags = pr->ndpr_raf;
2628 		p.prefixlen = pr->ndpr_plen;
2629 		p.vltime = pr->ndpr_vltime;
2630 		p.pltime = pr->ndpr_pltime;
2631 		p.if_index = pr->ndpr_ifp->if_index;
2632 		if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME)
2633 			p.expire = 0;
2634 		else {
2635 			/* XXX: we assume time_t is signed. */
2636 			maxexpire = (-1) &
2637 			    ~((time_t)1 << ((sizeof(maxexpire) * 8) - 1));
2638 			if (pr->ndpr_vltime < maxexpire - pr->ndpr_lastupdate)
2639 				p.expire = pr->ndpr_lastupdate +
2640 				    pr->ndpr_vltime +
2641 				    (time_second - time_uptime);
2642 			else
2643 				p.expire = maxexpire;
2644 		}
2645 		p.refcnt = pr->ndpr_refcnt;
2646 		p.flags = pr->ndpr_stateflags;
2647 		p.advrtrs = 0;
2648 		LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
2649 			p.advrtrs++;
2650 		error = SYSCTL_OUT(req, &p, sizeof(p));
2651 		if (error != 0)
2652 			return (error);
2653 		LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
2654 			s6.sin6_addr = pfr->router->rtaddr;
2655 			if (sa6_recoverscope(&s6))
2656 				log(LOG_ERR,
2657 				    "scope error in prefix list (%s)\n",
2658 				    ip6_sprintf(ip6buf, &pfr->router->rtaddr));
2659 			error = SYSCTL_OUT(req, &s6, sizeof(s6));
2660 			if (error != 0)
2661 				return (error);
2662 		}
2663 	}
2664 	return (0);
2665 }
2666