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