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