xref: /xnu-11215.41.3/bsd/netinet6/nd6.c (revision 33de042d024d46de5ff4e89f2471de6608e37fa4)
1 /*
2  * Copyright (c) 2000-2023 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*
30  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the project nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 
58 /*
59  * XXX
60  * KAME 970409 note:
61  * BSD/OS version heavily modifies this code, related to llinfo.
62  * Since we don't have BSD/OS version of net/route.c in our hand,
63  * I left the code mostly as it was in 970310.  -- itojun
64  */
65 
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/malloc.h>
69 #include <sys/mbuf.h>
70 #include <sys/socket.h>
71 #include <sys/sockio.h>
72 #include <sys/time.h>
73 #include <sys/kernel.h>
74 #include <sys/sysctl.h>
75 #include <sys/errno.h>
76 #include <sys/syslog.h>
77 #include <sys/protosw.h>
78 #include <sys/proc.h>
79 #include <sys/mcache.h>
80 
81 #include <dev/random/randomdev.h>
82 
83 #include <kern/queue.h>
84 #include <kern/zalloc.h>
85 
86 #include <net/if.h>
87 #include <net/if_dl.h>
88 #include <net/if_types.h>
89 #include <net/if_llreach.h>
90 #include <net/route.h>
91 #include <net/dlil.h>
92 #include <net/ntstat.h>
93 #include <net/net_osdep.h>
94 #include <net/nwk_wq.h>
95 
96 #include <netinet/in.h>
97 #include <netinet/in_arp.h>
98 #include <netinet/if_ether.h>
99 #include <netinet6/in6_var.h>
100 #include <netinet/ip6.h>
101 #include <netinet6/ip6_var.h>
102 #include <netinet6/nd6.h>
103 #include <netinet6/scope6_var.h>
104 #include <netinet/icmp6.h>
105 
106 #include <net/sockaddr_utils.h>
107 
108 #include <os/log.h>
109 
110 #include "loop.h"
111 
112 #define ND6_SLOWTIMER_INTERVAL          (60 * 60)       /* 1 hour */
113 #define ND6_RECALC_REACHTM_INTERVAL     (60 * 120)      /* 2 hours */
114 
115 /* timer values */
116 int     nd6_prune       = 1;    /* walk list every 1 seconds */
117 int     nd6_prune_lazy  = 5;    /* lazily walk list every 5 seconds */
118 int     nd6_delay       = 5;    /* delay first probe time 5 second */
119 int     nd6_umaxtries   = 3;    /* maximum unicast query */
120 int     nd6_mmaxtries   = 3;    /* maximum multicast query */
121 int     nd6_useloopback = 1;    /* use loopback interface for local traffic */
122 int     nd6_gctimer     = (60 * 60 * 24); /* 1 day: garbage collection timer */
123 
124 /* preventing too many loops in ND option parsing */
125 int nd6_maxndopt = 10;  /* max # of ND options allowed */
126 
127 int nd6_maxqueuelen = 1; /* max # of packets cached in unresolved ND entries */
128 
129 #if ND6_DEBUG
130 int nd6_debug = 1;
131 #else
132 int nd6_debug = 0;
133 #endif
134 
135 int nd6_optimistic_dad = ND6_OPTIMISTIC_DAD_DEFAULT;
136 
137 /* for debugging? */
138 static int nd6_inuse, nd6_allocated;
139 
140 /*
141  * Synchronization notes:
142  *
143  * The global list of ND entries are stored in llinfo_nd6; an entry
144  * gets inserted into the list when the route is created and gets
145  * removed from the list when it is deleted; this is done as part
146  * of RTM_ADD/RTM_RESOLVE/RTM_DELETE in nd6_rtrequest().
147  *
148  * Because rnh_lock and rt_lock for the entry are held during those
149  * operations, the same locks (and thus lock ordering) must be used
150  * elsewhere to access the relevant data structure fields:
151  *
152  * ln_next, ln_prev, ln_rt
153  *
154  *	- Routing lock (rnh_lock)
155  *
156  * ln_hold, ln_asked, ln_expire, ln_state, ln_router, ln_flags,
157  * ln_llreach, ln_lastused
158  *
159  *	- Routing entry lock (rt_lock)
160  *
161  * Due to the dependency on rt_lock, llinfo_nd6 has the same lifetime
162  * as the route entry itself.  When a route is deleted (RTM_DELETE),
163  * it is simply removed from the global list but the memory is not
164  * freed until the route itself is freed.
165  */
166 struct llinfo_nd6 llinfo_nd6 = {
167 	.ln_next = &llinfo_nd6,
168 	.ln_prev = &llinfo_nd6,
169 };
170 
171 static LCK_GRP_DECLARE(nd_if_lock_grp, "nd_if_lock");
172 static LCK_ATTR_DECLARE(nd_if_lock_attr, 0, 0);
173 
174 /* Protected by nd6_mutex */
175 struct nd_drhead nd_defrouter_list;
176 struct nd_prhead nd_prefix = { .lh_first = 0 };
177 struct nd_rtihead nd_rti_list;
178 /*
179  * nd6_timeout() is scheduled on a demand basis.  nd6_timeout_run is used
180  * to indicate whether or not a timeout has been scheduled.  The rnh_lock
181  * mutex is used to protect this scheduling; it is a natural choice given
182  * the work done in the timer callback.  Unfortunately, there are cases
183  * when nd6_timeout() needs to be scheduled while rnh_lock cannot be easily
184  * held, due to lock ordering.  In those cases, we utilize a "demand" counter
185  * nd6_sched_timeout_want which can be atomically incremented without
186  * having to hold rnh_lock.  On places where we acquire rnh_lock, such as
187  * nd6_rtrequest(), we check this counter and schedule the timer if it is
188  * non-zero.  The increment happens on various places when we allocate
189  * new ND entries, default routers, prefixes and addresses.
190  */
191 static int nd6_timeout_run;             /* nd6_timeout is scheduled to run */
192 static void nd6_timeout(void *);
193 int nd6_sched_timeout_want;             /* demand count for timer to be sched */
194 static boolean_t nd6_fast_timer_on = FALSE;
195 
196 /* Serialization variables for nd6_service(), protected by rnh_lock */
197 static boolean_t nd6_service_busy;
198 static void *nd6_service_wc = &nd6_service_busy;
199 static int nd6_service_waiters = 0;
200 
201 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
202 static struct sockaddr_in6 all1_sa;
203 
204 static int regen_tmpaddr(struct in6_ifaddr *);
205 
206 static struct llinfo_nd6 *nd6_llinfo_alloc(zalloc_flags_t);
207 static void nd6_llinfo_free(void *);
208 static void nd6_llinfo_purge(struct rtentry *);
209 static void nd6_llinfo_get_ri(struct rtentry *, struct rt_reach_info *);
210 static void nd6_llinfo_get_iflri(struct rtentry *, struct ifnet_llreach_info *);
211 static void nd6_llinfo_refresh(struct rtentry *);
212 static uint64_t ln_getexpire(struct llinfo_nd6 *);
213 
214 static void nd6_service(void *);
215 static void nd6_slowtimo(void *);
216 static int nd6_is_new_addr_neighbor(struct sockaddr_in6 *, struct ifnet *);
217 
218 static void nd6_router_select_rti_entries(struct ifnet *);
219 static void nd6_purge_interface_default_routers(struct ifnet *);
220 static void nd6_purge_interface_rti_entries(struct ifnet *);
221 static void nd6_purge_interface_prefixes(struct ifnet *);
222 static void nd6_purge_interface_llinfo(struct ifnet *);
223 
224 static int nd6_sysctl_drlist SYSCTL_HANDLER_ARGS;
225 static int nd6_sysctl_prlist SYSCTL_HANDLER_ARGS;
226 
227 /*
228  * Insertion and removal from llinfo_nd6 must be done with rnh_lock held.
229  */
230 #define LN_DEQUEUE(_ln) do {                                            \
231 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);                 \
232 	RT_LOCK_ASSERT_HELD((_ln)->ln_rt);                              \
233 	(_ln)->ln_next->ln_prev = (_ln)->ln_prev;                       \
234 	(_ln)->ln_prev->ln_next = (_ln)->ln_next;                       \
235 	(_ln)->ln_prev = (_ln)->ln_next = NULL;                         \
236 	(_ln)->ln_flags &= ~ND6_LNF_IN_USE;                             \
237 } while (0)
238 
239 #define LN_INSERTHEAD(_ln) do {                                         \
240 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);                 \
241 	RT_LOCK_ASSERT_HELD((_ln)->ln_rt);                              \
242 	(_ln)->ln_next = llinfo_nd6.ln_next;                            \
243 	llinfo_nd6.ln_next = (_ln);                                     \
244 	(_ln)->ln_prev = &llinfo_nd6;                                   \
245 	(_ln)->ln_next->ln_prev = (_ln);                                \
246 	(_ln)->ln_flags |= ND6_LNF_IN_USE;                              \
247 } while (0)
248 
249 static KALLOC_TYPE_DEFINE(llinfo_nd6_zone, struct llinfo_nd6, NET_KT_DEFAULT);
250 
251 extern int tvtohz(struct timeval *);
252 
253 static int nd6_init_done;
254 
255 SYSCTL_DECL(_net_inet6_icmp6);
256 
257 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
258     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
259     nd6_sysctl_drlist, "S,in6_defrouter", "");
260 
261 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
262     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
263     nd6_sysctl_prlist, "S,in6_defrouter", "");
264 
265 SYSCTL_DECL(_net_inet6_ip6);
266 
267 static int ip6_maxchainsent = 0;
268 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, maxchainsent,
269     CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_maxchainsent, 0,
270     "use dlil_output_list");
271 
272 SYSCTL_DECL(_net_inet6_icmp6);
273 int nd6_process_rti = ND6_PROCESS_RTI_DEFAULT;
274 
275 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, nd6_process_rti, CTLFLAG_RW | CTLFLAG_LOCKED,
276     &nd6_process_rti, 0,
277     "Enable/disable processing of Route Information Option in the "
278     "IPv6 Router Advertisement.");
279 
280 void
nd6_init(void)281 nd6_init(void)
282 {
283 	int i;
284 
285 	VERIFY(!nd6_init_done);
286 
287 	all1_sa.sin6_family = AF_INET6;
288 	all1_sa.sin6_len = sizeof(struct sockaddr_in6);
289 	for (i = 0; i < sizeof(all1_sa.sin6_addr); i++) {
290 		all1_sa.sin6_addr.s6_addr[i] = 0xff;
291 	}
292 
293 	/* initialization of the default router list */
294 	TAILQ_INIT(&nd_defrouter_list);
295 	TAILQ_INIT(&nd_rti_list);
296 
297 	nd6_nbr_init();
298 	nd6_rtr_init();
299 
300 	nd6_init_done = 1;
301 
302 	/* start timer */
303 	timeout(nd6_slowtimo, NULL, ND6_SLOWTIMER_INTERVAL * hz);
304 }
305 
306 static struct llinfo_nd6 *
nd6_llinfo_alloc(zalloc_flags_t how)307 nd6_llinfo_alloc(zalloc_flags_t how)
308 {
309 	return zalloc_flags(llinfo_nd6_zone, how | Z_ZERO);
310 }
311 
312 static void
nd6_llinfo_free(void * arg)313 nd6_llinfo_free(void *arg)
314 {
315 	struct llinfo_nd6 *__single ln = arg;
316 
317 	if (ln->ln_next != NULL || ln->ln_prev != NULL) {
318 		panic("%s: trying to free %p when it is in use", __func__, ln);
319 		/* NOTREACHED */
320 	}
321 
322 	/* Just in case there's anything there, free it */
323 	if (ln->ln_hold != NULL) {
324 		m_freem_list(ln->ln_hold);
325 		ln->ln_hold = NULL;
326 	}
327 
328 	/* Purge any link-layer info caching */
329 	VERIFY(ln->ln_rt->rt_llinfo == ln);
330 	if (ln->ln_rt->rt_llinfo_purge != NULL) {
331 		ln->ln_rt->rt_llinfo_purge(ln->ln_rt);
332 	}
333 
334 	zfree(llinfo_nd6_zone, ln);
335 }
336 
337 static void
nd6_llinfo_purge(struct rtentry * rt)338 nd6_llinfo_purge(struct rtentry *rt)
339 {
340 	struct llinfo_nd6 *__single ln = rt->rt_llinfo;
341 
342 	RT_LOCK_ASSERT_HELD(rt);
343 	VERIFY(rt->rt_llinfo_purge == nd6_llinfo_purge && ln != NULL);
344 
345 	if (ln->ln_llreach != NULL) {
346 		RT_CONVERT_LOCK(rt);
347 		ifnet_llreach_free(ln->ln_llreach);
348 		ln->ln_llreach = NULL;
349 	}
350 	ln->ln_lastused = 0;
351 }
352 
353 static void
nd6_llinfo_get_ri(struct rtentry * rt,struct rt_reach_info * ri)354 nd6_llinfo_get_ri(struct rtentry *rt, struct rt_reach_info *ri)
355 {
356 	struct llinfo_nd6 *__single ln = rt->rt_llinfo;
357 	struct if_llreach *__single lr = ln->ln_llreach;
358 
359 	if (lr == NULL) {
360 		bzero(ri, sizeof(*ri));
361 		ri->ri_rssi = IFNET_RSSI_UNKNOWN;
362 		ri->ri_lqm = IFNET_LQM_THRESH_OFF;
363 		ri->ri_npm = IFNET_NPM_THRESH_UNKNOWN;
364 	} else {
365 		IFLR_LOCK(lr);
366 		/* Export to rt_reach_info structure */
367 		ifnet_lr2ri(lr, ri);
368 		/* Export ND6 send expiration (calendar) time */
369 		ri->ri_snd_expire =
370 		    ifnet_llreach_up2calexp(lr, ln->ln_lastused);
371 		IFLR_UNLOCK(lr);
372 	}
373 }
374 
375 static void
nd6_llinfo_get_iflri(struct rtentry * rt,struct ifnet_llreach_info * iflri)376 nd6_llinfo_get_iflri(struct rtentry *rt, struct ifnet_llreach_info *iflri)
377 {
378 	struct llinfo_nd6 *__single ln = rt->rt_llinfo;
379 	struct if_llreach *__single lr = ln->ln_llreach;
380 
381 	if (lr == NULL) {
382 		bzero(iflri, sizeof(*iflri));
383 		iflri->iflri_rssi = IFNET_RSSI_UNKNOWN;
384 		iflri->iflri_lqm = IFNET_LQM_THRESH_OFF;
385 		iflri->iflri_npm = IFNET_NPM_THRESH_UNKNOWN;
386 	} else {
387 		IFLR_LOCK(lr);
388 		/* Export to ifnet_llreach_info structure */
389 		ifnet_lr2iflri(lr, iflri);
390 		/* Export ND6 send expiration (uptime) time */
391 		iflri->iflri_snd_expire =
392 		    ifnet_llreach_up2upexp(lr, ln->ln_lastused);
393 		IFLR_UNLOCK(lr);
394 	}
395 }
396 
397 static void
nd6_llinfo_refresh(struct rtentry * rt)398 nd6_llinfo_refresh(struct rtentry *rt)
399 {
400 	struct llinfo_nd6 *__single ln = rt->rt_llinfo;
401 	uint64_t timenow = net_uptime();
402 	ifnet_ref_t ifp = rt->rt_ifp;
403 	/*
404 	 * Can't refresh permanent, static or entries that are
405 	 * not direct host entries. Also skip if the entry is for
406 	 * host over an interface that has alternate neighbor cache
407 	 * management mechanisms (AWDL/NAN)
408 	 */
409 	if (!ln || ln->ln_expire == 0 || (rt->rt_flags & RTF_STATIC) ||
410 	    !(rt->rt_flags & RTF_LLINFO) || !ifp ||
411 	    (ifp->if_eflags & IFEF_IPV6_ND6ALT)) {
412 		return;
413 	}
414 
415 	if ((ln->ln_state > ND6_LLINFO_INCOMPLETE) &&
416 	    (ln->ln_state < ND6_LLINFO_PROBE)) {
417 		if (ln->ln_expire > timenow) {
418 			ln_setexpire(ln, timenow);
419 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_PROBE);
420 		}
421 	}
422 	return;
423 }
424 
425 const char *
ndcache_state2str(short ndp_state)426 ndcache_state2str(short ndp_state)
427 {
428 	const char *__null_terminated ndp_state_str = "UNKNOWN";
429 	switch (ndp_state) {
430 	case ND6_LLINFO_PURGE:
431 		ndp_state_str = "ND6_LLINFO_PURGE";
432 		break;
433 	case ND6_LLINFO_NOSTATE:
434 		ndp_state_str = "ND6_LLINFO_NOSTATE";
435 		break;
436 	case ND6_LLINFO_INCOMPLETE:
437 		ndp_state_str = "ND6_LLINFO_INCOMPLETE";
438 		break;
439 	case ND6_LLINFO_REACHABLE:
440 		ndp_state_str = "ND6_LLINFO_REACHABLE";
441 		break;
442 	case ND6_LLINFO_STALE:
443 		ndp_state_str = "ND6_LLINFO_STALE";
444 		break;
445 	case ND6_LLINFO_DELAY:
446 		ndp_state_str = "ND6_LLINFO_DELAY";
447 		break;
448 	case ND6_LLINFO_PROBE:
449 		ndp_state_str = "ND6_LLINFO_PROBE";
450 		break;
451 	default:
452 		/* Init'd to UNKNOWN */
453 		break;
454 	}
455 	return ndp_state_str;
456 }
457 
458 void
ln_setexpire(struct llinfo_nd6 * ln,uint64_t expiry)459 ln_setexpire(struct llinfo_nd6 *ln, uint64_t expiry)
460 {
461 	ln->ln_expire = expiry;
462 }
463 
464 static uint64_t
ln_getexpire(struct llinfo_nd6 * ln)465 ln_getexpire(struct llinfo_nd6 *ln)
466 {
467 	struct timeval caltime;
468 	uint64_t expiry;
469 
470 	if (ln->ln_expire != 0) {
471 		rtentry_ref_t rt = ln->ln_rt;
472 
473 		VERIFY(rt != NULL);
474 		/* account for system time change */
475 		getmicrotime(&caltime);
476 
477 		rt->base_calendartime +=
478 		    NET_CALCULATE_CLOCKSKEW(caltime,
479 		    rt->base_calendartime, net_uptime(), rt->base_uptime);
480 
481 		expiry = rt->base_calendartime +
482 		    ln->ln_expire - rt->base_uptime;
483 	} else {
484 		expiry = 0;
485 	}
486 	return expiry;
487 }
488 
489 void
nd6_ifreset(struct ifnet * ifp)490 nd6_ifreset(struct ifnet *ifp)
491 {
492 	struct nd_ifinfo *__single ndi = ND_IFINFO(ifp);
493 	VERIFY(NULL != ndi);
494 	VERIFY(ndi->initialized);
495 
496 	LCK_MTX_ASSERT(&ndi->lock, LCK_MTX_ASSERT_OWNED);
497 	ndi->linkmtu = ifp->if_mtu;
498 	ndi->chlim = IPV6_DEFHLIM;
499 	ndi->basereachable = REACHABLE_TIME;
500 	ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
501 	ndi->retrans = RETRANS_TIMER;
502 }
503 
504 void
nd6_ifattach(struct ifnet * ifp)505 nd6_ifattach(struct ifnet *ifp)
506 {
507 	struct nd_ifinfo *__single ndi = ND_IFINFO(ifp);
508 	VERIFY(NULL != ndi);
509 
510 	if (!ndi->initialized) {
511 		lck_mtx_init(&ndi->lock, &nd_if_lock_grp, &nd_if_lock_attr);
512 		ndi->flags = ND6_IFF_PERFORMNUD;
513 		ndi->flags |= ND6_IFF_DAD;
514 		ndi->initialized = TRUE;
515 	}
516 
517 	lck_mtx_lock(&ndi->lock);
518 
519 	if (!(ifp->if_flags & IFF_MULTICAST)) {
520 		ndi->flags |= ND6_IFF_IFDISABLED;
521 	}
522 
523 	nd6_ifreset(ifp);
524 	lck_mtx_unlock(&ndi->lock);
525 	nd6_setmtu(ifp);
526 
527 	nd6log0(info,
528 	    "Reinit'd ND information for interface %s\n",
529 	    if_name(ifp));
530 	return;
531 }
532 
533 #if 0
534 /*
535  * XXX Look more into this. Especially since we recycle ifnets and do delayed
536  * cleanup
537  */
538 void
539 nd6_ifdetach(struct nd_ifinfo *nd)
540 {
541 	/* XXX destroy nd's lock? */
542 	FREE(nd, M_IP6NDP);
543 }
544 #endif
545 
546 void
nd6_setmtu(struct ifnet * ifp)547 nd6_setmtu(struct ifnet *ifp)
548 {
549 	struct nd_ifinfo *__single ndi = ND_IFINFO(ifp);
550 	u_int32_t oldmaxmtu, maxmtu;
551 
552 	if ((NULL == ndi) || (FALSE == ndi->initialized)) {
553 		return;
554 	}
555 
556 	lck_mtx_lock(&ndi->lock);
557 	oldmaxmtu = ndi->maxmtu;
558 
559 	/*
560 	 * The ND level maxmtu is somewhat redundant to the interface MTU
561 	 * and is an implementation artifact of KAME.  Instead of hard-
562 	 * limiting the maxmtu based on the interface type here, we simply
563 	 * take the if_mtu value since SIOCSIFMTU would have taken care of
564 	 * the sanity checks related to the maximum MTU allowed for the
565 	 * interface (a value that is known only by the interface layer),
566 	 * by sending the request down via ifnet_ioctl().  The use of the
567 	 * ND level maxmtu and linkmtu are done via IN6_LINKMTU() which
568 	 * does further checking against if_mtu.
569 	 */
570 	maxmtu = ndi->maxmtu = ifp->if_mtu;
571 
572 	/*
573 	 * Decreasing the interface MTU under IPV6 minimum MTU may cause
574 	 * undesirable situation.  We thus notify the operator of the change
575 	 * explicitly.  The check for oldmaxmtu is necessary to restrict the
576 	 * log to the case of changing the MTU, not initializing it.
577 	 */
578 	if (oldmaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
579 		log(LOG_NOTICE, "nd6_setmtu: "
580 		    "new link MTU on %s (%u) is too small for IPv6\n",
581 		    if_name(ifp), (uint32_t)ndi->maxmtu);
582 	}
583 	ndi->linkmtu = ifp->if_mtu;
584 	lck_mtx_unlock(&ndi->lock);
585 
586 	/* also adjust in6_maxmtu if necessary. */
587 	if (maxmtu > in6_maxmtu) {
588 		in6_setmaxmtu();
589 	}
590 }
591 
592 void
nd6_option_init(void * __sized_by (icmp6len)opt,size_t icmp6len,union nd_opts * ndopts)593 nd6_option_init(void *__sized_by(icmp6len) opt, size_t icmp6len, union nd_opts *ndopts)
594 {
595 	bzero(ndopts, sizeof(*ndopts));
596 	if (icmp6len > 0) {
597 		ndopts->nd_opts_done = 0;
598 		ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
599 		ndopts->nd_opts_last = (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
600 	} else {
601 		ndopts->nd_opts_done = 1;
602 		ndopts->nd_opts_search = NULL;
603 		ndopts->nd_opts_last = NULL;
604 	}
605 	ndopts->nd_opts_initialized = 1;
606 }
607 
608 /*
609  * Take one ND option.
610  */
611 struct nd_opt_hdr *
nd6_option(union nd_opts * ndopts)612 nd6_option(union nd_opts *ndopts)
613 {
614 	struct nd_opt_hdr *nd_opt;
615 	int olen;
616 
617 	if (!ndopts) {
618 		panic("ndopts == NULL in nd6_option");
619 	}
620 	if (ndopts->nd_opts_initialized != 1) {
621 		panic("uninitialized ndopts in nd6_option");
622 	}
623 	if (!ndopts->nd_opts_search) {
624 		return NULL;
625 	}
626 	if (ndopts->nd_opts_done) {
627 		return NULL;
628 	}
629 
630 	nd_opt = ndopts->nd_opts_search;
631 
632 	/* make sure nd_opt_len is inside the buffer */
633 	if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
634 		bzero(ndopts, sizeof(*ndopts));
635 		return NULL;
636 	}
637 
638 	olen = nd_opt->nd_opt_len << 3;
639 	if (olen == 0) {
640 		/*
641 		 * Message validation requires that all included
642 		 * options have a length that is greater than zero.
643 		 */
644 		bzero(ndopts, sizeof(*ndopts));
645 		return NULL;
646 	}
647 
648 	VERIFY(ndopts->nd_opts_last >= ndopts->nd_opts_search);
649 	size_t remaining = (caddr_t)ndopts->nd_opts_last - (caddr_t)ndopts->nd_opts_search;
650 
651 	if (olen > remaining) {
652 		/* option overruns the end of buffer, invalid */
653 		bzero(ndopts, sizeof(*ndopts));
654 		return NULL;
655 	} else if (olen == remaining) {
656 		/* reached the end of options chain */
657 		ndopts->nd_opts_done = 1;
658 	} else {
659 		/* more options */
660 		ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
661 		ndopts->nd_opts_last = ndopts->nd_opts_last;
662 	}
663 
664 	return nd_opt;
665 }
666 
667 /*
668  * Parse multiple ND options.
669  * This function is much easier to use, for ND routines that do not need
670  * multiple options of the same type.
671  */
672 int
nd6_options(union nd_opts * ndopts)673 nd6_options(union nd_opts *ndopts)
674 {
675 	struct nd_opt_hdr *__single nd_opt;
676 	int i = 0;
677 
678 	if (ndopts == NULL) {
679 		panic("ndopts == NULL in nd6_options");
680 	}
681 	if (ndopts->nd_opts_initialized != 1) {
682 		panic("uninitialized ndopts in nd6_options");
683 	}
684 	if (ndopts->nd_opts_search == NULL) {
685 		return 0;
686 	}
687 
688 	while (1) {
689 		nd_opt = nd6_option(ndopts);
690 		if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
691 			/*
692 			 * Message validation requires that all included
693 			 * options have a length that is greater than zero.
694 			 */
695 			icmp6stat.icp6s_nd_badopt++;
696 			bzero(ndopts, sizeof(*ndopts));
697 			return -1;
698 		}
699 
700 		if (nd_opt == NULL) {
701 			goto skip1;
702 		}
703 
704 		switch (nd_opt->nd_opt_type) {
705 		case ND_OPT_SOURCE_LINKADDR:
706 		case ND_OPT_TARGET_LINKADDR:
707 		case ND_OPT_MTU:
708 		case ND_OPT_REDIRECTED_HEADER:
709 		case ND_OPT_NONCE:
710 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
711 				nd6log(error,
712 				    "duplicated ND6 option found (type=%d)\n",
713 				    nd_opt->nd_opt_type);
714 				/* XXX bark? */
715 			} else {
716 				ndopts->nd_opt_array[nd_opt->nd_opt_type] =
717 				    nd_opt;
718 			}
719 			break;
720 		case ND_OPT_PREFIX_INFORMATION:
721 			if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
722 				ndopts->nd_opt_array[nd_opt->nd_opt_type] =
723 				    nd_opt;
724 			}
725 			ndopts->nd_opts_pi_end =
726 			    (struct nd_opt_prefix_info *)nd_opt;
727 			break;
728 		case ND_OPT_PVD:
729 		case ND_OPT_RDNSS:
730 		case ND_OPT_DNSSL:
731 		case ND_OPT_CAPTIVE_PORTAL:
732 			/* ignore */
733 			break;
734 		case ND_OPT_ROUTE_INFO:
735 			if (nd6_process_rti) {
736 				if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
737 					ndopts->nd_opt_array[nd_opt->nd_opt_type]
738 					        = nd_opt;
739 				}
740 				ndopts->nd_opts_rti_end =
741 				    (struct nd_opt_route_info *)nd_opt;
742 				break;
743 			}
744 			OS_FALLTHROUGH;
745 		default:
746 			/*
747 			 * Unknown options must be silently ignored,
748 			 * to accommodate future extensions to the protocol.
749 			 */
750 			nd6log2(debug,
751 			    "nd6_options: unsupported option %d - "
752 			    "option ignored\n", nd_opt->nd_opt_type);
753 		}
754 
755 skip1:
756 		i++;
757 		if (i > nd6_maxndopt) {
758 			icmp6stat.icp6s_nd_toomanyopt++;
759 			nd6log(info, "too many loop in nd opt\n");
760 			break;
761 		}
762 
763 		if (ndopts->nd_opts_done) {
764 			break;
765 		}
766 	}
767 
768 	return 0;
769 }
770 
771 struct nd6svc_arg {
772 	int draining;
773 	uint32_t killed;
774 	uint32_t aging_lazy;
775 	uint32_t aging;
776 	uint32_t sticky;
777 	uint32_t found;
778 };
779 
780 
781 static void
nd6_service_neighbor_cache(struct nd6svc_arg * ap,uint64_t timenow)782 nd6_service_neighbor_cache(struct nd6svc_arg *ap, uint64_t timenow)
783 {
784 	struct llinfo_nd6 *__single ln;
785 	ifnet_ref_t ifp = NULL;
786 	boolean_t send_nc_failure_kev = FALSE;
787 	radix_node_head_ref_t rnh = rt_tables[AF_INET6];
788 
789 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
790 again:
791 	/*
792 	 * send_nc_failure_kev gets set when default router's IPv6 address
793 	 * can't be resolved.
794 	 * That can happen either:
795 	 * 1. When the entry has resolved once but can't be
796 	 * resolved later and the neighbor cache entry for gateway is deleted
797 	 * after max probe attempts.
798 	 *
799 	 * 2. When the entry is in ND6_LLINFO_INCOMPLETE but can not be resolved
800 	 * after max neighbor address resolution attempts.
801 	 *
802 	 * Both set send_nc_failure_kev to true. ifp is also set to the previous
803 	 * neighbor cache entry's route's ifp.
804 	 * Once we are done sending the notification, set send_nc_failure_kev
805 	 * to false to stop sending false notifications for non default router
806 	 * neighbors.
807 	 *
808 	 * We may to send more information like Gateway's IP that could not be
809 	 * resolved, however right now we do not install more than one default
810 	 * route per interface in the routing table.
811 	 */
812 	if (send_nc_failure_kev && ifp != NULL &&
813 	    ifp->if_addrlen == IF_LLREACH_MAXLEN) {
814 		struct kev_msg ev_msg;
815 		struct kev_nd6_ndfailure nd6_ndfailure;
816 		bzero(&ev_msg, sizeof(ev_msg));
817 		bzero(&nd6_ndfailure, sizeof(nd6_ndfailure));
818 		ev_msg.vendor_code      = KEV_VENDOR_APPLE;
819 		ev_msg.kev_class        = KEV_NETWORK_CLASS;
820 		ev_msg.kev_subclass     = KEV_ND6_SUBCLASS;
821 		ev_msg.event_code       = KEV_ND6_NDFAILURE;
822 
823 		nd6_ndfailure.link_data.if_family = ifp->if_family;
824 		nd6_ndfailure.link_data.if_unit = ifp->if_unit;
825 		strlcpy(nd6_ndfailure.link_data.if_name,
826 		    ifp->if_name,
827 		    sizeof(nd6_ndfailure.link_data.if_name));
828 		ev_msg.dv[0].data_ptr = &nd6_ndfailure;
829 		ev_msg.dv[0].data_length =
830 		    sizeof(nd6_ndfailure);
831 		dlil_post_complete_msg(NULL, &ev_msg);
832 	}
833 
834 	send_nc_failure_kev = FALSE;
835 	ifp = NULL;
836 	/*
837 	 * The global list llinfo_nd6 is modified by nd6_request() and is
838 	 * therefore protected by rnh_lock.  For obvious reasons, we cannot
839 	 * hold rnh_lock across calls that might lead to code paths which
840 	 * attempt to acquire rnh_lock, else we deadlock.  Hence for such
841 	 * cases we drop rt_lock and rnh_lock, make the calls, and repeat the
842 	 * loop.  To ensure that we don't process the same entry more than
843 	 * once in a single timeout, we mark the "already-seen" entries with
844 	 * ND6_LNF_TIMER_SKIP flag.  At the end of the loop, we do a second
845 	 * pass thru the entries and clear the flag so they can be processed
846 	 * during the next timeout.
847 	 */
848 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
849 
850 	ln = llinfo_nd6.ln_next;
851 	while (ln != NULL && ln != &llinfo_nd6) {
852 		rtentry_ref_t rt;
853 		struct sockaddr_in6 *__single dst;
854 		struct llinfo_nd6 *__single next;
855 		u_int32_t retrans, flags;
856 		struct nd_ifinfo *__single ndi = NULL;
857 		boolean_t is_router = FALSE;
858 
859 		/* ln_next/prev/rt is protected by rnh_lock */
860 		next = ln->ln_next;
861 		rt = ln->ln_rt;
862 		RT_LOCK(rt);
863 
864 		/* We've seen this already; skip it */
865 		if (ln->ln_flags & ND6_LNF_TIMER_SKIP) {
866 			RT_UNLOCK(rt);
867 			ln = next;
868 			continue;
869 		}
870 		ap->found++;
871 
872 		/* rt->rt_ifp should never be NULL */
873 		if ((ifp = rt->rt_ifp) == NULL) {
874 			panic("%s: ln(%p) rt(%p) rt_ifp == NULL", __func__,
875 			    ln, rt);
876 			/* NOTREACHED */
877 		}
878 
879 		/* rt_llinfo must always be equal to ln */
880 		if ((struct llinfo_nd6 *)rt->rt_llinfo != ln) {
881 			panic("%s: rt_llinfo(%p) is not equal to ln(%p)",
882 			    __func__, rt->rt_llinfo, ln);
883 			/* NOTREACHED */
884 		}
885 
886 		/* rt_key should never be NULL */
887 		dst = SIN6(rt_key(rt));
888 		if (dst == NULL) {
889 			panic("%s: rt(%p) key is NULL ln(%p)", __func__,
890 			    rt, ln);
891 			/* NOTREACHED */
892 		}
893 
894 		/* Set the flag in case we jump to "again" */
895 		ln->ln_flags |= ND6_LNF_TIMER_SKIP;
896 
897 		/*
898 		 * Do not touch neighbor cache entries that are permanent,
899 		 * static or are for interfaces that manage neighbor cache
900 		 * entries via alternate NDP means.
901 		 */
902 		if (ln->ln_expire == 0 || (rt->rt_flags & RTF_STATIC) ||
903 		    (rt->rt_ifp->if_eflags & IFEF_IPV6_ND6ALT)) {
904 			ap->sticky++;
905 		} else if (ap->draining && (rt->rt_refcnt == 0)) {
906 			/*
907 			 * If we are draining, immediately purge non-static
908 			 * entries without oustanding route refcnt.
909 			 */
910 			if (ln->ln_state > ND6_LLINFO_INCOMPLETE) {
911 				ND6_CACHE_STATE_TRANSITION(ln, (short)ND6_LLINFO_STALE);
912 			} else {
913 				ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_PURGE);
914 			}
915 			ln_setexpire(ln, timenow);
916 		}
917 
918 		/*
919 		 * If the entry has not expired, skip it. Take note on the
920 		 * state, as entries that are in the STALE state are simply
921 		 * waiting to be garbage collected, in which case we can
922 		 * relax the callout scheduling (use nd6_prune_lazy).
923 		 */
924 		if (ln->ln_expire > timenow) {
925 			switch (ln->ln_state) {
926 			case ND6_LLINFO_STALE:
927 				ap->aging_lazy++;
928 				break;
929 			default:
930 				ap->aging++;
931 				break;
932 			}
933 			RT_UNLOCK(rt);
934 			ln = next;
935 			continue;
936 		}
937 
938 		ndi = ND_IFINFO(ifp);
939 		/*
940 		 * The IPv6 initialization of the loopback interface
941 		 * may happen after another interface gets assigned
942 		 * an IPv6 address
943 		 */
944 		if (ndi == NULL && ifp == lo_ifp) {
945 			RT_UNLOCK(rt);
946 			ln = next;
947 			continue;
948 		}
949 		VERIFY(ndi->initialized);
950 		retrans = ndi->retrans;
951 		flags = ndi->flags;
952 
953 		RT_LOCK_ASSERT_HELD(rt);
954 		is_router = (rt->rt_flags & RTF_ROUTER) ? TRUE : FALSE;
955 
956 		switch (ln->ln_state) {
957 		case ND6_LLINFO_INCOMPLETE:
958 			if (ln->ln_asked < nd6_mmaxtries) {
959 				ifnet_ref_t exclifp = ln->ln_exclifp;
960 				ln->ln_asked++;
961 				ln_setexpire(ln, timenow + retrans / 1000);
962 				RT_ADDREF_LOCKED(rt);
963 				RT_UNLOCK(rt);
964 				lck_mtx_unlock(rnh_lock);
965 				if (ip6_forwarding) {
966 					nd6_prproxy_ns_output(ifp, exclifp,
967 					    NULL, &dst->sin6_addr, ln);
968 				} else {
969 					nd6_ns_output(ifp, NULL,
970 					    &dst->sin6_addr, ln, NULL, 0);
971 				}
972 				RT_REMREF(rt);
973 				ap->aging++;
974 				lck_mtx_lock(rnh_lock);
975 			} else {
976 				mbuf_ref_t m = ln->ln_hold;
977 				ln->ln_hold = NULL;
978 				send_nc_failure_kev = is_router;
979 				if (m != NULL) {
980 					RT_ADDREF_LOCKED(rt);
981 					RT_UNLOCK(rt);
982 					lck_mtx_unlock(rnh_lock);
983 
984 					mbuf_ref_t mnext;
985 					while (m) {
986 						mnext = m->m_nextpkt;
987 						m->m_nextpkt = NULL;
988 						m->m_pkthdr.rcvif = ifp;
989 						icmp6_error_flag(m, ICMP6_DST_UNREACH,
990 						    ICMP6_DST_UNREACH_ADDR, 0, 0);
991 						m = mnext;
992 					}
993 				} else {
994 					RT_ADDREF_LOCKED(rt);
995 					RT_UNLOCK(rt);
996 					lck_mtx_unlock(rnh_lock);
997 				}
998 
999 				/*
1000 				 * Enqueue work item to invoke callback for
1001 				 * this route entry
1002 				 */
1003 				route_event_enqueue_nwk_wq_entry(rt, NULL,
1004 				    ROUTE_LLENTRY_UNREACH, NULL, FALSE);
1005 				defrouter_set_reachability(&SIN6(rt_key(rt))->sin6_addr, rt->rt_ifp,
1006 				    FALSE);
1007 				nd6_free(rt);
1008 				ap->killed++;
1009 				lck_mtx_lock(rnh_lock);
1010 				/*
1011 				 * nd6_free above would flush out the routing table of
1012 				 * any cloned routes with same next-hop.
1013 				 * Walk the tree anyways as there could be static routes
1014 				 * left.
1015 				 *
1016 				 * We also already have a reference to rt that gets freed right
1017 				 * after the block below executes. Don't need an extra reference
1018 				 * on rt here.
1019 				 */
1020 				if (is_router) {
1021 					struct route_event rt_ev;
1022 					route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_UNREACH);
1023 					(void) rnh->rnh_walktree(rnh, route_event_walktree, (void *)&rt_ev);
1024 				}
1025 				rtfree_locked(rt);
1026 			}
1027 			LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1028 			goto again;
1029 
1030 		case ND6_LLINFO_REACHABLE:
1031 			if (ln->ln_expire != 0) {
1032 				ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);
1033 				ln_setexpire(ln, timenow + nd6_gctimer);
1034 				ap->aging_lazy++;
1035 				/*
1036 				 * Enqueue work item to invoke callback for
1037 				 * this route entry
1038 				 */
1039 				route_event_enqueue_nwk_wq_entry(rt, NULL,
1040 				    ROUTE_LLENTRY_STALE, NULL, TRUE);
1041 
1042 				RT_ADDREF_LOCKED(rt);
1043 				RT_UNLOCK(rt);
1044 				if (is_router) {
1045 					struct route_event rt_ev;
1046 					route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_STALE);
1047 					(void) rnh->rnh_walktree(rnh, route_event_walktree, (void *)&rt_ev);
1048 				}
1049 				rtfree_locked(rt);
1050 			} else {
1051 				RT_UNLOCK(rt);
1052 			}
1053 			break;
1054 
1055 		case ND6_LLINFO_STALE:
1056 		case ND6_LLINFO_PURGE:
1057 			/* Garbage Collection(RFC 4861 5.3) */
1058 			if (ln->ln_expire != 0) {
1059 				RT_ADDREF_LOCKED(rt);
1060 				RT_UNLOCK(rt);
1061 				lck_mtx_unlock(rnh_lock);
1062 				nd6_free(rt);
1063 				ap->killed++;
1064 				lck_mtx_lock(rnh_lock);
1065 				rtfree_locked(rt);
1066 				goto again;
1067 			} else {
1068 				RT_UNLOCK(rt);
1069 			}
1070 			break;
1071 
1072 		case ND6_LLINFO_DELAY:
1073 			if ((flags & ND6_IFF_PERFORMNUD) != 0) {
1074 				/* We need NUD */
1075 				ln->ln_asked = 1;
1076 				ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_PROBE);
1077 				ln_setexpire(ln, timenow + retrans / 1000);
1078 				RT_ADDREF_LOCKED(rt);
1079 				RT_UNLOCK(rt);
1080 				lck_mtx_unlock(rnh_lock);
1081 				nd6_ns_output(ifp, &dst->sin6_addr,
1082 				    &dst->sin6_addr, ln, NULL, 0);
1083 				RT_REMREF(rt);
1084 				ap->aging++;
1085 				lck_mtx_lock(rnh_lock);
1086 				goto again;
1087 			}
1088 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);         /* XXX */
1089 			ln_setexpire(ln, timenow + nd6_gctimer);
1090 			RT_UNLOCK(rt);
1091 			ap->aging_lazy++;
1092 			break;
1093 
1094 		case ND6_LLINFO_PROBE:
1095 			if (ln->ln_asked < nd6_umaxtries) {
1096 				ln->ln_asked++;
1097 				ln_setexpire(ln, timenow + retrans / 1000);
1098 				RT_ADDREF_LOCKED(rt);
1099 				RT_UNLOCK(rt);
1100 				lck_mtx_unlock(rnh_lock);
1101 				nd6_ns_output(ifp, &dst->sin6_addr,
1102 				    &dst->sin6_addr, ln, NULL, 0);
1103 				RT_REMREF(rt);
1104 				ap->aging++;
1105 				lck_mtx_lock(rnh_lock);
1106 			} else {
1107 				is_router = (rt->rt_flags & RTF_ROUTER) ? TRUE : FALSE;
1108 				send_nc_failure_kev = is_router;
1109 				RT_ADDREF_LOCKED(rt);
1110 				RT_UNLOCK(rt);
1111 				lck_mtx_unlock(rnh_lock);
1112 				nd6_free(rt);
1113 				ap->killed++;
1114 
1115 				/*
1116 				 * Enqueue work item to invoke callback for
1117 				 * this route entry
1118 				 */
1119 				route_event_enqueue_nwk_wq_entry(rt, NULL,
1120 				    ROUTE_LLENTRY_UNREACH, NULL, FALSE);
1121 				defrouter_set_reachability(&SIN6(rt_key(rt))->sin6_addr, rt->rt_ifp,
1122 				    FALSE);
1123 				lck_mtx_lock(rnh_lock);
1124 				/*
1125 				 * nd6_free above would flush out the routing table of
1126 				 * any cloned routes with same next-hop.
1127 				 * Walk the tree anyways as there could be static routes
1128 				 * left.
1129 				 *
1130 				 * We also already have a reference to rt that gets freed right
1131 				 * after the block below executes. Don't need an extra reference
1132 				 * on rt here.
1133 				 */
1134 				if (is_router) {
1135 					struct route_event rt_ev;
1136 					route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_UNREACH);
1137 					(void) rnh->rnh_walktree(rnh,
1138 					    route_event_walktree, (void *)&rt_ev);
1139 				}
1140 				rtfree_locked(rt);
1141 			}
1142 			LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1143 			goto again;
1144 
1145 		default:
1146 			RT_UNLOCK(rt);
1147 			break;
1148 		}
1149 		ln = next;
1150 	}
1151 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1152 
1153 	/* Now clear the flag from all entries */
1154 	ln = llinfo_nd6.ln_next;
1155 	while (ln != NULL && ln != &llinfo_nd6) {
1156 		rtentry_ref_t rt = ln->ln_rt;
1157 		struct llinfo_nd6 *__single next = ln->ln_next;
1158 
1159 		RT_LOCK_SPIN(rt);
1160 		if (ln->ln_flags & ND6_LNF_TIMER_SKIP) {
1161 			ln->ln_flags &= ~ND6_LNF_TIMER_SKIP;
1162 		}
1163 		RT_UNLOCK(rt);
1164 		ln = next;
1165 	}
1166 }
1167 
1168 static void
nd6_service_expired_default_router(struct nd6svc_arg * ap,uint64_t timenow)1169 nd6_service_expired_default_router(struct nd6svc_arg *ap, uint64_t timenow)
1170 {
1171 	struct nd_defrouter *__single dr = NULL;
1172 	struct nd_defrouter *__single ndr = NULL;
1173 	struct nd_drhead nd_defrouter_tmp;
1174 	/* expire default router list */
1175 	TAILQ_INIT(&nd_defrouter_tmp);
1176 
1177 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1178 	lck_mtx_lock(nd6_mutex);
1179 
1180 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter_list, dr_entry, ndr) {
1181 		ap->found++;
1182 		if (dr->expire != 0 && dr->expire < timenow) {
1183 			VERIFY(dr->ifp != NULL);
1184 			in6_ifstat_inc(dr->ifp, ifs6_defrtr_expiry_cnt);
1185 			if ((dr->stateflags & NDDRF_INELIGIBLE) == 0) {
1186 				in6_event_enqueue_nwk_wq_entry(IN6_NDP_RTR_EXPIRY, dr->ifp,
1187 				    &dr->rtaddr, dr->rtlifetime);
1188 			}
1189 			if (dr->ifp != NULL &&
1190 			    dr->ifp->if_type == IFT_CELLULAR) {
1191 				/*
1192 				 * Some buggy cellular gateways may not send
1193 				 * periodic router advertisements.
1194 				 * Or they may send it with router lifetime
1195 				 * value that is less than the configured Max and Min
1196 				 * Router Advertisement interval.
1197 				 * To top that an idle device may not wake up
1198 				 * when periodic RA is received on cellular
1199 				 * interface.
1200 				 * We could send RS on every wake but RFC
1201 				 * 4861 precludes that.
1202 				 * The addresses are of infinite lifetimes
1203 				 * and are tied to the lifetime of the bearer,
1204 				 * so keeping the addresses and just getting rid of
1205 				 * the router does not help us anyways.
1206 				 * If there's network renumbering, a lifetime with
1207 				 * value 0 would remove the default router.
1208 				 * Also it will get deleted as part of purge when
1209 				 * the PDP context is torn down and configured again.
1210 				 * For that reason, do not expire the default router
1211 				 * learned on cellular interface. Ever.
1212 				 */
1213 				dr->expire += dr->rtlifetime;
1214 				nd6log2(debug,
1215 				    "%s: Refreshing expired default router entry "
1216 				    "%s for interface %s\n", __func__,
1217 				    ip6_sprintf(&dr->rtaddr), if_name(dr->ifp));
1218 			} else {
1219 				ap->killed++;
1220 				/*
1221 				 * Remove the entry from default router list
1222 				 * and add it to the temp list.
1223 				 * nd_defrouter_tmp will be a local temporary
1224 				 * list as no one else can get the same
1225 				 * removed entry once it is removed from default
1226 				 * router list.
1227 				 * Remove the reference after calling defrtrlist_del
1228 				 */
1229 				TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
1230 				TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
1231 			}
1232 		} else {
1233 			if (dr->expire == 0 || (dr->stateflags & NDDRF_STATIC)) {
1234 				ap->sticky++;
1235 			} else {
1236 				ap->aging_lazy++;
1237 			}
1238 		}
1239 	}
1240 
1241 	/*
1242 	 * Keep the following separate from the above
1243 	 * iteration of nd_defrouter because it's not safe
1244 	 * to call defrtrlist_del while iterating over the
1245 	 * global default * router list. The Global list
1246 	 * has to be traversed while holding nd6_mutex throughout.
1247 	 *
1248 	 * The following call to defrtrlist_del should be
1249 	 * safe as we are iterating a local list of
1250 	 * default routers.
1251 	 */
1252 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter_tmp, dr_entry, ndr) {
1253 		TAILQ_REMOVE(&nd_defrouter_tmp, dr, dr_entry);
1254 		defrtrlist_del(dr, NULL);
1255 		NDDR_REMREF(dr);        /* remove list reference */
1256 	}
1257 
1258 	/* XXX TBD: Also iterate through RTI router lists */
1259 	/*
1260 	 * Also check if default router selection needs to be triggered
1261 	 * for default interface, to avoid an issue with co-existence of
1262 	 * static un-scoped default route configuration and default router
1263 	 * discovery/selection.
1264 	 */
1265 	if (trigger_v6_defrtr_select) {
1266 		defrouter_select(NULL, NULL);
1267 		trigger_v6_defrtr_select = FALSE;
1268 	}
1269 	lck_mtx_unlock(nd6_mutex);
1270 }
1271 
1272 static void
nd6_service_expired_route_info(struct nd6svc_arg * ap,uint64_t timenow)1273 nd6_service_expired_route_info(struct nd6svc_arg *ap, uint64_t timenow)
1274 {
1275 	struct nd_route_info *__single rti = NULL;
1276 	struct nd_route_info *__single rti_next = NULL;
1277 
1278 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1279 	lck_mtx_lock(nd6_mutex);
1280 	nd6_rti_list_wait(__func__);
1281 
1282 	TAILQ_FOREACH_SAFE(rti, &nd_rti_list, nd_rti_entry, rti_next) {
1283 		struct nd_defrouter *__single dr = NULL;
1284 		struct nd_defrouter *__single ndr = NULL;
1285 		struct nd_route_info rti_tmp = {};
1286 
1287 		rti_tmp.nd_rti_prefix = rti->nd_rti_prefix;
1288 		rti_tmp.nd_rti_prefixlen = rti->nd_rti_prefixlen;
1289 		TAILQ_INIT(&rti_tmp.nd_rti_router_list);
1290 
1291 		TAILQ_FOREACH_SAFE(dr, &rti->nd_rti_router_list, dr_entry, ndr) {
1292 			ap->found++;
1293 			if (dr->expire != 0 && dr->expire < timenow) {
1294 				VERIFY(dr->ifp != NULL);
1295 				if (dr->ifp != NULL &&
1296 				    dr->ifp->if_type == IFT_CELLULAR) {
1297 					/*
1298 					 * Don't expire these routes over cellular.
1299 					 * XXX Should we change this for non default routes?
1300 					 */
1301 					dr->expire += dr->rtlifetime;
1302 					nd6log2(debug,
1303 					    "%s: Refreshing expired default router entry "
1304 					    "%s for interface %s\n", __func__,
1305 					    ip6_sprintf(&dr->rtaddr), if_name(dr->ifp));
1306 				} else {
1307 					ap->killed++;
1308 					/*
1309 					 * Remove the entry from rti entry's router list
1310 					 * and add it to the temp list.
1311 					 * Remove the reference after calling defrtrlist_del
1312 					 */
1313 					TAILQ_REMOVE(&rti->nd_rti_router_list, dr, dr_entry);
1314 					TAILQ_INSERT_TAIL(&rti_tmp.nd_rti_router_list, dr, dr_entry);
1315 				}
1316 			} else {
1317 				if (dr->expire == 0 || (dr->stateflags & NDDRF_STATIC)) {
1318 					ap->sticky++;
1319 				} else {
1320 					ap->aging_lazy++;
1321 				}
1322 			}
1323 		}
1324 
1325 		/*
1326 		 * Keep the following separate from the above
1327 		 * iteration of nd_defrouter because it's not safe
1328 		 * to call defrtrlist_del while iterating global default
1329 		 * router list. Global list has to be traversed
1330 		 * while holding nd6_mutex throughout.
1331 		 *
1332 		 * The following call to defrtrlist_del should be
1333 		 * safe as we are iterating a local list of
1334 		 * default routers.
1335 		 */
1336 		TAILQ_FOREACH_SAFE(dr, &rti_tmp.nd_rti_router_list, dr_entry, ndr) {
1337 			TAILQ_REMOVE(&rti_tmp.nd_rti_router_list, dr, dr_entry);
1338 			defrtrlist_del(dr, &rti->nd_rti_router_list);
1339 			NDDR_REMREF(dr);        /* remove list reference */
1340 		}
1341 
1342 		/*
1343 		 * The above may have removed an entry from default router list.
1344 		 * If it did and the list is now empty, remove the rti as well.
1345 		 */
1346 		if (TAILQ_EMPTY(&rti->nd_rti_router_list)) {
1347 			TAILQ_REMOVE(&nd_rti_list, rti, nd_rti_entry);
1348 			ndrti_free(rti);
1349 		}
1350 	}
1351 
1352 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1353 	nd6_rti_list_signal_done();
1354 	lck_mtx_unlock(nd6_mutex);
1355 }
1356 
1357 
1358 /*
1359  * @function nd6_handle_duplicated_ip6_addr
1360  *
1361  * @brief
1362  * Handle a duplicated IPv6 secured non-termporary address
1363  *
1364  * @discussion
1365  * If the collision count hasn't been exceeded, removes the old
1366  * conflicting IPv6 address, increments the collision count,
1367  * and allocates a new address.
1368  *
1369  * Returns TRUE if the old address was removed, and the locks
1370  * (in6_ifaddr_rwlock, ia6->ia_ifa) were unlocked.
1371  */
1372 static boolean_t
nd6_handle_duplicated_ip6_addr(struct in6_ifaddr * ia6)1373 nd6_handle_duplicated_ip6_addr(struct in6_ifaddr *ia6)
1374 {
1375 	uint8_t collision_count;
1376 	int error = 0;
1377 	struct in6_ifaddr *__single new_ia6;
1378 	struct nd_prefix *__single pr;
1379 	ifnet_ref_t ifp;
1380 
1381 	LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
1382 	IFA_LOCK_ASSERT_HELD(&ia6->ia_ifa);
1383 
1384 	/* don't retry too many times */
1385 	collision_count = ia6->ia6_cga_collision_count;
1386 	if (collision_count >= ip6_cga_conflict_retries) {
1387 		return FALSE;
1388 	}
1389 
1390 	/* need the prefix to allocate a new address */
1391 	pr = ia6->ia6_ndpr;
1392 	if (pr == NULL) {
1393 		return FALSE;
1394 	}
1395 	NDPR_ADDREF(pr);
1396 	ifp = pr->ndpr_ifp;
1397 	log(LOG_DEBUG,
1398 	    "%s: %s duplicated (collision count %d)\n",
1399 	    ifp->if_xname, ip6_sprintf(&ia6->ia_addr.sin6_addr),
1400 	    collision_count);
1401 
1402 	/* remove the old address */
1403 	IFA_UNLOCK(&ia6->ia_ifa);
1404 	lck_rw_done(&in6_ifaddr_rwlock);
1405 	in6_purgeaddr(&ia6->ia_ifa);
1406 
1407 	/* allocate a new address with new collision count */
1408 	collision_count++;
1409 	new_ia6 = in6_pfx_newpersistaddr(pr, 1, &error, FALSE, collision_count);
1410 	if (new_ia6 != NULL) {
1411 		log(LOG_DEBUG,
1412 		    "%s: %s new (collision count %d)\n",
1413 		    ifp->if_xname, ip6_sprintf(&new_ia6->ia_addr.sin6_addr),
1414 		    collision_count);
1415 		IFA_LOCK(&new_ia6->ia_ifa);
1416 		NDPR_LOCK(pr);
1417 		new_ia6->ia6_ndpr = pr;
1418 		NDPR_ADDREF(pr); /* for addr reference */
1419 		pr->ndpr_addrcnt++;
1420 		VERIFY(pr->ndpr_addrcnt != 0);
1421 		NDPR_UNLOCK(pr);
1422 		IFA_UNLOCK(&new_ia6->ia_ifa);
1423 		ifa_remref(&new_ia6->ia_ifa);
1424 	} else {
1425 		log(LOG_ERR, "%s: in6_pfx_newpersistaddr failed %d\n",
1426 		    __func__, error);
1427 	}
1428 
1429 	/* release extra prefix reference */
1430 	NDPR_REMREF(pr);
1431 	return TRUE;
1432 }
1433 
1434 static boolean_t
secured_address_is_duplicated(int flags)1435 secured_address_is_duplicated(int flags)
1436 {
1437 #define _IN6_IFF_DUPLICATED_AUTOCONF_SECURED                            \
1438 	(IN6_IFF_DUPLICATED | IN6_IFF_AUTOCONF | IN6_IFF_SECURED)
1439 	return (flags & _IN6_IFF_DUPLICATED_AUTOCONF_SECURED) ==
1440 	       _IN6_IFF_DUPLICATED_AUTOCONF_SECURED;
1441 }
1442 
1443 static void
nd6_service_ip6_addr(struct nd6svc_arg * ap,uint64_t timenow)1444 nd6_service_ip6_addr(struct nd6svc_arg *ap, uint64_t timenow)
1445 {
1446 	struct in6_ifaddr *__single ia6 = NULL;
1447 	struct in6_ifaddr *__single nia6 = NULL;
1448 	/*
1449 	 * expire interface addresses.
1450 	 * in the past the loop was inside prefix expiry processing.
1451 	 * However, from a stricter spec-conformance standpoint, we should
1452 	 * rather separate address lifetimes and prefix lifetimes.
1453 	 */
1454 
1455 addrloop:
1456 	lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1457 
1458 	TAILQ_FOREACH_SAFE(ia6, &in6_ifaddrhead, ia6_link, nia6) {
1459 		int oldflags = ia6->ia6_flags;
1460 		ap->found++;
1461 		IFA_LOCK(&ia6->ia_ifa);
1462 		/*
1463 		 * Extra reference for ourselves; it's no-op if
1464 		 * we don't have to regenerate temporary address,
1465 		 * otherwise it protects the address from going
1466 		 * away since we drop in6_ifaddr_rwlock below.
1467 		 */
1468 		ifa_addref(&ia6->ia_ifa);
1469 
1470 		/*
1471 		 * Check for duplicated secured address
1472 		 *
1473 		 * nd6_handle_duplicated_ip6_addr attempts to regenerate
1474 		 * secure address in the event of a collision.
1475 		 * On successful generation this returns success
1476 		 * and we restart the loop.
1477 		 *
1478 		 * When we hit the maximum attempts, this returns
1479 		 * false.
1480 		 */
1481 		if (secured_address_is_duplicated(ia6->ia6_flags) &&
1482 		    nd6_handle_duplicated_ip6_addr(ia6)) {
1483 			/*
1484 			 * nd6_handle_duplicated_ip6_addr() unlocked
1485 			 * (in6_ifaddr_rwlock, ia6->ia_ifa) already.
1486 			 * Still need to release extra reference on
1487 			 * ia6->ia_ifa taken above.
1488 			 */
1489 			ifa_remref(&ia6->ia_ifa);
1490 			goto addrloop;
1491 		}
1492 
1493 		/* check address lifetime */
1494 		if (IFA6_IS_INVALID(ia6, timenow)) {
1495 			/*
1496 			 * If the expiring address is temporary, try
1497 			 * regenerating a new one.  This would be useful when
1498 			 * we suspended a laptop PC, then turned it on after a
1499 			 * period that could invalidate all temporary
1500 			 * addresses.  Although we may have to restart the
1501 			 * loop (see below), it must be after purging the
1502 			 * address.  Otherwise, we'd see an infinite loop of
1503 			 * regeneration.
1504 			 */
1505 			if (ip6_use_tempaddr &&
1506 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1507 				/*
1508 				 * NOTE: We have to drop the lock here
1509 				 * because regen_tmpaddr() eventually calls
1510 				 * in6_update_ifa(), which must take the lock
1511 				 * and would otherwise cause a hang.  This is
1512 				 * safe because the goto addrloop leads to a
1513 				 * re-evaluation of the in6_ifaddrs list
1514 				 */
1515 				IFA_UNLOCK(&ia6->ia_ifa);
1516 				lck_rw_done(&in6_ifaddr_rwlock);
1517 				(void) regen_tmpaddr(ia6);
1518 			} else {
1519 				IFA_UNLOCK(&ia6->ia_ifa);
1520 				lck_rw_done(&in6_ifaddr_rwlock);
1521 			}
1522 
1523 			/*
1524 			 * Purging the address would have caused
1525 			 * in6_ifaddr_rwlock to be dropped and reacquired;
1526 			 * therefore search again from the beginning
1527 			 * of in6_ifaddrs list.
1528 			 */
1529 			in6_purgeaddr(&ia6->ia_ifa);
1530 			ap->killed++;
1531 
1532 			if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) == 0) {
1533 				in6_ifstat_inc(ia6->ia_ifa.ifa_ifp, ifs6_addr_expiry_cnt);
1534 				in6_event_enqueue_nwk_wq_entry(IN6_NDP_ADDR_EXPIRY,
1535 				    ia6->ia_ifa.ifa_ifp, &ia6->ia_addr.sin6_addr,
1536 				    0);
1537 			}
1538 			/* Release extra reference taken above */
1539 			ifa_remref(&ia6->ia_ifa);
1540 			goto addrloop;
1541 		}
1542 		/*
1543 		 * The lazy timer runs every nd6_prune_lazy seconds with at
1544 		 * most "2 * nd6_prune_lazy - 1" leeway. We consider the worst
1545 		 * case here and make sure we schedule the regular timer if an
1546 		 * interface address is about to expire.
1547 		 */
1548 		if (IFA6_IS_INVALID(ia6, timenow + 3 * nd6_prune_lazy)) {
1549 			ap->aging++;
1550 		} else {
1551 			ap->aging_lazy++;
1552 		}
1553 		IFA_LOCK_ASSERT_HELD(&ia6->ia_ifa);
1554 		if (IFA6_IS_DEPRECATED(ia6, timenow)) {
1555 			ia6->ia6_flags |= IN6_IFF_DEPRECATED;
1556 
1557 			if ((oldflags & IN6_IFF_DEPRECATED) == 0) {
1558 #if SKYWALK
1559 				SK_NXS_MS_IF_ADDR_GENCNT_INC(ia6->ia_ifp);
1560 #endif /* SKYWALK */
1561 				/*
1562 				 * Only enqueue the Deprecated event when the address just
1563 				 * becomes deprecated.
1564 				 * Keep it limited to the stable address as it is common for
1565 				 * older temporary addresses to get deprecated while we generate
1566 				 * new ones.
1567 				 */
1568 				if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) == 0) {
1569 					in6_event_enqueue_nwk_wq_entry(IN6_ADDR_MARKED_DEPRECATED,
1570 					    ia6->ia_ifa.ifa_ifp, &ia6->ia_addr.sin6_addr,
1571 					    0);
1572 				}
1573 			}
1574 			/*
1575 			 * If a temporary address has just become deprecated,
1576 			 * regenerate a new one if possible.
1577 			 */
1578 			if (ip6_use_tempaddr &&
1579 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1580 			    (oldflags & IN6_IFF_DEPRECATED) == 0) {
1581 				/* see NOTE above */
1582 				IFA_UNLOCK(&ia6->ia_ifa);
1583 				lck_rw_done(&in6_ifaddr_rwlock);
1584 				if (regen_tmpaddr(ia6) == 0) {
1585 					/*
1586 					 * A new temporary address is
1587 					 * generated.
1588 					 * XXX: this means the address chain
1589 					 * has changed while we are still in
1590 					 * the loop.  Although the change
1591 					 * would not cause disaster (because
1592 					 * it's not a deletion, but an
1593 					 * addition,) we'd rather restart the
1594 					 * loop just for safety.  Or does this
1595 					 * significantly reduce performance??
1596 					 */
1597 					/* Release extra reference */
1598 					ifa_remref(&ia6->ia_ifa);
1599 					goto addrloop;
1600 				}
1601 				lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1602 			} else {
1603 				IFA_UNLOCK(&ia6->ia_ifa);
1604 			}
1605 		} else {
1606 			/*
1607 			 * A new RA might have made a deprecated address
1608 			 * preferred.
1609 			 */
1610 			ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
1611 #if SKYWALK
1612 			if ((oldflags & IN6_IFF_DEPRECATED) != 0) {
1613 				SK_NXS_MS_IF_ADDR_GENCNT_INC(ia6->ia_ifp);
1614 			}
1615 #endif /* SKYWALK */
1616 			IFA_UNLOCK(&ia6->ia_ifa);
1617 		}
1618 		LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
1619 		/* Release extra reference taken above */
1620 		ifa_remref(&ia6->ia_ifa);
1621 	}
1622 	lck_rw_done(&in6_ifaddr_rwlock);
1623 }
1624 
1625 static void
nd6_service_expired_prefix(struct nd6svc_arg * ap,uint64_t timenow)1626 nd6_service_expired_prefix(struct nd6svc_arg *ap, uint64_t timenow)
1627 {
1628 	struct nd_prefix *__single pr = NULL;
1629 
1630 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1631 	lck_mtx_lock(nd6_mutex);
1632 	/* expire prefix list */
1633 	pr = nd_prefix.lh_first;
1634 	while (pr != NULL) {
1635 		ap->found++;
1636 		/*
1637 		 * Skip already processed or defunct prefixes
1638 		 * We may iterate the prefix list from head again
1639 		 * so, we are trying to not revisit the same prefix
1640 		 * for the same instance of nd6_service
1641 		 */
1642 		NDPR_LOCK(pr);
1643 		if (pr->ndpr_stateflags & NDPRF_PROCESSED_SERVICE ||
1644 		    pr->ndpr_stateflags & NDPRF_DEFUNCT) {
1645 			pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1646 			NDPR_UNLOCK(pr);
1647 			pr = pr->ndpr_next;
1648 			continue;
1649 		}
1650 
1651 		/*
1652 		 * If there are still manual addresses configured in the system
1653 		 * that are associated with the prefix, ignore prefix expiry
1654 		 */
1655 		if (pr->ndpr_manual_addrcnt != 0) {
1656 			pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1657 			NDPR_UNLOCK(pr);
1658 			pr = pr->ndpr_next;
1659 			continue;
1660 		}
1661 
1662 		/*
1663 		 * check prefix lifetime.
1664 		 * since pltime is just for autoconf, pltime processing for
1665 		 * prefix is not necessary.
1666 		 */
1667 		if (pr->ndpr_expire != 0 && pr->ndpr_expire < timenow) {
1668 			/*
1669 			 * address expiration and prefix expiration are
1670 			 * separate. NEVER perform in6_purgeaddr here.
1671 			 */
1672 			pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1673 			NDPR_ADDREF(pr);
1674 			prelist_remove(pr);
1675 			NDPR_UNLOCK(pr);
1676 
1677 			in6_ifstat_inc(pr->ndpr_ifp, ifs6_pfx_expiry_cnt);
1678 			in6_event_enqueue_nwk_wq_entry(IN6_NDP_PFX_EXPIRY,
1679 			    pr->ndpr_ifp, &pr->ndpr_prefix.sin6_addr,
1680 			    0);
1681 			NDPR_REMREF(pr);
1682 			pfxlist_onlink_check();
1683 			pr = nd_prefix.lh_first;
1684 			ap->killed++;
1685 		} else {
1686 			if (pr->ndpr_expire == 0 ||
1687 			    (pr->ndpr_stateflags & NDPRF_STATIC)) {
1688 				ap->sticky++;
1689 			} else {
1690 				ap->aging_lazy++;
1691 			}
1692 			pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1693 			NDPR_UNLOCK(pr);
1694 			pr = pr->ndpr_next;
1695 		}
1696 	}
1697 	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
1698 		NDPR_LOCK(pr);
1699 		pr->ndpr_stateflags &= ~NDPRF_PROCESSED_SERVICE;
1700 		NDPR_UNLOCK(pr);
1701 	}
1702 	lck_mtx_unlock(nd6_mutex);
1703 }
1704 
1705 
1706 /*
1707  * ND6 service routine to expire default route list and prefix list
1708  */
1709 static void
nd6_service(void * arg)1710 nd6_service(void *arg)
1711 {
1712 	struct nd6svc_arg *__single ap = arg;
1713 	uint64_t timenow;
1714 
1715 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1716 	/*
1717 	 * Since we may drop rnh_lock and nd6_mutex below, we want
1718 	 * to run this entire operation single threaded.
1719 	 */
1720 	while (nd6_service_busy) {
1721 		nd6log2(debug, "%s: %s is blocked by %d waiters\n",
1722 		    __func__, ap->draining ? "drainer" : "timer",
1723 		    nd6_service_waiters);
1724 		nd6_service_waiters++;
1725 		(void) msleep(nd6_service_wc, rnh_lock, (PZERO - 1),
1726 		    __func__, NULL);
1727 		LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1728 	}
1729 
1730 	/* We are busy now; tell everyone else to go away */
1731 	nd6_service_busy = TRUE;
1732 	net_update_uptime();
1733 	timenow = net_uptime();
1734 
1735 	/* Iterate and service neighbor cache entries */
1736 	nd6_service_neighbor_cache(ap, timenow);
1737 
1738 	/*
1739 	 * There is lock ordering requirement and rnh_lock
1740 	 * has to be released before acquiring nd6_mutex.
1741 	 */
1742 	lck_mtx_unlock(rnh_lock);
1743 
1744 	/* Iterate and service expired default router */
1745 	nd6_service_expired_default_router(ap, timenow);
1746 
1747 	/* Iterate and service expired route information entries */
1748 	nd6_service_expired_route_info(ap, timenow);
1749 
1750 	/* Iterate and service expired/duplicated IPv6 address */
1751 	nd6_service_ip6_addr(ap, timenow);
1752 
1753 	/* Iterate and service expired IPv6 prefixes */
1754 	nd6_service_expired_prefix(ap, timenow);
1755 
1756 	lck_mtx_lock(rnh_lock);
1757 	/* We're done; let others enter */
1758 	nd6_service_busy = FALSE;
1759 	if (nd6_service_waiters > 0) {
1760 		nd6_service_waiters = 0;
1761 		wakeup(nd6_service_wc);
1762 	}
1763 }
1764 
1765 static int nd6_need_draining = 0;
1766 
1767 void
nd6_drain(void * arg)1768 nd6_drain(void *arg)
1769 {
1770 #pragma unused(arg)
1771 	nd6log2(debug, "%s: draining ND6 entries\n", __func__);
1772 
1773 	lck_mtx_lock(rnh_lock);
1774 	nd6_need_draining = 1;
1775 	nd6_sched_timeout(NULL, NULL);
1776 	lck_mtx_unlock(rnh_lock);
1777 }
1778 
1779 /*
1780  * We use the ``arg'' variable to decide whether or not the timer we're
1781  * running is the fast timer. We do this to reset the nd6_fast_timer_on
1782  * variable so that later we don't end up ignoring a ``fast timer''
1783  * request if the 5 second timer is running (see nd6_sched_timeout).
1784  */
1785 static void
nd6_timeout(void * arg)1786 nd6_timeout(void *arg)
1787 {
1788 	struct nd6svc_arg sarg;
1789 	uint32_t buf;
1790 
1791 	lck_mtx_lock(rnh_lock);
1792 	bzero(&sarg, sizeof(sarg));
1793 	if (nd6_need_draining != 0) {
1794 		nd6_need_draining = 0;
1795 		sarg.draining = 1;
1796 	}
1797 	nd6_service(&sarg);
1798 	nd6log3(debug, "%s: found %u, aging_lazy %u, aging %u, "
1799 	    "sticky %u, killed %u\n", __func__, sarg.found, sarg.aging_lazy,
1800 	    sarg.aging, sarg.sticky, sarg.killed);
1801 	/* re-arm the timer if there's work to do */
1802 	nd6_timeout_run--;
1803 	VERIFY(nd6_timeout_run >= 0 && nd6_timeout_run < 2);
1804 	if (arg == &nd6_fast_timer_on) {
1805 		nd6_fast_timer_on = FALSE;
1806 	}
1807 	if (sarg.aging_lazy > 0 || sarg.aging > 0 || nd6_sched_timeout_want) {
1808 		struct timeval atv, ltv;
1809 		struct timeval *__single leeway;
1810 		int lazy = nd6_prune_lazy;
1811 
1812 		if (sarg.aging > 0 || lazy < 1) {
1813 			atv.tv_usec = 0;
1814 			atv.tv_sec = nd6_prune;
1815 			leeway = NULL;
1816 		} else {
1817 			VERIFY(lazy >= 1);
1818 			atv.tv_usec = 0;
1819 			atv.tv_sec = MAX(nd6_prune, lazy);
1820 			ltv.tv_usec = 0;
1821 			read_frandom(&buf, sizeof(buf));
1822 			ltv.tv_sec = MAX(buf % lazy, 1) * 2;
1823 			leeway = &ltv;
1824 		}
1825 		nd6_sched_timeout(&atv, leeway);
1826 	} else if (nd6_debug) {
1827 		nd6log3(debug, "%s: not rescheduling timer\n", __func__);
1828 	}
1829 	lck_mtx_unlock(rnh_lock);
1830 }
1831 
1832 void
nd6_sched_timeout(struct timeval * atv,struct timeval * ltv)1833 nd6_sched_timeout(struct timeval *atv, struct timeval *ltv)
1834 {
1835 	struct timeval tv;
1836 
1837 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1838 	if (atv == NULL) {
1839 		tv.tv_usec = 0;
1840 		tv.tv_sec = MAX(nd6_prune, 1);
1841 		atv = &tv;
1842 		ltv = NULL;     /* ignore leeway */
1843 	}
1844 	/* see comments on top of this file */
1845 	if (nd6_timeout_run == 0) {
1846 		if (ltv == NULL) {
1847 			nd6log3(debug, "%s: timer scheduled in "
1848 			    "T+%llus.%lluu (demand %d)\n", __func__,
1849 			    (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1850 			    nd6_sched_timeout_want);
1851 			nd6_fast_timer_on = TRUE;
1852 			timeout(nd6_timeout, &nd6_fast_timer_on, tvtohz(atv));
1853 		} else {
1854 			nd6log3(debug, "%s: timer scheduled in "
1855 			    "T+%llus.%lluu with %llus.%lluu leeway "
1856 			    "(demand %d)\n", __func__, (uint64_t)atv->tv_sec,
1857 			    (uint64_t)atv->tv_usec, (uint64_t)ltv->tv_sec,
1858 			    (uint64_t)ltv->tv_usec, nd6_sched_timeout_want);
1859 			nd6_fast_timer_on = FALSE;
1860 			timeout_with_leeway(nd6_timeout, NULL,
1861 			    tvtohz(atv), tvtohz(ltv));
1862 		}
1863 		nd6_timeout_run++;
1864 		nd6_sched_timeout_want = 0;
1865 	} else if (nd6_timeout_run == 1 && ltv == NULL &&
1866 	    nd6_fast_timer_on == FALSE) {
1867 		nd6log3(debug, "%s: fast timer scheduled in "
1868 		    "T+%llus.%lluu (demand %d)\n", __func__,
1869 		    (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1870 		    nd6_sched_timeout_want);
1871 		nd6_fast_timer_on = TRUE;
1872 		nd6_sched_timeout_want = 0;
1873 		nd6_timeout_run++;
1874 		timeout(nd6_timeout, &nd6_fast_timer_on, tvtohz(atv));
1875 	} else {
1876 		if (ltv == NULL) {
1877 			nd6log3(debug, "%s: not scheduling timer: "
1878 			    "timers %d, fast_timer %d, T+%llus.%lluu\n",
1879 			    __func__, nd6_timeout_run, nd6_fast_timer_on,
1880 			    (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec);
1881 		} else {
1882 			nd6log3(debug, "%s: not scheduling timer: "
1883 			    "timers %d, fast_timer %d, T+%llus.%lluu "
1884 			    "with %llus.%lluu leeway\n", __func__,
1885 			    nd6_timeout_run, nd6_fast_timer_on,
1886 			    (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1887 			    (uint64_t)ltv->tv_sec, (uint64_t)ltv->tv_usec);
1888 		}
1889 	}
1890 }
1891 
1892 /*
1893  * ND6 router advertisement kernel notification
1894  */
1895 void
nd6_post_msg(u_int32_t code,struct nd_prefix_list * prefix_list,u_int32_t list_length,u_int32_t mtu)1896 nd6_post_msg(u_int32_t code, struct nd_prefix_list *prefix_list,
1897     u_int32_t list_length, u_int32_t mtu)
1898 {
1899 	struct kev_msg ev_msg;
1900 	struct kev_nd6_ra_data nd6_ra_msg_data;
1901 	struct nd_prefix_list *__single itr = prefix_list;
1902 
1903 	bzero(&ev_msg, sizeof(struct kev_msg));
1904 	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
1905 	ev_msg.kev_class        = KEV_NETWORK_CLASS;
1906 	ev_msg.kev_subclass     = KEV_ND6_SUBCLASS;
1907 	ev_msg.event_code       = code;
1908 
1909 	bzero(&nd6_ra_msg_data, sizeof(nd6_ra_msg_data));
1910 
1911 	if (mtu > 0 && mtu >= IPV6_MMTU) {
1912 		nd6_ra_msg_data.mtu = mtu;
1913 		nd6_ra_msg_data.flags |= KEV_ND6_DATA_VALID_MTU;
1914 	}
1915 
1916 	if (list_length > 0 && prefix_list != NULL) {
1917 		nd6_ra_msg_data.list_length = list_length;
1918 		nd6_ra_msg_data.flags |= KEV_ND6_DATA_VALID_PREFIX;
1919 	}
1920 
1921 	while (itr != NULL && nd6_ra_msg_data.list_index < list_length) {
1922 		SOCKADDR_COPY(&itr->pr.ndpr_prefix, &nd6_ra_msg_data.prefix.prefix,
1923 		    sizeof(nd6_ra_msg_data.prefix.prefix));
1924 		nd6_ra_msg_data.prefix.raflags = itr->pr.ndpr_raf;
1925 		nd6_ra_msg_data.prefix.prefixlen = itr->pr.ndpr_plen;
1926 		nd6_ra_msg_data.prefix.origin = PR_ORIG_RA;
1927 		nd6_ra_msg_data.prefix.vltime = itr->pr.ndpr_vltime;
1928 		nd6_ra_msg_data.prefix.pltime = itr->pr.ndpr_pltime;
1929 		nd6_ra_msg_data.prefix.expire = ndpr_getexpire(&itr->pr);
1930 		nd6_ra_msg_data.prefix.flags = itr->pr.ndpr_stateflags;
1931 		nd6_ra_msg_data.prefix.refcnt = itr->pr.ndpr_addrcnt;
1932 		nd6_ra_msg_data.prefix.if_index = itr->pr.ndpr_ifp->if_index;
1933 
1934 		/* send the message up */
1935 		ev_msg.dv[0].data_ptr           = &nd6_ra_msg_data;
1936 		ev_msg.dv[0].data_length        = sizeof(nd6_ra_msg_data);
1937 		ev_msg.dv[1].data_length        = 0;
1938 		dlil_post_complete_msg(NULL, &ev_msg);
1939 
1940 		/* clean up for the next prefix */
1941 		bzero(&nd6_ra_msg_data.prefix, sizeof(nd6_ra_msg_data.prefix));
1942 		itr = itr->next;
1943 		nd6_ra_msg_data.list_index++;
1944 	}
1945 }
1946 
1947 /*
1948  * Regenerate deprecated/invalidated temporary address
1949  */
1950 static int
regen_tmpaddr(struct in6_ifaddr * ia6)1951 regen_tmpaddr(struct in6_ifaddr *ia6)
1952 {
1953 	struct ifaddr *__single ifa;
1954 	ifnet_ref_t ifp;
1955 	struct in6_ifaddr *__single public_ifa6 = NULL;
1956 	uint64_t timenow = net_uptime();
1957 
1958 	ifp = ia6->ia_ifa.ifa_ifp;
1959 	ifnet_lock_shared(ifp);
1960 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1961 		struct in6_ifaddr *__single it6;
1962 
1963 		IFA_LOCK(ifa);
1964 		if (ifa->ifa_addr->sa_family != AF_INET6) {
1965 			IFA_UNLOCK(ifa);
1966 			continue;
1967 		}
1968 		it6 = ifatoia6(ifa);
1969 
1970 		/* ignore no autoconf addresses. */
1971 		if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0) {
1972 			IFA_UNLOCK(ifa);
1973 			continue;
1974 		}
1975 		/* ignore autoconf addresses with different prefixes. */
1976 		if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr) {
1977 			IFA_UNLOCK(ifa);
1978 			continue;
1979 		}
1980 		/*
1981 		 * Now we are looking at an autoconf address with the same
1982 		 * prefix as ours.  If the address is temporary and is still
1983 		 * preferred, do not create another one.  It would be rare, but
1984 		 * could happen, for example, when we resume a laptop PC after
1985 		 * a long period.
1986 		 */
1987 		if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1988 		    !IFA6_IS_DEPRECATED(it6, timenow)) {
1989 			IFA_UNLOCK(ifa);
1990 			if (public_ifa6 != NULL) {
1991 				ifa_remref(&public_ifa6->ia_ifa);
1992 			}
1993 			public_ifa6 = NULL;
1994 			break;
1995 		}
1996 
1997 		/*
1998 		 * This is a public autoconf address that has the same prefix
1999 		 * as ours.  If it is preferred, keep it.  We can't break the
2000 		 * loop here, because there may be a still-preferred temporary
2001 		 * address with the prefix.
2002 		 */
2003 		if (!IFA6_IS_DEPRECATED(it6, timenow)) {
2004 			ifa_addref(ifa); /* for public_ifa6 */
2005 			IFA_UNLOCK(ifa);
2006 			if (public_ifa6 != NULL) {
2007 				ifa_remref(&public_ifa6->ia_ifa);
2008 			}
2009 			public_ifa6 = it6;
2010 		} else {
2011 			IFA_UNLOCK(ifa);
2012 		}
2013 	}
2014 	ifnet_lock_done(ifp);
2015 
2016 	if (public_ifa6 != NULL) {
2017 		int e;
2018 
2019 		if ((e = in6_tmpifadd(public_ifa6, 0)) != 0) {
2020 			log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
2021 			    " tmp addr,errno=%d\n", e);
2022 			ifa_remref(&public_ifa6->ia_ifa);
2023 			return -1;
2024 		}
2025 		ifa_remref(&public_ifa6->ia_ifa);
2026 		return 0;
2027 	}
2028 
2029 	return -1;
2030 }
2031 
2032 static void
nd6_purge_interface_default_routers(struct ifnet * ifp)2033 nd6_purge_interface_default_routers(struct ifnet *ifp)
2034 {
2035 	struct nd_defrouter *__single dr = NULL;
2036 	struct nd_defrouter *__single ndr = NULL;
2037 	struct nd_drhead nd_defrouter_tmp = {};
2038 
2039 	TAILQ_INIT(&nd_defrouter_tmp);
2040 
2041 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2042 
2043 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter_list, dr_entry, ndr) {
2044 		if (dr->ifp != ifp) {
2045 			continue;
2046 		}
2047 		/*
2048 		 * Remove the entry from default router list
2049 		 * and add it to the temp list.
2050 		 * nd_defrouter_tmp will be a local temporary
2051 		 * list as no one else can get the same
2052 		 * removed entry once it is removed from default
2053 		 * router list.
2054 		 * Remove the reference after calling defrtrlist_del.
2055 		 *
2056 		 * The uninstalled entries have to be iterated first
2057 		 * when we call defrtrlist_del.
2058 		 * This is to ensure that we don't end up calling
2059 		 * default router  selection when there are other
2060 		 * uninstalled candidate default routers on
2061 		 * the interface.
2062 		 * If we don't respect that order, we may end
2063 		 * up missing out on some entries.
2064 		 *
2065 		 * For that reason, installed ones must be inserted
2066 		 * at the tail and uninstalled ones at the head
2067 		 */
2068 		TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
2069 
2070 		if (dr->stateflags & NDDRF_INSTALLED) {
2071 			TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
2072 		} else {
2073 			TAILQ_INSERT_HEAD(&nd_defrouter_tmp, dr, dr_entry);
2074 		}
2075 	}
2076 
2077 	/*
2078 	 * The following call to defrtrlist_del should be
2079 	 * safe as we are iterating a local list of
2080 	 * default routers.
2081 	 *
2082 	 * We don't really need nd6_mutex here but keeping
2083 	 * it as it is to avoid changing assertions held in
2084 	 * the functions in the call-path.
2085 	 */
2086 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter_tmp, dr_entry, ndr) {
2087 		TAILQ_REMOVE(&nd_defrouter_tmp, dr, dr_entry);
2088 		defrtrlist_del(dr, NULL);
2089 		NDDR_REMREF(dr);        /* remove list reference */
2090 	}
2091 }
2092 
2093 static void
nd6_purge_interface_prefixes(struct ifnet * ifp)2094 nd6_purge_interface_prefixes(struct ifnet *ifp)
2095 {
2096 	boolean_t removed = FALSE;
2097 	struct nd_prefix *__single pr = NULL;
2098 	struct nd_prefix *__single npr = NULL;
2099 
2100 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2101 
2102 	/* Nuke prefix list entries toward ifp */
2103 	for (pr = nd_prefix.lh_first; pr; pr = npr) {
2104 		NDPR_LOCK(pr);
2105 		npr = pr->ndpr_next;
2106 		if (pr->ndpr_ifp == ifp &&
2107 		    !(pr->ndpr_stateflags & NDPRF_DEFUNCT)) {
2108 			/*
2109 			 * Because if_detach() does *not* release prefixes
2110 			 * while purging addresses the reference count will
2111 			 * still be above zero. We therefore reset it to
2112 			 * make sure that the prefix really gets purged.
2113 			 */
2114 			pr->ndpr_addrcnt = 0;
2115 
2116 			/*
2117 			 * Previously, pr->ndpr_addr is removed as well,
2118 			 * but I strongly believe we don't have to do it.
2119 			 * nd6_purge() is only called from in6_ifdetach(),
2120 			 * which removes all the associated interface addresses
2121 			 * by itself.
2122 			 * ([email protected] 20010129)
2123 			 */
2124 			NDPR_ADDREF(pr);
2125 			prelist_remove(pr);
2126 			NDPR_UNLOCK(pr);
2127 			NDPR_REMREF(pr);
2128 			removed = TRUE;
2129 			npr = nd_prefix.lh_first;
2130 		} else {
2131 			NDPR_UNLOCK(pr);
2132 		}
2133 	}
2134 	if (removed) {
2135 		pfxlist_onlink_check();
2136 	}
2137 }
2138 
2139 static void
nd6_router_select_rti_entries(struct ifnet * ifp)2140 nd6_router_select_rti_entries(struct ifnet *ifp)
2141 {
2142 	struct nd_route_info *__single rti = NULL;
2143 	struct nd_route_info *__single rti_next = NULL;
2144 
2145 	nd6_rti_list_wait(__func__);
2146 
2147 	TAILQ_FOREACH_SAFE(rti, &nd_rti_list, nd_rti_entry, rti_next) {
2148 		defrouter_select(ifp, &rti->nd_rti_router_list);
2149 	}
2150 
2151 	nd6_rti_list_signal_done();
2152 }
2153 
2154 static void
nd6_purge_interface_rti_entries(struct ifnet * ifp)2155 nd6_purge_interface_rti_entries(struct ifnet *ifp)
2156 {
2157 	struct nd_route_info *__single rti = NULL;
2158 	struct nd_route_info *__single rti_next = NULL;
2159 
2160 	nd6_rti_list_wait(__func__);
2161 
2162 	TAILQ_FOREACH_SAFE(rti, &nd_rti_list, nd_rti_entry, rti_next) {
2163 		struct nd_route_info rti_tmp = {};
2164 		struct nd_defrouter *__single dr = NULL;
2165 		struct nd_defrouter *__single ndr = NULL;
2166 
2167 		rti_tmp.nd_rti_prefix = rti->nd_rti_prefix;
2168 		rti_tmp.nd_rti_prefixlen = rti->nd_rti_prefixlen;
2169 		TAILQ_INIT(&rti_tmp.nd_rti_router_list);
2170 
2171 		TAILQ_FOREACH_SAFE(dr, &rti->nd_rti_router_list, dr_entry, ndr) {
2172 			/*
2173 			 * If ifp is provided, skip the entries that don't match.
2174 			 * Else it is treated as a purge.
2175 			 */
2176 			if (ifp != NULL && dr->ifp != ifp) {
2177 				continue;
2178 			}
2179 
2180 			/*
2181 			 * Remove the entry from rti's router list
2182 			 * and add it to the temp list.
2183 			 * Remove the reference after calling defrtrlist_del.
2184 			 *
2185 			 * The uninstalled entries have to be iterated first
2186 			 * when we call defrtrlist_del.
2187 			 * This is to ensure that we don't end up calling
2188 			 * router  selection when there are other
2189 			 * uninstalled candidate default routers on
2190 			 * the interface.
2191 			 * If we don't respect that order, we may end
2192 			 * up missing out on some entries.
2193 			 *
2194 			 * For that reason, installed ones must be inserted
2195 			 * at the tail and uninstalled ones at the head
2196 			 */
2197 
2198 			TAILQ_REMOVE(&rti->nd_rti_router_list, dr, dr_entry);
2199 			if (dr->stateflags & NDDRF_INSTALLED) {
2200 				TAILQ_INSERT_TAIL(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2201 			} else {
2202 				TAILQ_INSERT_HEAD(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2203 			}
2204 		}
2205 
2206 		/*
2207 		 * The following call to defrtrlist_del should be
2208 		 * safe as we are iterating a local list of
2209 		 * routers.
2210 		 *
2211 		 * We don't really need nd6_mutex here but keeping
2212 		 * it as it is to avoid changing assertions held in
2213 		 * the functions in the call-path.
2214 		 */
2215 		TAILQ_FOREACH_SAFE(dr, &rti_tmp.nd_rti_router_list, dr_entry, ndr) {
2216 			TAILQ_REMOVE(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2217 			defrtrlist_del(dr, &rti->nd_rti_router_list);
2218 			NDDR_REMREF(dr);        /* remove list reference */
2219 		}
2220 		/*
2221 		 * The above may have removed an entry from default router list.
2222 		 * If it did and the list is now empty, remove the rti as well.
2223 		 */
2224 		if (TAILQ_EMPTY(&rti->nd_rti_router_list)) {
2225 			TAILQ_REMOVE(&nd_rti_list, rti, nd_rti_entry);
2226 			ndrti_free(rti);
2227 		}
2228 	}
2229 
2230 	nd6_rti_list_signal_done();
2231 }
2232 
2233 static void
nd6_purge_interface_llinfo(struct ifnet * ifp)2234 nd6_purge_interface_llinfo(struct ifnet *ifp)
2235 {
2236 	struct llinfo_nd6 *__single ln = NULL;
2237 	/* Note that rt->rt_ifp may not be the same as ifp,
2238 	 * due to KAME goto ours hack.  See RTM_RESOLVE case in
2239 	 * nd6_rtrequest(), and ip6_input().
2240 	 */
2241 again:
2242 	lck_mtx_lock(rnh_lock);
2243 	ln = llinfo_nd6.ln_next;
2244 	while (ln != NULL && ln != &llinfo_nd6) {
2245 		rtentry_ref_t rt;
2246 		struct llinfo_nd6 *__single nln;
2247 
2248 		nln = ln->ln_next;
2249 		rt = ln->ln_rt;
2250 		RT_LOCK(rt);
2251 		if (rt->rt_gateway != NULL &&
2252 		    rt->rt_gateway->sa_family == AF_LINK &&
2253 		    SDL(rt->rt_gateway)->sdl_index == ifp->if_index) {
2254 			RT_ADDREF_LOCKED(rt);
2255 			RT_UNLOCK(rt);
2256 			lck_mtx_unlock(rnh_lock);
2257 			/*
2258 			 * See comments on nd6_service() for reasons why
2259 			 * this loop is repeated; we bite the costs of
2260 			 * going thru the same llinfo_nd6 more than once
2261 			 * here, since this purge happens during detach,
2262 			 * and that unlike the timer case, it's possible
2263 			 * there's more than one purges happening at the
2264 			 * same time (thus a flag wouldn't buy anything).
2265 			 */
2266 			nd6_free(rt);
2267 			RT_REMREF(rt);
2268 			LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2269 			goto again;
2270 		} else {
2271 			RT_UNLOCK(rt);
2272 		}
2273 		ln = nln;
2274 	}
2275 	lck_mtx_unlock(rnh_lock);
2276 }
2277 
2278 /*
2279  * Nuke neighbor cache/prefix/default router management table, right before
2280  * ifp goes away.
2281  */
2282 void
nd6_purge(struct ifnet * ifp)2283 nd6_purge(struct ifnet *ifp)
2284 {
2285 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2286 	lck_mtx_lock(nd6_mutex);
2287 
2288 	/* Nuke default router list entries toward ifp */
2289 	nd6_purge_interface_default_routers(ifp);
2290 
2291 	/* Nuke prefix list entries toward ifp */
2292 	nd6_purge_interface_prefixes(ifp);
2293 
2294 	/* Nuke route info option entries toward ifp */
2295 	nd6_purge_interface_rti_entries(ifp);
2296 
2297 	lck_mtx_unlock(nd6_mutex);
2298 
2299 	/* cancel default outgoing interface setting */
2300 	if (nd6_defifindex == ifp->if_index) {
2301 		nd6_setdefaultiface(0);
2302 	}
2303 
2304 	/*
2305 	 * Perform default router selection even when we are a router,
2306 	 * if Scoped Routing is enabled.
2307 	 * XXX ?Should really not be needed since when defrouter_select
2308 	 * was changed to work on interface.
2309 	 */
2310 	lck_mtx_lock(nd6_mutex);
2311 	/* refresh default router list */
2312 	defrouter_select(ifp, NULL);
2313 	lck_mtx_unlock(nd6_mutex);
2314 
2315 	/* Nuke neighbor cache entries for the ifp. */
2316 	nd6_purge_interface_llinfo(ifp);
2317 }
2318 
2319 /*
2320  * Upon success, the returned route will be locked and the caller is
2321  * responsible for releasing the reference and doing RT_UNLOCK(rt).
2322  * This routine does not require rnh_lock to be held by the caller,
2323  * although it needs to be indicated of such a case in order to call
2324  * the correct variant of the relevant routing routines.
2325  */
2326 struct rtentry *
nd6_lookup(struct in6_addr * addr6,int create,struct ifnet * ifp,int rt_locked)2327 nd6_lookup(struct in6_addr *addr6, int create, struct ifnet *ifp, int rt_locked)
2328 {
2329 	rtentry_ref_t rt;
2330 	struct sockaddr_in6 sin6;
2331 	unsigned int ifscope;
2332 
2333 	SOCKADDR_ZERO(&sin6, sizeof(sin6));
2334 	sin6.sin6_len = sizeof(struct sockaddr_in6);
2335 	sin6.sin6_family = AF_INET6;
2336 	sin6.sin6_addr = *addr6;
2337 
2338 	ifscope = (ifp != NULL) ? ifp->if_index : IFSCOPE_NONE;
2339 	if (rt_locked) {
2340 		LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2341 		rt = rtalloc1_scoped_locked(SA(&sin6), create, 0, ifscope);
2342 	} else {
2343 		rt = rtalloc1_scoped(SA(&sin6), create, 0, ifscope);
2344 	}
2345 
2346 	if (rt != NULL) {
2347 		RT_LOCK(rt);
2348 		if ((rt->rt_flags & RTF_LLINFO) == 0) {
2349 			/*
2350 			 * This is the case for the default route.
2351 			 * If we want to create a neighbor cache for the
2352 			 * address, we should free the route for the
2353 			 * destination and allocate an interface route.
2354 			 */
2355 			if (create) {
2356 				RT_UNLOCK(rt);
2357 				if (rt_locked) {
2358 					rtfree_locked(rt);
2359 				} else {
2360 					rtfree(rt);
2361 				}
2362 				rt = NULL;
2363 			}
2364 		}
2365 	}
2366 	if (rt == NULL) {
2367 		if (create && ifp) {
2368 			struct ifaddr *__single ifa;
2369 			u_int32_t ifa_flags;
2370 			int e;
2371 
2372 			/*
2373 			 * If no route is available and create is set,
2374 			 * we allocate a host route for the destination
2375 			 * and treat it like an interface route.
2376 			 * This hack is necessary for a neighbor which can't
2377 			 * be covered by our own prefix.
2378 			 */
2379 			ifa = ifaof_ifpforaddr(SA(&sin6), ifp);
2380 			if (ifa == NULL) {
2381 				return NULL;
2382 			}
2383 
2384 			/*
2385 			 * Create a new route.  RTF_LLINFO is necessary
2386 			 * to create a Neighbor Cache entry for the
2387 			 * destination in nd6_rtrequest which will be
2388 			 * called in rtrequest via ifa->ifa_rtrequest.
2389 			 */
2390 			if (!rt_locked) {
2391 				lck_mtx_lock(rnh_lock);
2392 			}
2393 			IFA_LOCK_SPIN(ifa);
2394 			ifa_flags = ifa->ifa_flags;
2395 			IFA_UNLOCK(ifa);
2396 			e = rtrequest_scoped_locked(RTM_ADD, SA(&sin6), ifa->ifa_addr, SA(&all1_sa),
2397 			    (ifa_flags | RTF_HOST | RTF_LLINFO) & ~RTF_CLONING, &rt, ifscope);
2398 			if (e != 0) {
2399 				if (e != EEXIST) {
2400 					log(LOG_ERR, "%s: failed to add route "
2401 					    "for a neighbor(%s), errno=%d\n",
2402 					    __func__, ip6_sprintf(addr6), e);
2403 				}
2404 			}
2405 			if (!rt_locked) {
2406 				lck_mtx_unlock(rnh_lock);
2407 			}
2408 			ifa_remref(ifa);
2409 			if (rt == NULL) {
2410 				return NULL;
2411 			}
2412 
2413 			RT_LOCK(rt);
2414 			if (rt->rt_llinfo) {
2415 				struct llinfo_nd6 *__single ln = rt->rt_llinfo;
2416 				boolean_t nud_enabled = FALSE;
2417 
2418 				/*
2419 				 * The IPv6 initialization of the loopback interface
2420 				 * may happen after another interface gets assigned
2421 				 * an IPv6 address.
2422 				 * To avoid asserting treat local routes as special
2423 				 * case.
2424 				 */
2425 				if (rt->rt_ifp != lo_ifp) {
2426 					struct nd_ifinfo *__single ndi = ND_IFINFO(rt->rt_ifp);
2427 					VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2428 					nud_enabled = !!(ndi->flags & ND6_IFF_PERFORMNUD);
2429 				}
2430 
2431 				/*
2432 				 * For interface's that do not perform NUD
2433 				 * neighbor cache entres must always be marked
2434 				 * reachable with no expiry
2435 				 */
2436 				if (nud_enabled) {
2437 					ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_NOSTATE);
2438 				} else {
2439 					ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2440 					ln_setexpire(ln, 0);
2441 				}
2442 			}
2443 		} else {
2444 			return NULL;
2445 		}
2446 	}
2447 	RT_LOCK_ASSERT_HELD(rt);
2448 	/*
2449 	 * Validation for the entry.
2450 	 * Note that the check for rt_llinfo is necessary because a cloned
2451 	 * route from a parent route that has the L flag (e.g. the default
2452 	 * route to a p2p interface) may have the flag, too, while the
2453 	 * destination is not actually a neighbor.
2454 	 * XXX: we can't use rt->rt_ifp to check for the interface, since
2455 	 *	it might be the loopback interface if the entry is for our
2456 	 *	own address on a non-loopback interface. Instead, we should
2457 	 *	use rt->rt_ifa->ifa_ifp, which would specify the REAL
2458 	 *	interface.
2459 	 * Note also that ifa_ifp and ifp may differ when we connect two
2460 	 * interfaces to a same link, install a link prefix to an interface,
2461 	 * and try to install a neighbor cache on an interface that does not
2462 	 * have a route to the prefix.
2463 	 *
2464 	 * If the address is from a proxied prefix, the ifa_ifp and ifp might
2465 	 * not match, because nd6_na_input() could have modified the ifp
2466 	 * of the route to point to the interface where the NA arrived on,
2467 	 * hence the test for RTF_PROXY.
2468 	 */
2469 	if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
2470 	    rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
2471 	    (ifp && rt->rt_ifa->ifa_ifp != ifp &&
2472 	    !(rt->rt_flags & RTF_PROXY))) {
2473 		RT_REMREF_LOCKED(rt);
2474 		RT_UNLOCK(rt);
2475 		if (create) {
2476 			log(LOG_DEBUG, "%s: failed to lookup %s "
2477 			    "(if = %s)\n", __func__, ip6_sprintf(addr6),
2478 			    ifp ? if_name(ifp) : "unspec");
2479 			/* xxx more logs... kazu */
2480 		}
2481 		return NULL;
2482 	}
2483 	/*
2484 	 * Caller needs to release reference and call RT_UNLOCK(rt).
2485 	 */
2486 	return rt;
2487 }
2488 
2489 /*
2490  * Test whether a given IPv6 address is a neighbor or not, ignoring
2491  * the actual neighbor cache.  The neighbor cache is ignored in order
2492  * to not reenter the routing code from within itself.
2493  */
2494 static int
nd6_is_new_addr_neighbor(struct sockaddr_in6 * addr,struct ifnet * ifp)2495 nd6_is_new_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
2496 {
2497 	struct nd_prefix *__single pr;
2498 	struct ifaddr *__single dstaddr;
2499 
2500 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2501 
2502 	/*
2503 	 * A link-local address is always a neighbor.
2504 	 * XXX: a link does not necessarily specify a single interface.
2505 	 */
2506 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
2507 		struct sockaddr_in6 sin6_copy;
2508 		u_int32_t zone;
2509 
2510 		/*
2511 		 * We need sin6_copy since sa6_recoverscope() may modify the
2512 		 * content (XXX).
2513 		 */
2514 		sin6_copy = *addr;
2515 		if (sa6_recoverscope(&sin6_copy, FALSE)) {
2516 			return 0; /* XXX: should be impossible */
2517 		}
2518 		if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone)) {
2519 			return 0;
2520 		}
2521 		if (sin6_copy.sin6_scope_id == zone) {
2522 			return 1;
2523 		} else {
2524 			return 0;
2525 		}
2526 	}
2527 
2528 	/*
2529 	 * If the address matches one of our addresses,
2530 	 * it should be a neighbor.
2531 	 * If the address matches one of our on-link prefixes, it should be a
2532 	 * neighbor.
2533 	 */
2534 	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
2535 		NDPR_LOCK(pr);
2536 		if (pr->ndpr_ifp != ifp) {
2537 			NDPR_UNLOCK(pr);
2538 			continue;
2539 		}
2540 		if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
2541 			NDPR_UNLOCK(pr);
2542 			continue;
2543 		}
2544 		if (in6_are_masked_addr_scope_equal(&pr->ndpr_prefix.sin6_addr, pr->ndpr_prefix.sin6_scope_id,
2545 		    &addr->sin6_addr, addr->sin6_scope_id, &pr->ndpr_mask)) {
2546 			NDPR_UNLOCK(pr);
2547 			return 1;
2548 		}
2549 		NDPR_UNLOCK(pr);
2550 	}
2551 
2552 	/*
2553 	 * If the address is assigned on the node of the other side of
2554 	 * a p2p interface, the address should be a neighbor.
2555 	 */
2556 	dstaddr = ifa_ifwithdstaddr(SA(addr));
2557 	if (dstaddr != NULL) {
2558 		if (dstaddr->ifa_ifp == ifp) {
2559 			ifa_remref(dstaddr);
2560 			return 1;
2561 		}
2562 		ifa_remref(dstaddr);
2563 		dstaddr = NULL;
2564 	}
2565 
2566 	return 0;
2567 }
2568 
2569 
2570 /*
2571  * Detect if a given IPv6 address identifies a neighbor on a given link.
2572  * XXX: should take care of the destination of a p2p link?
2573  */
2574 int
nd6_is_addr_neighbor(struct sockaddr_in6 * addr,struct ifnet * ifp,int rt_locked)2575 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp,
2576     int rt_locked)
2577 {
2578 	rtentry_ref_t rt;
2579 
2580 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2581 	lck_mtx_lock(nd6_mutex);
2582 	if (nd6_is_new_addr_neighbor(addr, ifp)) {
2583 		lck_mtx_unlock(nd6_mutex);
2584 		return 1;
2585 	}
2586 	lck_mtx_unlock(nd6_mutex);
2587 
2588 	/*
2589 	 * Even if the address matches none of our addresses, it might be
2590 	 * in the neighbor cache.
2591 	 */
2592 	if ((rt = nd6_lookup(&addr->sin6_addr, 0, ifp, rt_locked)) != NULL) {
2593 		RT_LOCK_ASSERT_HELD(rt);
2594 		RT_REMREF_LOCKED(rt);
2595 		RT_UNLOCK(rt);
2596 		return 1;
2597 	}
2598 
2599 	return 0;
2600 }
2601 
2602 /*
2603  * Free an nd6 llinfo entry.
2604  * Since the function would cause significant changes in the kernel, DO NOT
2605  * make it global, unless you have a strong reason for the change, and are sure
2606  * that the change is safe.
2607  */
2608 void
nd6_free(struct rtentry * rt)2609 nd6_free(struct rtentry *rt)
2610 {
2611 	struct llinfo_nd6 *__single ln = NULL;
2612 	struct in6_addr in6 = {};
2613 	struct nd_defrouter *__single dr = NULL;
2614 
2615 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2616 	RT_LOCK_ASSERT_NOTHELD(rt);
2617 	lck_mtx_lock(nd6_mutex);
2618 
2619 	RT_LOCK(rt);
2620 	RT_ADDREF_LOCKED(rt);   /* Extra ref */
2621 	ln = rt->rt_llinfo;
2622 	in6 = SIN6(rt_key(rt))->sin6_addr;
2623 
2624 	/*
2625 	 * Prevent another thread from modifying rt_key, rt_gateway
2626 	 * via rt_setgate() after the rt_lock is dropped by marking
2627 	 * the route as defunct.
2628 	 */
2629 	rt->rt_flags |= RTF_CONDEMNED;
2630 
2631 	/*
2632 	 * We used to have pfctlinput(PRC_HOSTDEAD) here.  Even though it is
2633 	 * not harmful, it was not really necessary.  Perform default router
2634 	 * selection even when we are a router, if Scoped Routing is enabled.
2635 	 */
2636 	/* XXX TDB Handle lists in route information option as well */
2637 	dr = defrouter_lookup(NULL, &SIN6(rt_key(rt))->sin6_addr, rt->rt_ifp);
2638 
2639 	if ((ln && ln->ln_router) || dr) {
2640 		/*
2641 		 * rt6_flush must be called whether or not the neighbor
2642 		 * is in the Default Router List.
2643 		 * See a corresponding comment in nd6_na_input().
2644 		 */
2645 		RT_UNLOCK(rt);
2646 		lck_mtx_unlock(nd6_mutex);
2647 		rt6_flush(&in6, rt->rt_ifp);
2648 		lck_mtx_lock(nd6_mutex);
2649 	} else {
2650 		RT_UNLOCK(rt);
2651 	}
2652 
2653 	if (dr) {
2654 		NDDR_REMREF(dr);
2655 		/*
2656 		 * Unreachablity of a router might affect the default
2657 		 * router selection and on-link detection of advertised
2658 		 * prefixes.
2659 		 */
2660 
2661 		/*
2662 		 * Temporarily fake the state to choose a new default
2663 		 * router and to perform on-link determination of
2664 		 * prefixes correctly.
2665 		 * Below the state will be set correctly,
2666 		 * or the entry itself will be deleted.
2667 		 */
2668 		RT_LOCK_SPIN(rt);
2669 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_INCOMPLETE);
2670 
2671 		/*
2672 		 * Since defrouter_select() does not affect the
2673 		 * on-link determination and MIP6 needs the check
2674 		 * before the default router selection, we perform
2675 		 * the check now.
2676 		 */
2677 		RT_UNLOCK(rt);
2678 		pfxlist_onlink_check();
2679 
2680 		/*
2681 		 * refresh default router list
2682 		 */
2683 		defrouter_select(rt->rt_ifp, NULL);
2684 
2685 		/* Loop through all RTI's as well and trigger router selection. */
2686 		nd6_router_select_rti_entries(rt->rt_ifp);
2687 	}
2688 	RT_LOCK_ASSERT_NOTHELD(rt);
2689 	lck_mtx_unlock(nd6_mutex);
2690 	/*
2691 	 * Detach the route from the routing tree and the list of neighbor
2692 	 * caches, and disable the route entry not to be used in already
2693 	 * cached routes.
2694 	 */
2695 	(void) rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt), 0, NULL);
2696 
2697 	/* Extra ref held above; now free it */
2698 	rtfree(rt);
2699 }
2700 
2701 void
nd6_rtrequest(int req,struct rtentry * rt,struct sockaddr * sa)2702 nd6_rtrequest(int req, struct rtentry *rt, struct sockaddr *sa)
2703 {
2704 #pragma unused(sa)
2705 	struct sockaddr *gate = rt->rt_gateway;
2706 	struct llinfo_nd6 *__single ln = rt->rt_llinfo;
2707 	static struct sockaddr_dl null_sdl =
2708 	{ .sdl_len = sizeof(null_sdl), .sdl_family = AF_LINK };
2709 	ifnet_ref_t ifp = rt->rt_ifp;
2710 	struct ifaddr *__single ifa;
2711 	uint64_t timenow;
2712 	char buf[MAX_IPv6_STR_LEN];
2713 	boolean_t nud_enabled = FALSE;
2714 
2715 	/*
2716 	 * The IPv6 initialization of the loopback interface
2717 	 * may happen after another interface gets assigned
2718 	 * an IPv6 address.
2719 	 * To avoid asserting treat local routes as special
2720 	 * case.
2721 	 */
2722 	if (rt->rt_ifp != lo_ifp) {
2723 		struct nd_ifinfo *__single ndi = ND_IFINFO(rt->rt_ifp);
2724 		VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2725 		nud_enabled = !!(ndi->flags & ND6_IFF_PERFORMNUD);
2726 	}
2727 
2728 	VERIFY(nd6_init_done);
2729 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2730 	RT_LOCK_ASSERT_HELD(rt);
2731 
2732 	/*
2733 	 * We have rnh_lock held, see if we need to schedule the timer;
2734 	 * we might do this again below during RTM_RESOLVE, but doing it
2735 	 * now handles all other cases.
2736 	 */
2737 	if (nd6_sched_timeout_want) {
2738 		nd6_sched_timeout(NULL, NULL);
2739 	}
2740 
2741 	if (rt->rt_flags & RTF_GATEWAY) {
2742 		return;
2743 	}
2744 
2745 	if (!nd6_need_cache(ifp) && !(rt->rt_flags & RTF_HOST)) {
2746 		/*
2747 		 * This is probably an interface direct route for a link
2748 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
2749 		 * We do not need special treatment below for such a route.
2750 		 * Moreover, the RTF_LLINFO flag which would be set below
2751 		 * would annoy the ndp(8) command.
2752 		 */
2753 		return;
2754 	}
2755 
2756 	if (req == RTM_RESOLVE) {
2757 		int no_nd_cache;
2758 
2759 		if (!nd6_need_cache(ifp)) {     /* stf case */
2760 			no_nd_cache = 1;
2761 		} else {
2762 			struct sockaddr_in6 sin6;
2763 
2764 			rtkey_to_sa6(rt, &sin6);
2765 			/*
2766 			 * nd6_is_addr_neighbor() may call nd6_lookup(),
2767 			 * therefore we drop rt_lock to avoid deadlock
2768 			 * during the lookup.
2769 			 */
2770 			RT_ADDREF_LOCKED(rt);
2771 			RT_UNLOCK(rt);
2772 			no_nd_cache = !nd6_is_addr_neighbor(&sin6, ifp, 1);
2773 			RT_LOCK(rt);
2774 			RT_REMREF_LOCKED(rt);
2775 		}
2776 
2777 		/*
2778 		 * FreeBSD and BSD/OS often make a cloned host route based
2779 		 * on a less-specific route (e.g. the default route).
2780 		 * If the less specific route does not have a "gateway"
2781 		 * (this is the case when the route just goes to a p2p or an
2782 		 * stf interface), we'll mistakenly make a neighbor cache for
2783 		 * the host route, and will see strange neighbor solicitation
2784 		 * for the corresponding destination.  In order to avoid the
2785 		 * confusion, we check if the destination of the route is
2786 		 * a neighbor in terms of neighbor discovery, and stop the
2787 		 * process if not.  Additionally, we remove the LLINFO flag
2788 		 * so that ndp(8) will not try to get the neighbor information
2789 		 * of the destination.
2790 		 */
2791 		if (no_nd_cache) {
2792 			rt->rt_flags &= ~RTF_LLINFO;
2793 			return;
2794 		}
2795 	}
2796 
2797 	timenow = net_uptime();
2798 
2799 	switch (req) {
2800 	case RTM_ADD:
2801 		/*
2802 		 * There is no backward compatibility :)
2803 		 *
2804 		 * if ((rt->rt_flags & RTF_HOST) == 0 &&
2805 		 *      SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
2806 		 *              rt->rt_flags |= RTF_CLONING;
2807 		 */
2808 		if ((rt->rt_flags & RTF_CLONING) ||
2809 		    ((rt->rt_flags & RTF_LLINFO) && ln == NULL)) {
2810 			/*
2811 			 * Case 1: This route should come from a route to
2812 			 * interface (RTF_CLONING case) or the route should be
2813 			 * treated as on-link but is currently not
2814 			 * (RTF_LLINFO && ln == NULL case).
2815 			 */
2816 			if (rt_setgate(rt, rt_key(rt), SA(&null_sdl)) == 0) {
2817 				gate = rt->rt_gateway;
2818 				SDL(gate)->sdl_type = ifp->if_type;
2819 				SDL(gate)->sdl_index = ifp->if_index;
2820 				/*
2821 				 * In case we're called before 1.0 sec.
2822 				 * has elapsed.
2823 				 */
2824 				if (ln != NULL) {
2825 					ln_setexpire(ln,
2826 					    (ifp->if_eflags & IFEF_IPV6_ND6ALT)
2827 					    ? 0 : MAX(timenow, 1));
2828 				}
2829 			}
2830 			if (rt->rt_flags & RTF_CLONING) {
2831 				break;
2832 			}
2833 		}
2834 		/*
2835 		 * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
2836 		 * We don't do that here since llinfo is not ready yet.
2837 		 *
2838 		 * There are also couple of other things to be discussed:
2839 		 * - unsolicited NA code needs improvement beforehand
2840 		 * - RFC4861 says we MAY send multicast unsolicited NA
2841 		 *   (7.2.6 paragraph 4), however, it also says that we
2842 		 *   SHOULD provide a mechanism to prevent multicast NA storm.
2843 		 *   we don't have anything like it right now.
2844 		 *   note that the mechanism needs a mutual agreement
2845 		 *   between proxies, which means that we need to implement
2846 		 *   a new protocol, or a new kludge.
2847 		 * - from RFC4861 6.2.4, host MUST NOT send an unsolicited RA.
2848 		 *   we need to check ip6forwarding before sending it.
2849 		 *   (or should we allow proxy ND configuration only for
2850 		 *   routers?  there's no mention about proxy ND from hosts)
2851 		 */
2852 		OS_FALLTHROUGH;
2853 	case RTM_RESOLVE:
2854 		if (!(ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK))) {
2855 			/*
2856 			 * Address resolution isn't necessary for a point to
2857 			 * point link, so we can skip this test for a p2p link.
2858 			 */
2859 			if (gate->sa_family != AF_LINK ||
2860 			    gate->sa_len < sizeof(null_sdl)) {
2861 				/* Don't complain in case of RTM_ADD */
2862 				if (req == RTM_RESOLVE) {
2863 					log(LOG_ERR, "%s: route to %s has bad "
2864 					    "gateway address (sa_family %u "
2865 					    "sa_len %u) on %s\n", __func__,
2866 					    inet_ntop(AF_INET6,
2867 					    &SIN6(rt_key(rt))->sin6_addr, buf,
2868 					    sizeof(buf)), gate->sa_family,
2869 					    gate->sa_len, if_name(ifp));
2870 				}
2871 				break;
2872 			}
2873 			SDL(gate)->sdl_type = ifp->if_type;
2874 			SDL(gate)->sdl_index = ifp->if_index;
2875 		}
2876 		if (ln != NULL) {
2877 			break;  /* This happens on a route change */
2878 		}
2879 		/*
2880 		 * Case 2: This route may come from cloning, or a manual route
2881 		 * add with a LL address.
2882 		 */
2883 		rt->rt_llinfo = ln = nd6_llinfo_alloc(Z_WAITOK);
2884 
2885 		nd6_allocated++;
2886 		rt->rt_llinfo_get_ri    = nd6_llinfo_get_ri;
2887 		rt->rt_llinfo_get_iflri = nd6_llinfo_get_iflri;
2888 		rt->rt_llinfo_purge     = nd6_llinfo_purge;
2889 		rt->rt_llinfo_free      = nd6_llinfo_free;
2890 		rt->rt_llinfo_refresh   = nd6_llinfo_refresh;
2891 		rt->rt_flags |= RTF_LLINFO;
2892 		ln->ln_rt = rt;
2893 		/* this is required for "ndp" command. - shin */
2894 		/*
2895 		 * For interface's that do not perform NUD
2896 		 * neighbor cache entries must always be marked
2897 		 * reachable with no expiry
2898 		 */
2899 		if ((req == RTM_ADD) || !nud_enabled) {
2900 			/*
2901 			 * gate should have some valid AF_LINK entry,
2902 			 * and ln->ln_expire should have some lifetime
2903 			 * which is specified by ndp command.
2904 			 */
2905 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2906 			ln_setexpire(ln, 0);
2907 		} else {
2908 			/*
2909 			 * When req == RTM_RESOLVE, rt is created and
2910 			 * initialized in rtrequest(), so rt_expire is 0.
2911 			 */
2912 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_NOSTATE);
2913 			/* In case we're called before 1.0 sec. has elapsed */
2914 			ln_setexpire(ln, (ifp->if_eflags & IFEF_IPV6_ND6ALT) ?
2915 			    0 : MAX(timenow, 1));
2916 		}
2917 		LN_INSERTHEAD(ln);
2918 		nd6_inuse++;
2919 
2920 		/* We have at least one entry; arm the timer if not already */
2921 		nd6_sched_timeout(NULL, NULL);
2922 
2923 		/*
2924 		 * If we have too many cache entries, initiate immediate
2925 		 * purging for some "less recently used" entries.  Note that
2926 		 * we cannot directly call nd6_free() here because it would
2927 		 * cause re-entering rtable related routines triggering an LOR
2928 		 * problem.
2929 		 */
2930 		if (ip6_neighborgcthresh > 0 &&
2931 		    nd6_inuse >= ip6_neighborgcthresh) {
2932 			int i;
2933 
2934 			for (i = 0; i < 10 && llinfo_nd6.ln_prev != ln; i++) {
2935 				struct llinfo_nd6 *__single ln_end = llinfo_nd6.ln_prev;
2936 				rtentry_ref_t rt_end = ln_end->ln_rt;
2937 
2938 				/* Move this entry to the head */
2939 				RT_LOCK(rt_end);
2940 				LN_DEQUEUE(ln_end);
2941 				LN_INSERTHEAD(ln_end);
2942 
2943 				if (ln_end->ln_expire == 0) {
2944 					RT_UNLOCK(rt_end);
2945 					continue;
2946 				}
2947 				if (ln_end->ln_state > ND6_LLINFO_INCOMPLETE) {
2948 					ND6_CACHE_STATE_TRANSITION(ln_end, ND6_LLINFO_STALE);
2949 				} else {
2950 					ND6_CACHE_STATE_TRANSITION(ln_end, ND6_LLINFO_PURGE);
2951 				}
2952 				ln_setexpire(ln_end, timenow);
2953 				RT_UNLOCK(rt_end);
2954 			}
2955 		}
2956 
2957 		/*
2958 		 * check if rt_key(rt) is one of my address assigned
2959 		 * to the interface.
2960 		 */
2961 		ifa = (struct ifaddr *)in6ifa_ifpwithaddr(rt->rt_ifp,
2962 		    &SIN6(rt_key(rt))->sin6_addr);
2963 		if (ifa != NULL) {
2964 			caddr_t macp = nd6_ifptomac(ifp);
2965 			ln_setexpire(ln, 0);
2966 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2967 			if (macp != NULL) {
2968 				SOCKADDR_COPY(macp, LLADDR(SDL(gate)), ifp->if_addrlen);
2969 				SDL(gate)->sdl_alen = ifp->if_addrlen;
2970 			}
2971 			if (nd6_useloopback) {
2972 				if (rt->rt_ifp != lo_ifp) {
2973 					/*
2974 					 * Purge any link-layer info caching.
2975 					 */
2976 					if (rt->rt_llinfo_purge != NULL) {
2977 						rt->rt_llinfo_purge(rt);
2978 					}
2979 
2980 					/*
2981 					 * Adjust route ref count for the
2982 					 * interfaces.
2983 					 */
2984 					if (rt->rt_if_ref_fn != NULL) {
2985 						rt->rt_if_ref_fn(lo_ifp, 1);
2986 						rt->rt_if_ref_fn(rt->rt_ifp,
2987 						    -1);
2988 					}
2989 				}
2990 				rt->rt_ifp = lo_ifp;
2991 				/*
2992 				 * If rmx_mtu is not locked, update it
2993 				 * to the MTU used by the new interface.
2994 				 */
2995 				if (!(rt->rt_rmx.rmx_locks & RTV_MTU)) {
2996 					rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
2997 				}
2998 				/*
2999 				 * Make sure rt_ifa be equal to the ifaddr
3000 				 * corresponding to the address.
3001 				 * We need this because when we refer
3002 				 * rt_ifa->ia6_flags in ip6_input, we assume
3003 				 * that the rt_ifa points to the address instead
3004 				 * of the loopback address.
3005 				 */
3006 				if (ifa != rt->rt_ifa) {
3007 					rtsetifa(rt, ifa);
3008 				}
3009 			}
3010 			ifa_remref(ifa);
3011 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
3012 			ln_setexpire(ln, 0);
3013 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
3014 
3015 			/* join solicited node multicast for proxy ND */
3016 			if (ifp->if_flags & IFF_MULTICAST) {
3017 				struct in6_addr llsol;
3018 				struct in6_multi *__single in6m;
3019 				int error;
3020 
3021 				llsol = SIN6(rt_key(rt))->sin6_addr;
3022 				llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
3023 				llsol.s6_addr32[1] = 0;
3024 				llsol.s6_addr32[2] = htonl(1);
3025 				llsol.s6_addr8[12] = 0xff;
3026 				if (in6_setscope(&llsol, ifp, NULL)) {
3027 					break;
3028 				}
3029 				error = in6_mc_join(ifp, &llsol,
3030 				    NULL, &in6m, 0);
3031 				if (error) {
3032 					nd6log(error, "%s: failed to join "
3033 					    "%s (errno=%d)\n", if_name(ifp),
3034 					    ip6_sprintf(&llsol), error);
3035 				} else {
3036 					IN6M_REMREF(in6m);
3037 				}
3038 			}
3039 		}
3040 		break;
3041 
3042 	case RTM_DELETE:
3043 		if (ln == NULL) {
3044 			break;
3045 		}
3046 		/* leave from solicited node multicast for proxy ND */
3047 		if ((rt->rt_flags & RTF_ANNOUNCE) &&
3048 		    (ifp->if_flags & IFF_MULTICAST)) {
3049 			struct in6_addr llsol;
3050 			struct in6_multi *__single in6m;
3051 
3052 			llsol = SIN6(rt_key(rt))->sin6_addr;
3053 			llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
3054 			llsol.s6_addr32[1] = 0;
3055 			llsol.s6_addr32[2] = htonl(1);
3056 			llsol.s6_addr8[12] = 0xff;
3057 			if (in6_setscope(&llsol, ifp, NULL) == 0) {
3058 				in6_multihead_lock_shared();
3059 				IN6_LOOKUP_MULTI(&llsol, ifp, in6m);
3060 				in6_multihead_lock_done();
3061 				if (in6m != NULL) {
3062 					in6_mc_leave(in6m, NULL);
3063 					IN6M_REMREF(in6m);
3064 				}
3065 			}
3066 		}
3067 		nd6_inuse--;
3068 		/*
3069 		 * Unchain it but defer the actual freeing until the route
3070 		 * itself is to be freed.  rt->rt_llinfo still points to
3071 		 * llinfo_nd6, and likewise, ln->ln_rt still points to this
3072 		 * route entry, except that RTF_LLINFO is now cleared.
3073 		 */
3074 		if (ln->ln_flags & ND6_LNF_IN_USE) {
3075 			LN_DEQUEUE(ln);
3076 		}
3077 
3078 		/*
3079 		 * Purge any link-layer info caching.
3080 		 */
3081 		if (rt->rt_llinfo_purge != NULL) {
3082 			rt->rt_llinfo_purge(rt);
3083 		}
3084 
3085 		rt->rt_flags &= ~RTF_LLINFO;
3086 		if (ln->ln_hold != NULL) {
3087 			m_freem_list(ln->ln_hold);
3088 			ln->ln_hold = NULL;
3089 		}
3090 	}
3091 }
3092 
3093 int
nd6_ioctl(u_long cmd,caddr_t __sized_by (IOCPARM_LEN (cmd))data,struct ifnet * ifp)3094 nd6_ioctl(u_long cmd, caddr_t __sized_by(IOCPARM_LEN(cmd)) data, struct ifnet *ifp)
3095 {
3096 	struct nd_defrouter *__single dr;
3097 	struct nd_prefix *__single pr;
3098 	rtentry_ref_t rt;
3099 
3100 	int error = 0;
3101 
3102 	VERIFY(ifp != NULL);
3103 
3104 	switch (cmd) {
3105 	case OSIOCGIFINFO_IN6:          /* struct in6_ondireq */
3106 	case SIOCGIFINFO_IN6: {         /* struct in6_ondireq */
3107 		u_int32_t linkmtu;
3108 		struct in6_ondireq *__single ondi = (struct in6_ondireq *)(void *)data;
3109 		struct nd_ifinfo *__single ndi;
3110 		/*
3111 		 * SIOCGIFINFO_IN6 ioctl is encoded with in6_ondireq
3112 		 * instead of in6_ndireq, so we treat it as such.
3113 		 */
3114 		ndi = ND_IFINFO(ifp);
3115 		if ((NULL == ndi) || (FALSE == ndi->initialized)) {
3116 			error = EINVAL;
3117 			break;
3118 		}
3119 		lck_mtx_lock(&ndi->lock);
3120 		linkmtu = IN6_LINKMTU(ifp);
3121 		bcopy(&linkmtu, &ondi->ndi.linkmtu, sizeof(linkmtu));
3122 		bcopy(&ndi->maxmtu, &ondi->ndi.maxmtu,
3123 		    sizeof(u_int32_t));
3124 		bcopy(&ndi->basereachable, &ondi->ndi.basereachable,
3125 		    sizeof(u_int32_t));
3126 		bcopy(&ndi->reachable, &ondi->ndi.reachable,
3127 		    sizeof(u_int32_t));
3128 		bcopy(&ndi->retrans, &ondi->ndi.retrans,
3129 		    sizeof(u_int32_t));
3130 		bcopy(&ndi->flags, &ondi->ndi.flags,
3131 		    sizeof(u_int32_t));
3132 		bcopy(&ndi->recalctm, &ondi->ndi.recalctm,
3133 		    sizeof(int));
3134 		ondi->ndi.chlim = ndi->chlim;
3135 		/*
3136 		 * The below truncation is fine as we mostly use it for
3137 		 * debugging purpose.
3138 		 */
3139 		ondi->ndi.receivedra = (uint8_t)ndi->ndefrouters;
3140 		ondi->ndi.collision_count = (uint8_t)ndi->cga_collision_count;
3141 		lck_mtx_unlock(&ndi->lock);
3142 		break;
3143 	}
3144 
3145 	case SIOCSIFINFO_FLAGS: {       /* struct in6_ndireq */
3146 		/*
3147 		 * XXX BSD has a bunch of checks here to ensure
3148 		 * that interface disabled flag is not reset if
3149 		 * link local address has failed DAD.
3150 		 * Investigate that part.
3151 		 */
3152 		struct in6_ndireq *__single cndi = (struct in6_ndireq *)(void *)data;
3153 		u_int32_t oflags, flags;
3154 		struct nd_ifinfo *__single ndi = ND_IFINFO(ifp);
3155 
3156 		/* XXX: almost all other fields of cndi->ndi is unused */
3157 		if ((NULL == ndi) || !ndi->initialized) {
3158 			error = EINVAL;
3159 			break;
3160 		}
3161 
3162 		lck_mtx_lock(&ndi->lock);
3163 		oflags = ndi->flags;
3164 		bcopy(&cndi->ndi.flags, &(ndi->flags), sizeof(flags));
3165 		flags = ndi->flags;
3166 		lck_mtx_unlock(&ndi->lock);
3167 
3168 		if (oflags == flags) {
3169 			break;
3170 		}
3171 
3172 		error = nd6_setifinfo(ifp, oflags, flags);
3173 		break;
3174 	}
3175 
3176 	case SIOCSNDFLUSH_IN6:          /* struct in6_ifreq */
3177 		/* flush default router list */
3178 		/*
3179 		 * xxx sumikawa: should not delete route if default
3180 		 * route equals to the top of default router list
3181 		 *
3182 		 * XXX TODO: Needs to be done for RTI as well
3183 		 * Is very specific flush command with ndp for default routers.
3184 		 */
3185 		lck_mtx_lock(nd6_mutex);
3186 		defrouter_reset();
3187 		defrouter_select(ifp, NULL);
3188 		lck_mtx_unlock(nd6_mutex);
3189 		/* xxx sumikawa: flush prefix list */
3190 		break;
3191 
3192 	case SIOCSPFXFLUSH_IN6: {       /* struct in6_ifreq */
3193 		/* flush all the prefix advertised by routers */
3194 		struct nd_prefix *__single next = NULL;
3195 
3196 		lck_mtx_lock(nd6_mutex);
3197 		for (pr = nd_prefix.lh_first; pr; pr = next) {
3198 			struct in6_ifaddr *__single ia = NULL;
3199 			bool iterate_pfxlist_again = false;
3200 
3201 			next = pr->ndpr_next;
3202 
3203 			NDPR_LOCK(pr);
3204 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
3205 				NDPR_UNLOCK(pr);
3206 				continue; /* XXX */
3207 			}
3208 			if (ifp != lo_ifp && pr->ndpr_ifp != ifp) {
3209 				NDPR_UNLOCK(pr);
3210 				continue;
3211 			}
3212 			/* do we really have to remove addresses as well? */
3213 			NDPR_ADDREF(pr);
3214 			NDPR_UNLOCK(pr);
3215 			lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
3216 			bool from_begining = true;
3217 			while (from_begining) {
3218 				from_begining = false;
3219 				TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
3220 					IFA_LOCK(&ia->ia_ifa);
3221 					if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0) {
3222 						IFA_UNLOCK(&ia->ia_ifa);
3223 						continue;
3224 					}
3225 
3226 					if (ia->ia6_ndpr == pr) {
3227 						ifa_addref(&ia->ia_ifa);
3228 						IFA_UNLOCK(&ia->ia_ifa);
3229 						lck_rw_done(&in6_ifaddr_rwlock);
3230 						lck_mtx_unlock(nd6_mutex);
3231 						in6_purgeaddr(&ia->ia_ifa);
3232 						ifa_remref(&ia->ia_ifa);
3233 						lck_mtx_lock(nd6_mutex);
3234 						lck_rw_lock_exclusive(
3235 							&in6_ifaddr_rwlock);
3236 						/*
3237 						 * Purging the address caused
3238 						 * in6_ifaddr_rwlock to be
3239 						 * dropped and
3240 						 * reacquired; therefore search again
3241 						 * from the beginning of in6_ifaddrs.
3242 						 * The same applies for the prefix list.
3243 						 */
3244 						iterate_pfxlist_again = true;
3245 						from_begining = true;
3246 						break;
3247 					}
3248 					IFA_UNLOCK(&ia->ia_ifa);
3249 				}
3250 			}
3251 			lck_rw_done(&in6_ifaddr_rwlock);
3252 			NDPR_LOCK(pr);
3253 			prelist_remove(pr);
3254 			NDPR_UNLOCK(pr);
3255 			pfxlist_onlink_check();
3256 			NDPR_REMREF(pr);
3257 			if (iterate_pfxlist_again) {
3258 				next = nd_prefix.lh_first;
3259 			}
3260 		}
3261 		lck_mtx_unlock(nd6_mutex);
3262 		break;
3263 	}
3264 
3265 	case SIOCSRTRFLUSH_IN6: {       /* struct in6_ifreq */
3266 		/* flush all the default routers */
3267 		struct nd_defrouter *__single next;
3268 		struct nd_drhead nd_defrouter_tmp;
3269 
3270 		TAILQ_INIT(&nd_defrouter_tmp);
3271 		lck_mtx_lock(nd6_mutex);
3272 		if ((dr = TAILQ_FIRST(&nd_defrouter_list)) != NULL) {
3273 			/*
3274 			 * The first entry of the list may be stored in
3275 			 * the routing table, so we'll delete it later.
3276 			 */
3277 			for (dr = TAILQ_NEXT(dr, dr_entry); dr; dr = next) {
3278 				next = TAILQ_NEXT(dr, dr_entry);
3279 				if (ifp == lo_ifp || dr->ifp == ifp) {
3280 					/*
3281 					 * Remove the entry from default router list
3282 					 * and add it to the temp list.
3283 					 * nd_defrouter_tmp will be a local temporary
3284 					 * list as no one else can get the same
3285 					 * removed entry once it is removed from default
3286 					 * router list.
3287 					 * Remove the reference after calling defrtrlist_de
3288 					 */
3289 					TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
3290 					TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
3291 				}
3292 			}
3293 
3294 			dr = TAILQ_FIRST(&nd_defrouter_list);
3295 			if (ifp == lo_ifp ||
3296 			    dr->ifp == ifp) {
3297 				TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
3298 				TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
3299 			}
3300 		}
3301 
3302 		/*
3303 		 * Keep the following separate from the above iteration of
3304 		 * nd_defrouter because it's not safe to call
3305 		 * defrtrlist_del while iterating global default
3306 		 * router list. Global list has to be traversed
3307 		 * while holding nd6_mutex throughout.
3308 		 *
3309 		 * The following call to defrtrlist_del should be
3310 		 * safe as we are iterating a local list of
3311 		 * default routers.
3312 		 */
3313 		TAILQ_FOREACH_SAFE(dr, &nd_defrouter_tmp, dr_entry, next) {
3314 			TAILQ_REMOVE(&nd_defrouter_tmp, dr, dr_entry);
3315 			defrtrlist_del(dr, NULL);
3316 			NDDR_REMREF(dr);        /* remove list reference */
3317 		}
3318 
3319 		/* For now flush RTI routes here as well to avoid any regressions */
3320 		nd6_purge_interface_rti_entries((ifp == lo_ifp) ? NULL : ifp);
3321 
3322 		lck_mtx_unlock(nd6_mutex);
3323 		break;
3324 	}
3325 
3326 	case SIOCGNBRINFO_IN6_32: {     /* struct in6_nbrinfo_32 */
3327 		struct llinfo_nd6 *__single ln;
3328 		struct in6_nbrinfo_32 nbi_32;
3329 		struct in6_addr nb_addr; /* make local for safety */
3330 
3331 		bcopy(data, &nbi_32, sizeof(nbi_32));
3332 		nb_addr = nbi_32.addr;
3333 		/*
3334 		 * XXX: KAME specific hack for scoped addresses
3335 		 *      XXXX: for other scopes than link-local?
3336 		 */
3337 		if (in6_embedded_scope && (IN6_IS_ADDR_LINKLOCAL(&nbi_32.addr) ||
3338 		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi_32.addr))) {
3339 			u_int16_t *idp =
3340 			    (u_int16_t *)(void *)&nb_addr.s6_addr[2];
3341 
3342 			if (*idp == 0) {
3343 				*idp = htons(ifp->if_index);
3344 			}
3345 		}
3346 
3347 		/* Callee returns a locked route upon success */
3348 		if ((rt = nd6_lookup(&nb_addr, 0, ifp, 0)) == NULL) {
3349 			error = EINVAL;
3350 			break;
3351 		}
3352 		RT_LOCK_ASSERT_HELD(rt);
3353 		ln = rt->rt_llinfo;
3354 		nbi_32.state = ln->ln_state;
3355 		nbi_32.asked = ln->ln_asked;
3356 		nbi_32.isrouter = ln->ln_router;
3357 		nbi_32.expire = (int)ln_getexpire(ln);
3358 		RT_REMREF_LOCKED(rt);
3359 		RT_UNLOCK(rt);
3360 		bcopy(&nbi_32, data, sizeof(nbi_32));
3361 		break;
3362 	}
3363 
3364 	case SIOCGNBRINFO_IN6_64: {     /* struct in6_nbrinfo_64 */
3365 		struct llinfo_nd6 *__single ln;
3366 		struct in6_nbrinfo_64 nbi_64;
3367 		struct in6_addr nb_addr; /* make local for safety */
3368 
3369 		bcopy(data, &nbi_64, sizeof(nbi_64));
3370 		nb_addr = nbi_64.addr;
3371 		/*
3372 		 * XXX: KAME specific hack for scoped addresses
3373 		 *      XXXX: for other scopes than link-local?
3374 		 */
3375 		if (in6_embedded_scope && (IN6_IS_ADDR_LINKLOCAL(&nbi_64.addr) ||
3376 		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi_64.addr))) {
3377 			u_int16_t *idp =
3378 			    (u_int16_t *)(void *)&nb_addr.s6_addr[2];
3379 
3380 			if (*idp == 0) {
3381 				*idp = htons(ifp->if_index);
3382 			}
3383 		}
3384 
3385 		/* Callee returns a locked route upon success */
3386 		if ((rt = nd6_lookup(&nb_addr, 0, ifp, 0)) == NULL) {
3387 			error = EINVAL;
3388 			break;
3389 		}
3390 		RT_LOCK_ASSERT_HELD(rt);
3391 		ln = rt->rt_llinfo;
3392 		nbi_64.state = ln->ln_state;
3393 		nbi_64.asked = ln->ln_asked;
3394 		nbi_64.isrouter = ln->ln_router;
3395 		nbi_64.expire = (int)ln_getexpire(ln);
3396 		RT_REMREF_LOCKED(rt);
3397 		RT_UNLOCK(rt);
3398 		bcopy(&nbi_64, data, sizeof(nbi_64));
3399 		break;
3400 	}
3401 
3402 	case SIOCGDEFIFACE_IN6_32:      /* struct in6_ndifreq_32 */
3403 	case SIOCGDEFIFACE_IN6_64: {    /* struct in6_ndifreq_64 */
3404 		struct in6_ndifreq_64 *__single ndif_64 =
3405 		    (struct in6_ndifreq_64 *)(void *)data;
3406 		struct in6_ndifreq_32 *__single ndif_32 =
3407 		    (struct in6_ndifreq_32 *)(void *)data;
3408 
3409 		if (cmd == SIOCGDEFIFACE_IN6_64) {
3410 			u_int64_t j = nd6_defifindex;
3411 			__nochk_bcopy(&j, &ndif_64->ifindex, sizeof(j));
3412 		} else {
3413 			bcopy(&nd6_defifindex, &ndif_32->ifindex,
3414 			    sizeof(u_int32_t));
3415 		}
3416 		break;
3417 	}
3418 
3419 	case SIOCSDEFIFACE_IN6_32:      /* struct in6_ndifreq_32 */
3420 	case SIOCSDEFIFACE_IN6_64: {    /* struct in6_ndifreq_64 */
3421 		struct in6_ndifreq_64 *__single ndif_64 =
3422 		    (struct in6_ndifreq_64 *)(void *)data;
3423 		struct in6_ndifreq_32 *__single ndif_32 =
3424 		    (struct in6_ndifreq_32 *)(void *)data;
3425 		u_int32_t idx;
3426 
3427 		if (cmd == SIOCSDEFIFACE_IN6_64) {
3428 			u_int64_t j;
3429 			__nochk_bcopy(&ndif_64->ifindex, &j, sizeof(j));
3430 			idx = (u_int32_t)j;
3431 		} else {
3432 			bcopy(&ndif_32->ifindex, &idx, sizeof(idx));
3433 		}
3434 
3435 		error = nd6_setdefaultiface(idx);
3436 		return error;
3437 		/* NOTREACHED */
3438 	}
3439 	case SIOCGIFCGAPREP_IN6_32:
3440 	case SIOCGIFCGAPREP_IN6_64: {
3441 		/* get CGA parameters */
3442 		union {
3443 			struct in6_cgareq_32    *cga32;
3444 			struct in6_cgareq_64    *cga64;
3445 			void                    *data;
3446 		} cgareq_u;
3447 		struct nd_ifinfo        *__single ndi;
3448 		struct in6_cga_modifier *__single ndi_cga_mod;
3449 		struct in6_cga_modifier *__single req_cga_mod;
3450 
3451 		ndi = ND_IFINFO(ifp);
3452 		if ((NULL == ndi) || !ndi->initialized) {
3453 			error = EINVAL;
3454 			break;
3455 		}
3456 		cgareq_u.data = data;
3457 		req_cga_mod = (cmd == SIOCGIFCGAPREP_IN6_64)
3458 		    ? &(cgareq_u.cga64->cgar_cgaprep.cga_modifier)
3459 		    : &(cgareq_u.cga32->cgar_cgaprep.cga_modifier);
3460 		lck_mtx_lock(&ndi->lock);
3461 		ndi_cga_mod = &(ndi->local_cga_modifier);
3462 		bcopy(ndi_cga_mod, req_cga_mod, sizeof(*req_cga_mod));
3463 		lck_mtx_unlock(&ndi->lock);
3464 		break;
3465 	}
3466 	case SIOCSIFCGAPREP_IN6_32:
3467 	case SIOCSIFCGAPREP_IN6_64:
3468 	{
3469 		/* set CGA parameters */
3470 		struct in6_cgareq       cgareq;
3471 		struct nd_ifinfo        *__single ndi;
3472 		struct in6_cga_modifier *__single ndi_cga_mod;
3473 		struct in6_cga_modifier *__single req_cga_mod;
3474 
3475 		ndi = ND_IFINFO(ifp);
3476 		if ((NULL == ndi) || !ndi->initialized) {
3477 			error = EINVAL;
3478 			break;
3479 		}
3480 		if (cmd == SIOCSIFCGAPREP_IN6_64) {
3481 			in6_cgareq_copy_from_user64(data, &cgareq);
3482 		} else {
3483 			in6_cgareq_copy_from_user32(data, &cgareq);
3484 		}
3485 		req_cga_mod = &cgareq.cgar_cgaprep.cga_modifier;
3486 		lck_mtx_lock(&ndi->lock);
3487 		ndi_cga_mod = &(ndi->local_cga_modifier);
3488 		bcopy(req_cga_mod, ndi_cga_mod, sizeof(*ndi_cga_mod));
3489 		ndi->cga_initialized = TRUE;
3490 		ndi->cga_collision_count = 0;
3491 		lck_mtx_unlock(&ndi->lock);
3492 		break;
3493 	}
3494 	default:
3495 		break;
3496 	}
3497 	return error;
3498 }
3499 
3500 /*
3501  * Create neighbor cache entry and cache link-layer address,
3502  * on reception of inbound ND6 packets. (RS/RA/NS/redirect)
3503  */
3504 void
nd6_cache_lladdr(struct ifnet * ifp,struct in6_addr * from,char * lladdr __sized_by (lladdrlen),int lladdrlen,int type,int code,int * did_update)3505 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr __sized_by(lladdrlen),
3506     int lladdrlen, int type, int code, int *did_update)
3507 {
3508 #pragma unused(lladdrlen)
3509 	rtentry_ref_t rt = NULL;
3510 	struct llinfo_nd6 *__single ln = NULL;
3511 	int is_newentry;
3512 	struct sockaddr_dl *sdl = NULL;
3513 	int do_update;
3514 	int olladdr;
3515 	int llchange;
3516 	short newstate = 0;
3517 	uint64_t timenow;
3518 	boolean_t sched_timeout = FALSE;
3519 	struct nd_ifinfo *__single ndi = NULL;
3520 
3521 	if (ifp == NULL) {
3522 		panic("ifp == NULL in nd6_cache_lladdr");
3523 	}
3524 	if (from == NULL) {
3525 		panic("from == NULL in nd6_cache_lladdr");
3526 	}
3527 
3528 	if (did_update != NULL) {
3529 		did_update = 0;
3530 	}
3531 
3532 	/* nothing must be updated for unspecified address */
3533 	if (IN6_IS_ADDR_UNSPECIFIED(from)) {
3534 		return;
3535 	}
3536 
3537 	/*
3538 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
3539 	 * the caller.
3540 	 */
3541 	timenow = net_uptime();
3542 
3543 	rt = nd6_lookup(from, 0, ifp, 0);
3544 	if (rt == NULL) {
3545 		if ((rt = nd6_lookup(from, 1, ifp, 0)) == NULL) {
3546 			return;
3547 		}
3548 		RT_LOCK_ASSERT_HELD(rt);
3549 		is_newentry = 1;
3550 	} else {
3551 		RT_LOCK_ASSERT_HELD(rt);
3552 		/* do nothing if static ndp is set */
3553 		if (rt->rt_flags & RTF_STATIC) {
3554 			RT_REMREF_LOCKED(rt);
3555 			RT_UNLOCK(rt);
3556 			return;
3557 		}
3558 		is_newentry = 0;
3559 	}
3560 
3561 	if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
3562 fail:
3563 		RT_UNLOCK(rt);
3564 		nd6_free(rt);
3565 		rtfree(rt);
3566 		return;
3567 	}
3568 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
3569 	if (ln == NULL) {
3570 		goto fail;
3571 	}
3572 	if (rt->rt_gateway == NULL) {
3573 		goto fail;
3574 	}
3575 	if (rt->rt_gateway->sa_family != AF_LINK) {
3576 		goto fail;
3577 	}
3578 	sdl = SDL(rt->rt_gateway);
3579 
3580 	olladdr = (sdl->sdl_alen) ? 1 : 0;
3581 	if (olladdr && lladdr) {
3582 		if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen)) {
3583 			llchange = 1;
3584 		} else {
3585 			llchange = 0;
3586 		}
3587 	} else {
3588 		llchange = 0;
3589 	}
3590 
3591 	/*
3592 	 * newentry olladdr  lladdr  llchange	(*=record)
3593 	 *	0	n	n	--	(1)
3594 	 *	0	y	n	--	(2)
3595 	 *	0	n	y	--	(3) * STALE
3596 	 *	0	y	y	n	(4) *
3597 	 *	0	y	y	y	(5) * STALE
3598 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
3599 	 *	1	--	y	--	(7) * STALE
3600 	 */
3601 
3602 	if (lladdr != NULL) {           /* (3-5) and (7) */
3603 		/*
3604 		 * Record source link-layer address
3605 		 * XXX is it dependent to ifp->if_type?
3606 		 */
3607 		sdl->sdl_alen = ifp->if_addrlen;
3608 		bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
3609 
3610 		/* cache the gateway (sender HW) address */
3611 		nd6_llreach_alloc(rt, ifp, LLADDR(sdl), sdl->sdl_alen, FALSE);
3612 	}
3613 
3614 	if (is_newentry == 0) {
3615 		if ((!olladdr && lladdr != NULL) ||     /* (3) */
3616 		    (olladdr && lladdr != NULL && llchange)) {  /* (5) */
3617 			do_update = 1;
3618 			newstate = ND6_LLINFO_STALE;
3619 		} else {                                /* (1-2,4) */
3620 			do_update = 0;
3621 		}
3622 	} else {
3623 		do_update = 1;
3624 		if (lladdr == NULL) {                   /* (6) */
3625 			newstate = ND6_LLINFO_NOSTATE;
3626 		} else {                                /* (7) */
3627 			newstate = ND6_LLINFO_STALE;
3628 		}
3629 	}
3630 
3631 	/*
3632 	 * For interface's that do not perform NUD or NDP
3633 	 * neighbor cache entres must always be marked
3634 	 * reachable with no expiry
3635 	 */
3636 	ndi = ND_IFINFO(ifp);
3637 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
3638 
3639 	if ((ndi && !(ndi->flags & ND6_IFF_PERFORMNUD)) ||
3640 	    (ifp->if_eflags & IFEF_IPV6_ND6ALT)) {
3641 		newstate = ND6_LLINFO_REACHABLE;
3642 		ln_setexpire(ln, 0);
3643 	}
3644 
3645 	if (do_update) {
3646 		/*
3647 		 * Update the state of the neighbor cache.
3648 		 */
3649 		ND6_CACHE_STATE_TRANSITION(ln, newstate);
3650 
3651 		if ((ln->ln_state == ND6_LLINFO_STALE) ||
3652 		    (ln->ln_state == ND6_LLINFO_REACHABLE)) {
3653 			mbuf_ref_t m = ln->ln_hold;
3654 			/*
3655 			 * XXX: since nd6_output() below will cause
3656 			 * a state transition to DELAY and reset the timer,
3657 			 * we must set the timer now, although it is actually
3658 			 * meaningless.
3659 			 */
3660 			if (ln->ln_state == ND6_LLINFO_STALE) {
3661 				ln_setexpire(ln, timenow + nd6_gctimer);
3662 			}
3663 
3664 			ln->ln_hold = NULL;
3665 			if (m != NULL) {
3666 				struct sockaddr_in6 sin6;
3667 
3668 				rtkey_to_sa6(rt, &sin6);
3669 				/*
3670 				 * we assume ifp is not a p2p here, so just
3671 				 * set the 2nd argument as the 1st one.
3672 				 */
3673 				RT_UNLOCK(rt);
3674 				nd6_output_list(ifp, ifp, m, &sin6, rt, NULL);
3675 				RT_LOCK(rt);
3676 			}
3677 		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
3678 			/* probe right away */
3679 			ln_setexpire(ln, timenow);
3680 			sched_timeout = TRUE;
3681 		}
3682 	}
3683 
3684 	/*
3685 	 * ICMP6 type dependent behavior.
3686 	 *
3687 	 * NS: clear IsRouter if new entry
3688 	 * RS: clear IsRouter
3689 	 * RA: set IsRouter if there's lladdr
3690 	 * redir: clear IsRouter if new entry
3691 	 *
3692 	 * RA case, (1):
3693 	 * The spec says that we must set IsRouter in the following cases:
3694 	 * - If lladdr exist, set IsRouter.  This means (1-5).
3695 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
3696 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
3697 	 * A quetion arises for (1) case.  (1) case has no lladdr in the
3698 	 * neighbor cache, this is similar to (6).
3699 	 * This case is rare but we figured that we MUST NOT set IsRouter.
3700 	 *
3701 	 * newentry olladdr  lladdr  llchange	    NS  RS	RA	redir
3702 	 *								D R
3703 	 *	0	n	n	--	(1)	c	?	s
3704 	 *	0	y	n	--	(2)	c	s	s
3705 	 *	0	n	y	--	(3)	c	s	s
3706 	 *	0	y	y	n	(4)	c	s	s
3707 	 *	0	y	y	y	(5)	c	s	s
3708 	 *	1	--	n	--	(6) c	c		c s
3709 	 *	1	--	y	--	(7) c	c	s	c s
3710 	 *
3711 	 *					(c=clear s=set)
3712 	 */
3713 	switch (type & 0xff) {
3714 	case ND_NEIGHBOR_SOLICIT:
3715 		/*
3716 		 * New entry must have is_router flag cleared.
3717 		 */
3718 		if (is_newentry) {      /* (6-7) */
3719 			ln->ln_router = 0;
3720 		}
3721 		break;
3722 	case ND_REDIRECT:
3723 		/*
3724 		 * If the ICMP message is a Redirect to a better router, always
3725 		 * set the is_router flag.  Otherwise, if the entry is newly
3726 		 * created, then clear the flag.  [RFC 4861, sec 8.3]
3727 		 */
3728 		if (code == ND_REDIRECT_ROUTER) {
3729 			ln->ln_router = 1;
3730 		} else if (is_newentry) { /* (6-7) */
3731 			ln->ln_router = 0;
3732 		}
3733 		break;
3734 	case ND_ROUTER_SOLICIT:
3735 		/*
3736 		 * is_router flag must always be cleared.
3737 		 */
3738 		ln->ln_router = 0;
3739 		break;
3740 	case ND_ROUTER_ADVERT:
3741 		/*
3742 		 * Mark an entry with lladdr as a router.
3743 		 */
3744 		if ((!is_newentry && (olladdr || lladdr)) ||    /* (2-5) */
3745 		    (is_newentry && lladdr)) {                  /* (7) */
3746 			ln->ln_router = 1;
3747 		}
3748 		break;
3749 	}
3750 
3751 	if (do_update) {
3752 		int route_ev_code = 0;
3753 
3754 		if (llchange) {
3755 			route_ev_code = ROUTE_LLENTRY_CHANGED;
3756 		} else {
3757 			route_ev_code = ROUTE_LLENTRY_RESOLVED;
3758 		}
3759 
3760 		/* Enqueue work item to invoke callback for this route entry */
3761 		route_event_enqueue_nwk_wq_entry(rt, NULL, route_ev_code, NULL, TRUE);
3762 
3763 		if (ln->ln_router || (rt->rt_flags & RTF_ROUTER)) {
3764 			radix_node_head_ref_t rnh = NULL;
3765 			struct in6_addr rt_addr = SIN6(rt_key(rt))->sin6_addr;
3766 			ifnet_ref_t rt_ifp = rt->rt_ifp;
3767 			struct route_event rt_ev;
3768 			route_event_init(&rt_ev, rt, NULL, llchange ? ROUTE_LLENTRY_CHANGED :
3769 			    ROUTE_LLENTRY_RESOLVED);
3770 			/*
3771 			 * We already have a valid reference on rt.
3772 			 * The function frees that before returning.
3773 			 * We therefore don't need an extra reference here
3774 			 */
3775 			RT_UNLOCK(rt);
3776 			defrouter_set_reachability(&rt_addr, rt_ifp, TRUE);
3777 			lck_mtx_lock(rnh_lock);
3778 
3779 			rnh = rt_tables[AF_INET6];
3780 			if (rnh != NULL) {
3781 				(void) rnh->rnh_walktree(rnh, route_event_walktree,
3782 				    (void *)&rt_ev);
3783 			}
3784 			lck_mtx_unlock(rnh_lock);
3785 			RT_LOCK(rt);
3786 		}
3787 	}
3788 
3789 	if (did_update != NULL) {
3790 		*did_update = do_update;
3791 	}
3792 
3793 	/*
3794 	 * When the link-layer address of a router changes, select the
3795 	 * best router again.  In particular, when the neighbor entry is newly
3796 	 * created, it might affect the selection policy.
3797 	 * Question: can we restrict the first condition to the "is_newentry"
3798 	 * case?
3799 	 *
3800 	 * Note: Perform default router selection even when we are a router,
3801 	 * if Scoped Routing is enabled.
3802 	 */
3803 	if (do_update && ln->ln_router) {
3804 		/*
3805 		 * XXX TODO: This should also be iterated over router list
3806 		 * for route information option's router lists as well.
3807 		 */
3808 		RT_REMREF_LOCKED(rt);
3809 		RT_UNLOCK(rt);
3810 		lck_mtx_lock(nd6_mutex);
3811 		defrouter_select(ifp, NULL);
3812 		nd6_router_select_rti_entries(ifp);
3813 		lck_mtx_unlock(nd6_mutex);
3814 	} else {
3815 		RT_REMREF_LOCKED(rt);
3816 		RT_UNLOCK(rt);
3817 	}
3818 	if (sched_timeout) {
3819 		lck_mtx_lock(rnh_lock);
3820 		nd6_sched_timeout(NULL, NULL);
3821 		lck_mtx_unlock(rnh_lock);
3822 	}
3823 }
3824 
3825 static void
nd6_slowtimo(void * arg)3826 nd6_slowtimo(void *arg)
3827 {
3828 #pragma unused(arg)
3829 	struct nd_ifinfo *__single nd6if = NULL;
3830 	ifnet_ref_t ifp = NULL;
3831 
3832 	ifnet_head_lock_shared();
3833 	for (ifp = ifnet_head.tqh_first; ifp;
3834 	    ifp = ifp->if_link.tqe_next) {
3835 		nd6if = ND_IFINFO(ifp);
3836 		if ((NULL == nd6if) || (FALSE == nd6if->initialized)) {
3837 			continue;
3838 		}
3839 
3840 		lck_mtx_lock(&nd6if->lock);
3841 		if (nd6if->basereachable && /* already initialized */
3842 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
3843 			/*
3844 			 * Since reachable time rarely changes by router
3845 			 * advertisements, we SHOULD insure that a new random
3846 			 * value gets recomputed at least once every few hours.
3847 			 * (RFC 4861, 6.3.4)
3848 			 */
3849 			nd6if->recalctm = nd6_recalc_reachtm_interval;
3850 			nd6if->reachable =
3851 			    ND_COMPUTE_RTIME(nd6if->basereachable);
3852 		}
3853 		lck_mtx_unlock(&nd6if->lock);
3854 	}
3855 	ifnet_head_done();
3856 	timeout(nd6_slowtimo, NULL, ND6_SLOWTIMER_INTERVAL * hz);
3857 }
3858 
3859 int
nd6_output(struct ifnet * ifp,struct ifnet * origifp,struct mbuf * m0,struct sockaddr_in6 * dst,struct rtentry * hint0,struct flowadv * adv)3860 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
3861     struct sockaddr_in6 *dst, struct rtentry *hint0, struct flowadv *adv)
3862 {
3863 	return nd6_output_list(ifp, origifp, m0, dst, hint0, adv);
3864 }
3865 
3866 /*
3867  * nd6_output_list()
3868  *
3869  * Assumption: route determination for first packet can be correctly applied to
3870  * all packets in the chain.
3871  */
3872 #define senderr(e) { error = (e); goto bad; }
3873 int
nd6_output_list(struct ifnet * ifp,struct ifnet * origifp,struct mbuf * m0,struct sockaddr_in6 * dst,struct rtentry * hint0,struct flowadv * adv)3874 nd6_output_list(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
3875     struct sockaddr_in6 *dst, struct rtentry *hint0, struct flowadv *adv)
3876 {
3877 	rtentry_ref_t rt = hint0, hint = hint0;
3878 	struct llinfo_nd6 *__single ln = NULL;
3879 	int error = 0;
3880 	uint64_t timenow;
3881 	rtentry_ref_t rtrele = NULL;
3882 	struct nd_ifinfo *__single ndi = NULL;
3883 
3884 	if (rt != NULL) {
3885 		RT_LOCK_SPIN(rt);
3886 		RT_ADDREF_LOCKED(rt);
3887 	}
3888 
3889 	if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr) || !nd6_need_cache(ifp)) {
3890 		if (rt != NULL) {
3891 			RT_UNLOCK(rt);
3892 		}
3893 		goto sendpkt;
3894 	}
3895 
3896 	/*
3897 	 * Next hop determination.  Because we may involve the gateway route
3898 	 * in addition to the original route, locking is rather complicated.
3899 	 * The general concept is that regardless of whether the route points
3900 	 * to the original route or to the gateway route, this routine takes
3901 	 * an extra reference on such a route.  This extra reference will be
3902 	 * released at the end.
3903 	 *
3904 	 * Care must be taken to ensure that the "hint0" route never gets freed
3905 	 * via rtfree(), since the caller may have stored it inside a struct
3906 	 * route with a reference held for that placeholder.
3907 	 *
3908 	 * This logic is similar to, though not exactly the same as the one
3909 	 * used by route_to_gwroute().
3910 	 */
3911 	if (rt != NULL) {
3912 		/*
3913 		 * We have a reference to "rt" by now (or below via rtalloc1),
3914 		 * which will either be released or freed at the end of this
3915 		 * routine.
3916 		 */
3917 		RT_LOCK_ASSERT_HELD(rt);
3918 		if (!(rt->rt_flags & RTF_UP)) {
3919 			RT_REMREF_LOCKED(rt);
3920 			RT_UNLOCK(rt);
3921 			if ((hint = rt = rtalloc1_scoped(SA(dst), 1, 0,
3922 			    ifp->if_index)) != NULL) {
3923 				RT_LOCK_SPIN(rt);
3924 				if (rt->rt_ifp != ifp) {
3925 					/* XXX: loop care? */
3926 					RT_UNLOCK(rt);
3927 					error = nd6_output_list(ifp, origifp, m0,
3928 					    dst, rt, adv);
3929 					rtfree(rt);
3930 					return error;
3931 				}
3932 			} else {
3933 				senderr(EHOSTUNREACH);
3934 			}
3935 		}
3936 
3937 		if (rt->rt_flags & RTF_GATEWAY) {
3938 			rtentry_ref_t gwrt;
3939 			struct in6_ifaddr *__single ia6 = NULL;
3940 			struct sockaddr_in6 gw6;
3941 
3942 			rtgw_to_sa6(rt, &gw6);
3943 			/*
3944 			 * Must drop rt_lock since nd6_is_addr_neighbor()
3945 			 * calls nd6_lookup() and acquires rnh_lock.
3946 			 */
3947 			RT_UNLOCK(rt);
3948 
3949 			/*
3950 			 * We skip link-layer address resolution and NUD
3951 			 * if the gateway is not a neighbor from ND point
3952 			 * of view, regardless of the value of nd_ifinfo.flags.
3953 			 * The second condition is a bit tricky; we skip
3954 			 * if the gateway is our own address, which is
3955 			 * sometimes used to install a route to a p2p link.
3956 			 */
3957 			if (!nd6_is_addr_neighbor(&gw6, ifp, 0) ||
3958 			    (ia6 = in6ifa_ifpwithaddr(ifp, &gw6.sin6_addr))) {
3959 				/*
3960 				 * We allow this kind of tricky route only
3961 				 * when the outgoing interface is p2p.
3962 				 * XXX: we may need a more generic rule here.
3963 				 */
3964 				if (ia6 != NULL) {
3965 					ifa_remref(&ia6->ia_ifa);
3966 				}
3967 				if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
3968 					senderr(EHOSTUNREACH);
3969 				}
3970 				goto sendpkt;
3971 			}
3972 
3973 			RT_LOCK_SPIN(rt);
3974 			gw6 = *(SIN6(rt->rt_gateway));
3975 
3976 			/* If hint is now down, give up */
3977 			if (!(rt->rt_flags & RTF_UP)) {
3978 				RT_UNLOCK(rt);
3979 				senderr(EHOSTUNREACH);
3980 			}
3981 
3982 			/* If there's no gateway route, look it up */
3983 			if ((gwrt = rt->rt_gwroute) == NULL) {
3984 				RT_UNLOCK(rt);
3985 				goto lookup;
3986 			}
3987 			/* Become a regular mutex */
3988 			RT_CONVERT_LOCK(rt);
3989 
3990 			/*
3991 			 * Take gwrt's lock while holding route's lock;
3992 			 * this is okay since gwrt never points back
3993 			 * to rt, so no lock ordering issues.
3994 			 */
3995 			RT_LOCK_SPIN(gwrt);
3996 			if (!(gwrt->rt_flags & RTF_UP)) {
3997 				rt->rt_gwroute = NULL;
3998 				RT_UNLOCK(gwrt);
3999 				RT_UNLOCK(rt);
4000 				rtfree(gwrt);
4001 lookup:
4002 				lck_mtx_lock(rnh_lock);
4003 				gwrt = rtalloc1_scoped_locked(SA(&gw6), 1, 0,
4004 				    ifp->if_index);
4005 
4006 				RT_LOCK(rt);
4007 				/*
4008 				 * Bail out if the route is down, no route
4009 				 * to gateway, circular route, or if the
4010 				 * gateway portion of "rt" has changed.
4011 				 */
4012 				if (!(rt->rt_flags & RTF_UP) ||
4013 				    gwrt == NULL || gwrt == rt ||
4014 				    SOCKADDR_CMP(SA(&gw6), rt->rt_gateway, SA(&gw6)->sa_len) != 0) {
4015 					if (gwrt == rt) {
4016 						RT_REMREF_LOCKED(gwrt);
4017 						gwrt = NULL;
4018 					}
4019 					RT_UNLOCK(rt);
4020 					if (gwrt != NULL) {
4021 						rtfree_locked(gwrt);
4022 					}
4023 					lck_mtx_unlock(rnh_lock);
4024 					senderr(EHOSTUNREACH);
4025 				}
4026 				VERIFY(gwrt != NULL);
4027 				/*
4028 				 * Set gateway route; callee adds ref to gwrt;
4029 				 * gwrt has an extra ref from rtalloc1() for
4030 				 * this routine.
4031 				 */
4032 				rt_set_gwroute(rt, rt_key(rt), gwrt);
4033 				RT_UNLOCK(rt);
4034 				lck_mtx_unlock(rnh_lock);
4035 				/* Remember to release/free "rt" at the end */
4036 				rtrele = rt;
4037 				rt = gwrt;
4038 			} else {
4039 				RT_ADDREF_LOCKED(gwrt);
4040 				RT_UNLOCK(gwrt);
4041 				RT_UNLOCK(rt);
4042 				/* Remember to release/free "rt" at the end */
4043 				rtrele = rt;
4044 				rt = gwrt;
4045 			}
4046 			VERIFY(rt == gwrt);
4047 
4048 			/*
4049 			 * This is an opportunity to revalidate the parent
4050 			 * route's gwroute, in case it now points to a dead
4051 			 * route entry.  Parent route won't go away since the
4052 			 * clone (hint) holds a reference to it.  rt == gwrt.
4053 			 */
4054 			RT_LOCK_SPIN(hint);
4055 			if ((hint->rt_flags & (RTF_WASCLONED | RTF_UP)) ==
4056 			    (RTF_WASCLONED | RTF_UP)) {
4057 				rtentry_ref_t prt = hint->rt_parent;
4058 				VERIFY(prt != NULL);
4059 
4060 				RT_CONVERT_LOCK(hint);
4061 				RT_ADDREF(prt);
4062 				RT_UNLOCK(hint);
4063 				rt_revalidate_gwroute(prt, rt);
4064 				RT_REMREF(prt);
4065 			} else {
4066 				RT_UNLOCK(hint);
4067 			}
4068 
4069 			RT_LOCK_SPIN(rt);
4070 			/* rt == gwrt; if it is now down, give up */
4071 			if (!(rt->rt_flags & RTF_UP)) {
4072 				RT_UNLOCK(rt);
4073 				rtfree(rt);
4074 				rt = NULL;
4075 				/* "rtrele" == original "rt" */
4076 				senderr(EHOSTUNREACH);
4077 			}
4078 		}
4079 
4080 		/* Become a regular mutex */
4081 		RT_CONVERT_LOCK(rt);
4082 	}
4083 
4084 	/*
4085 	 * Address resolution or Neighbor Unreachability Detection
4086 	 * for the next hop.
4087 	 * At this point, the destination of the packet must be a unicast
4088 	 * or an anycast address(i.e. not a multicast).
4089 	 */
4090 
4091 	/* Look up the neighbor cache for the nexthop */
4092 	if (rt && (rt->rt_flags & RTF_LLINFO) != 0) {
4093 		ln = rt->rt_llinfo;
4094 	} else {
4095 		struct sockaddr_in6 sin6;
4096 		/*
4097 		 * Clear out Scope ID field in case it is set.
4098 		 */
4099 		sin6 = *dst;
4100 		if (in6_embedded_scope) {
4101 			sin6.sin6_scope_id = 0;
4102 		}
4103 		/*
4104 		 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
4105 		 * the condition below is not very efficient.  But we believe
4106 		 * it is tolerable, because this should be a rare case.
4107 		 * Must drop rt_lock since nd6_is_addr_neighbor() calls
4108 		 * nd6_lookup() and acquires rnh_lock.
4109 		 */
4110 		if (rt != NULL) {
4111 			RT_UNLOCK(rt);
4112 		}
4113 		if (nd6_is_addr_neighbor(&sin6, ifp, 0)) {
4114 			/* "rtrele" may have been used, so clean up "rt" now */
4115 			if (rt != NULL) {
4116 				/* Don't free "hint0" */
4117 				if (rt == hint0) {
4118 					RT_REMREF(rt);
4119 				} else {
4120 					rtfree(rt);
4121 				}
4122 			}
4123 			/* Callee returns a locked route upon success */
4124 			rt = nd6_lookup(&dst->sin6_addr, 1, ifp, 0);
4125 			if (rt != NULL) {
4126 				RT_LOCK_ASSERT_HELD(rt);
4127 				ln = rt->rt_llinfo;
4128 			}
4129 		} else if (rt != NULL) {
4130 			RT_LOCK(rt);
4131 		}
4132 	}
4133 
4134 	if (!ln || !rt) {
4135 		if (rt != NULL) {
4136 			RT_UNLOCK(rt);
4137 		}
4138 		ndi = ND_IFINFO(ifp);
4139 		VERIFY(ndi != NULL && ndi->initialized);
4140 		lck_mtx_lock(&ndi->lock);
4141 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
4142 		    !(ndi->flags & ND6_IFF_PERFORMNUD)) {
4143 			lck_mtx_unlock(&ndi->lock);
4144 			log(LOG_DEBUG,
4145 			    "nd6_output: can't allocate llinfo for %s "
4146 			    "(ln=0x%llx, rt=0x%llx)\n",
4147 			    ip6_sprintf(&dst->sin6_addr),
4148 			    (uint64_t)VM_KERNEL_ADDRPERM(ln),
4149 			    (uint64_t)VM_KERNEL_ADDRPERM(rt));
4150 			senderr(EIO);   /* XXX: good error? */
4151 		}
4152 		lck_mtx_unlock(&ndi->lock);
4153 
4154 		goto sendpkt;   /* send anyway */
4155 	}
4156 
4157 	net_update_uptime();
4158 	timenow = net_uptime();
4159 
4160 	/* We don't have to do link-layer address resolution on a p2p link. */
4161 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
4162 	    ln->ln_state < ND6_LLINFO_REACHABLE) {
4163 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);
4164 		ln_setexpire(ln, timenow + nd6_gctimer);
4165 	}
4166 
4167 	/*
4168 	 * The first time we send a packet to a neighbor whose entry is
4169 	 * STALE, we have to change the state to DELAY and a sets a timer to
4170 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
4171 	 * neighbor unreachability detection on expiration.
4172 	 * (RFC 4861 7.3.3)
4173 	 */
4174 	if (ln->ln_state == ND6_LLINFO_STALE) {
4175 		ln->ln_asked = 0;
4176 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_DELAY);
4177 		ln_setexpire(ln, timenow + nd6_delay);
4178 		/* N.B.: we will re-arm the timer below. */
4179 		_CASSERT(ND6_LLINFO_DELAY > ND6_LLINFO_INCOMPLETE);
4180 	}
4181 
4182 	/*
4183 	 * If the neighbor cache entry has a state other than INCOMPLETE
4184 	 * (i.e. its link-layer address is already resolved), just
4185 	 * send the packet.
4186 	 */
4187 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE) {
4188 		RT_UNLOCK(rt);
4189 		/*
4190 		 * Move this entry to the head of the queue so that it is
4191 		 * less likely for this entry to be a target of forced
4192 		 * garbage collection (see nd6_rtrequest()).  Do this only
4193 		 * if the entry is non-permanent (as permanent ones will
4194 		 * never be purged), and if the number of active entries
4195 		 * is at least half of the threshold.
4196 		 */
4197 		if (ln->ln_state == ND6_LLINFO_DELAY ||
4198 		    (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4199 		    nd6_inuse >= (ip6_neighborgcthresh >> 1))) {
4200 			lck_mtx_lock(rnh_lock);
4201 			if (ln->ln_state == ND6_LLINFO_DELAY) {
4202 				nd6_sched_timeout(NULL, NULL);
4203 			}
4204 			if (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4205 			    nd6_inuse >= (ip6_neighborgcthresh >> 1)) {
4206 				RT_LOCK_SPIN(rt);
4207 				if (ln->ln_flags & ND6_LNF_IN_USE) {
4208 					LN_DEQUEUE(ln);
4209 					LN_INSERTHEAD(ln);
4210 				}
4211 				RT_UNLOCK(rt);
4212 			}
4213 			lck_mtx_unlock(rnh_lock);
4214 		}
4215 		goto sendpkt;
4216 	}
4217 
4218 	/*
4219 	 * If this is a prefix proxy route, record the inbound interface
4220 	 * so that it can be excluded from the list of interfaces eligible
4221 	 * for forwarding the proxied NS in nd6_prproxy_ns_output().
4222 	 */
4223 	if (rt->rt_flags & RTF_PROXY) {
4224 		ln->ln_exclifp = ((origifp == ifp) ? NULL : origifp);
4225 	}
4226 
4227 	/*
4228 	 * There is a neighbor cache entry, but no ethernet address
4229 	 * response yet.  Replace the held mbuf (if any) with this
4230 	 * latest one.
4231 	 *
4232 	 * This code conforms to the rate-limiting rule described in Section
4233 	 * 7.2.2 of RFC 4861, because the timer is set correctly after sending
4234 	 * an NS below.
4235 	 */
4236 	if (ln->ln_state == ND6_LLINFO_NOSTATE) {
4237 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_INCOMPLETE);
4238 	}
4239 	if (ln->ln_hold) {
4240 		m_freem_list(ln->ln_hold);
4241 	}
4242 	ln->ln_hold = m0;
4243 	if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
4244 		ln->ln_asked++;
4245 		ndi = ND_IFINFO(ifp);
4246 		VERIFY(ndi != NULL && ndi->initialized);
4247 		lck_mtx_lock(&ndi->lock);
4248 		ln_setexpire(ln, timenow + ndi->retrans / 1000);
4249 		lck_mtx_unlock(&ndi->lock);
4250 		RT_UNLOCK(rt);
4251 		/* We still have a reference on rt (for ln) */
4252 		if (ip6_forwarding) {
4253 			nd6_prproxy_ns_output(ifp, origifp, NULL,
4254 			    &dst->sin6_addr, ln);
4255 		} else {
4256 			nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, NULL, 0);
4257 		}
4258 		lck_mtx_lock(rnh_lock);
4259 		nd6_sched_timeout(NULL, NULL);
4260 		lck_mtx_unlock(rnh_lock);
4261 	} else {
4262 		RT_UNLOCK(rt);
4263 	}
4264 	/*
4265 	 * Move this entry to the head of the queue so that it is
4266 	 * less likely for this entry to be a target of forced
4267 	 * garbage collection (see nd6_rtrequest()).  Do this only
4268 	 * if the entry is non-permanent (as permanent ones will
4269 	 * never be purged), and if the number of active entries
4270 	 * is at least half of the threshold.
4271 	 */
4272 	if (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4273 	    nd6_inuse >= (ip6_neighborgcthresh >> 1)) {
4274 		lck_mtx_lock(rnh_lock);
4275 		RT_LOCK_SPIN(rt);
4276 		if (ln->ln_flags & ND6_LNF_IN_USE) {
4277 			LN_DEQUEUE(ln);
4278 			LN_INSERTHEAD(ln);
4279 		}
4280 		/* Clean up "rt" now while we can */
4281 		if (rt == hint0) {
4282 			RT_REMREF_LOCKED(rt);
4283 			RT_UNLOCK(rt);
4284 		} else {
4285 			RT_UNLOCK(rt);
4286 			rtfree_locked(rt);
4287 		}
4288 		rt = NULL;      /* "rt" has been taken care of */
4289 		lck_mtx_unlock(rnh_lock);
4290 	}
4291 	error = 0;
4292 	goto release;
4293 
4294 sendpkt:
4295 	if (rt != NULL) {
4296 		RT_LOCK_ASSERT_NOTHELD(rt);
4297 	}
4298 
4299 	/* discard the packet if IPv6 operation is disabled on the interface */
4300 	if (ifp->if_eflags & IFEF_IPV6_DISABLED) {
4301 		error = ENETDOWN; /* better error? */
4302 		goto bad;
4303 	}
4304 
4305 	if (ifp->if_flags & IFF_LOOPBACK) {
4306 		/* forwarding rules require the original scope_id */
4307 		m0->m_pkthdr.rcvif = origifp;
4308 		error = dlil_output(origifp, PF_INET6, m0, (caddr_t)rt,
4309 		    SA(dst), 0, adv);
4310 		goto release;
4311 	} else {
4312 		/* Do not allow loopback address to wind up on a wire */
4313 		struct ip6_hdr *__single ip6 = mtod(m0, struct ip6_hdr *);
4314 
4315 		if ((IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) ||
4316 		    IN6_IS_ADDR_LOOPBACK(&ip6->ip6_dst))) {
4317 			ip6stat.ip6s_badscope++;
4318 			error = EADDRNOTAVAIL;
4319 			goto bad;
4320 		}
4321 	}
4322 
4323 	if (rt != NULL) {
4324 		RT_LOCK_SPIN(rt);
4325 		/* Mark use timestamp */
4326 		if (rt->rt_llinfo != NULL) {
4327 			nd6_llreach_use(rt->rt_llinfo);
4328 		}
4329 		RT_UNLOCK(rt);
4330 	}
4331 
4332 	mbuf_ref_t mcur = m0;
4333 	uint32_t pktcnt = 0;
4334 
4335 	while (mcur) {
4336 		if (hint != NULL && nstat_collect) {
4337 			int scnt;
4338 
4339 			if ((mcur->m_pkthdr.csum_flags & CSUM_TSO_IPV6) &&
4340 			    (mcur->m_pkthdr.tso_segsz > 0)) {
4341 				scnt = mcur->m_pkthdr.len / mcur->m_pkthdr.tso_segsz;
4342 			} else {
4343 				scnt = 1;
4344 			}
4345 
4346 			nstat_route_tx(hint, scnt, mcur->m_pkthdr.len, 0);
4347 		}
4348 		pktcnt++;
4349 
4350 		mcur->m_pkthdr.rcvif = NULL;
4351 		mcur = mcur->m_nextpkt;
4352 	}
4353 	if (pktcnt > ip6_maxchainsent) {
4354 		ip6_maxchainsent = pktcnt;
4355 	}
4356 	error = dlil_output(ifp, PF_INET6, m0, (caddr_t)rt, SA(dst), 0, adv);
4357 	goto release;
4358 
4359 bad:
4360 	if (m0 != NULL) {
4361 		m_freem_list(m0);
4362 	}
4363 
4364 release:
4365 	/* Clean up "rt" unless it's already been done */
4366 	if (rt != NULL) {
4367 		RT_LOCK_SPIN(rt);
4368 		if (rt == hint0) {
4369 			RT_REMREF_LOCKED(rt);
4370 			RT_UNLOCK(rt);
4371 		} else {
4372 			RT_UNLOCK(rt);
4373 			rtfree(rt);
4374 		}
4375 	}
4376 	/* And now clean up "rtrele" if there is any */
4377 	if (rtrele != NULL) {
4378 		RT_LOCK_SPIN(rtrele);
4379 		if (rtrele == hint0) {
4380 			RT_REMREF_LOCKED(rtrele);
4381 			RT_UNLOCK(rtrele);
4382 		} else {
4383 			RT_UNLOCK(rtrele);
4384 			rtfree(rtrele);
4385 		}
4386 	}
4387 	return error;
4388 }
4389 #undef senderr
4390 
4391 int
nd6_need_cache(struct ifnet * ifp)4392 nd6_need_cache(struct ifnet *ifp)
4393 {
4394 	/*
4395 	 * XXX: we currently do not make neighbor cache on any interface
4396 	 * other than ARCnet, Ethernet, FDDI and GIF.
4397 	 *
4398 	 * RFC2893 says:
4399 	 * - unidirectional tunnels needs no ND
4400 	 */
4401 	switch (ifp->if_type) {
4402 	case IFT_ARCNET:
4403 	case IFT_ETHER:
4404 	case IFT_FDDI:
4405 	case IFT_IEEE1394:
4406 	case IFT_L2VLAN:
4407 	case IFT_IEEE8023ADLAG:
4408 #if IFT_IEEE80211
4409 	case IFT_IEEE80211:
4410 #endif
4411 	case IFT_GIF:           /* XXX need more cases? */
4412 	case IFT_PPP:
4413 #if IFT_TUNNEL
4414 	case IFT_TUNNEL:
4415 #endif
4416 	case IFT_BRIDGE:
4417 	case IFT_CELLULAR:
4418 		return 1;
4419 	default:
4420 		return 0;
4421 	}
4422 }
4423 
4424 /*
4425  * This is the ND pre-output routine; care must be taken to ensure that
4426  * the "hint" route never gets freed via rtfree(), since the caller may
4427  * have stored it inside a struct route with a reference held for that
4428  * placeholder.
4429  */
4430 errno_t
nd6_lookup_ipv6(ifnet_t ifp,const struct sockaddr_in6 * ip6_dest,struct sockaddr_dl * ll_dest,size_t ll_dest_len,route_t hint,mbuf_t packet)4431 nd6_lookup_ipv6(ifnet_t  ifp, const struct sockaddr_in6 *ip6_dest,
4432     struct sockaddr_dl *ll_dest, size_t ll_dest_len, route_t hint,
4433     mbuf_t packet)
4434 {
4435 	route_t __single route = hint;
4436 	errno_t result = 0;
4437 	struct sockaddr_dl *__single sdl = NULL;
4438 	size_t  copy_len;
4439 
4440 	if (ifp == NULL || ip6_dest == NULL) {
4441 		return EINVAL;
4442 	}
4443 
4444 	if (ip6_dest->sin6_family != AF_INET6) {
4445 		return EAFNOSUPPORT;
4446 	}
4447 
4448 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING)) {
4449 		return ENETDOWN;
4450 	}
4451 
4452 	if (hint != NULL) {
4453 		/*
4454 		 * Callee holds a reference on the route and returns
4455 		 * with the route entry locked, upon success.
4456 		 */
4457 		result = route_to_gwroute(SA(ip6_dest), hint, &route);
4458 		if (result != 0) {
4459 			return result;
4460 		}
4461 		if (route != NULL) {
4462 			RT_LOCK_ASSERT_HELD(route);
4463 		}
4464 	}
4465 
4466 	if ((packet != NULL && (packet->m_flags & M_MCAST) != 0) ||
4467 	    ((ifp->if_flags & IFF_MULTICAST) &&
4468 	    IN6_IS_ADDR_MULTICAST(&ip6_dest->sin6_addr))) {
4469 		if (route != NULL) {
4470 			RT_UNLOCK(route);
4471 		}
4472 		result = dlil_resolve_multi(ifp, SA(ip6_dest), SA(ll_dest), ll_dest_len);
4473 		if (route != NULL) {
4474 			RT_LOCK(route);
4475 		}
4476 		goto release;
4477 	} else if (route == NULL) {
4478 		/*
4479 		 * rdar://24596652
4480 		 * For unicast, lookup existing ND6 entries but
4481 		 * do not trigger a resolution
4482 		 */
4483 		lck_mtx_lock(rnh_lock);
4484 		route = rt_lookup(TRUE,
4485 		    __DECONST(struct sockaddr *, ip6_dest), NULL,
4486 		    rt_tables[AF_INET6], ifp->if_index);
4487 		lck_mtx_unlock(rnh_lock);
4488 
4489 		if (route != NULL) {
4490 			RT_LOCK(route);
4491 		}
4492 	}
4493 
4494 	if (route == NULL) {
4495 		/*
4496 		 * This could happen, if we could not allocate memory or
4497 		 * if route_to_gwroute() didn't return a route.
4498 		 */
4499 		result = ENOBUFS;
4500 		goto release;
4501 	}
4502 
4503 	if (route->rt_gateway->sa_family != AF_LINK) {
4504 		nd6log0(error, "%s: route %s on %s%d gateway address not AF_LINK\n",
4505 		    __func__, ip6_sprintf(&ip6_dest->sin6_addr),
4506 		    route->rt_ifp->if_name, route->rt_ifp->if_unit);
4507 		result = EADDRNOTAVAIL;
4508 		goto release;
4509 	}
4510 
4511 	sdl = SDL(route->rt_gateway);
4512 	if (sdl->sdl_alen == 0) {
4513 		/* this should be impossible, but we bark here for debugging */
4514 		nd6log(error, "%s: route %s on %s%d sdl_alen == 0\n", __func__,
4515 		    ip6_sprintf(&ip6_dest->sin6_addr), route->rt_ifp->if_name,
4516 		    route->rt_ifp->if_unit);
4517 		result = EHOSTUNREACH;
4518 		goto release;
4519 	}
4520 
4521 	copy_len = sdl->sdl_len <= ll_dest_len ? sdl->sdl_len : ll_dest_len;
4522 	SOCKADDR_COPY(sdl, ll_dest, copy_len);
4523 
4524 release:
4525 	if (route != NULL) {
4526 		if (route == hint) {
4527 			RT_REMREF_LOCKED(route);
4528 			RT_UNLOCK(route);
4529 		} else {
4530 			RT_UNLOCK(route);
4531 			rtfree(route);
4532 		}
4533 	}
4534 	return result;
4535 }
4536 
4537 #if (DEVELOPMENT || DEBUG)
4538 
4539 static int sysctl_nd6_lookup_ipv6 SYSCTL_HANDLER_ARGS;
4540 SYSCTL_PROC(_net_inet6_icmp6, OID_AUTO, nd6_lookup_ipv6,
4541     CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_LOCKED, 0, 0,
4542     sysctl_nd6_lookup_ipv6, "S", "");
4543 
4544 int
4545 sysctl_nd6_lookup_ipv6 SYSCTL_HANDLER_ARGS
4546 {
4547 #pragma unused(oidp, arg1, arg2)
4548 	int error = 0;
4549 	struct nd6_lookup_ipv6_args nd6_lookup_ipv6_args;
4550 	ifnet_ref_t ifp = NULL;
4551 
4552 	/*
4553 	 * Only root can lookup MAC addresses
4554 	 */
4555 	error = proc_suser(current_proc());
4556 	if (error != 0) {
4557 		nd6log0(error, "%s: proc_suser() error %d\n",
4558 		    __func__, error);
4559 		goto done;
4560 	}
4561 	if (req->oldptr == USER_ADDR_NULL) {
4562 		req->oldidx = sizeof(struct nd6_lookup_ipv6_args);
4563 	}
4564 	if (req->newptr == USER_ADDR_NULL) {
4565 		goto done;
4566 	}
4567 	if (req->oldlen != sizeof(struct nd6_lookup_ipv6_args) ||
4568 	    req->newlen != sizeof(struct nd6_lookup_ipv6_args)) {
4569 		error = EINVAL;
4570 		nd6log0(error, "%s: bad req, error %d\n",
4571 		    __func__, error);
4572 		goto done;
4573 	}
4574 	error = SYSCTL_IN(req, &nd6_lookup_ipv6_args,
4575 	    sizeof(struct nd6_lookup_ipv6_args));
4576 	if (error != 0) {
4577 		nd6log0(error, "%s: SYSCTL_IN() error %d\n",
4578 		    __func__, error);
4579 		goto done;
4580 	}
4581 
4582 	if (nd6_lookup_ipv6_args.ll_dest_len > sizeof(nd6_lookup_ipv6_args.ll_dest_)) {
4583 		error = EINVAL;
4584 		nd6log0(error, "%s: bad ll_dest_len, error %d\n",
4585 		    __func__, error);
4586 		goto done;
4587 	}
4588 
4589 	/* Make sure to terminate the string */
4590 	nd6_lookup_ipv6_args.ifname[IFNAMSIZ - 1] = 0;
4591 
4592 	error = ifnet_find_by_name(__unsafe_null_terminated_from_indexable(nd6_lookup_ipv6_args.ifname), &ifp);
4593 	if (error != 0) {
4594 		nd6log0(error, "%s: ifnet_find_by_name() error %d\n",
4595 		    __func__, error);
4596 		goto done;
4597 	}
4598 
4599 	error = nd6_lookup_ipv6(ifp, &nd6_lookup_ipv6_args.ip6_dest,
4600 	    &nd6_lookup_ipv6_args.ll_dest_._sdl,
4601 	    nd6_lookup_ipv6_args.ll_dest_len, NULL, NULL);
4602 	if (error != 0) {
4603 		nd6log0(error, "%s: nd6_lookup_ipv6() error %d\n",
4604 		    __func__, error);
4605 		goto done;
4606 	}
4607 
4608 	error = SYSCTL_OUT(req, &nd6_lookup_ipv6_args,
4609 	    sizeof(struct nd6_lookup_ipv6_args));
4610 	if (error != 0) {
4611 		nd6log0(error, "%s: SYSCTL_OUT() error %d\n",
4612 		    __func__, error);
4613 		goto done;
4614 	}
4615 done:
4616 	return error;
4617 }
4618 
4619 #endif /* (DEVELOPMENT || DEBUG) */
4620 
4621 int
nd6_setifinfo(struct ifnet * ifp,u_int32_t before,u_int32_t after)4622 nd6_setifinfo(struct ifnet *ifp, u_int32_t before, u_int32_t after)
4623 {
4624 	uint32_t b, a;
4625 	int err = 0;
4626 
4627 	/*
4628 	 * Handle ND6_IFF_IFDISABLED
4629 	 */
4630 	if ((before & ND6_IFF_IFDISABLED) ||
4631 	    (after & ND6_IFF_IFDISABLED)) {
4632 		b = (before & ND6_IFF_IFDISABLED);
4633 		a = (after & ND6_IFF_IFDISABLED);
4634 
4635 		if (b != a && (err = nd6_if_disable(ifp,
4636 		    ((int32_t)(a - b) > 0))) != 0) {
4637 			goto done;
4638 		}
4639 	}
4640 
4641 	/*
4642 	 * Handle ND6_IFF_PROXY_PREFIXES
4643 	 */
4644 	if ((before & ND6_IFF_PROXY_PREFIXES) ||
4645 	    (after & ND6_IFF_PROXY_PREFIXES)) {
4646 		b = (before & ND6_IFF_PROXY_PREFIXES);
4647 		a = (after & ND6_IFF_PROXY_PREFIXES);
4648 
4649 		if (b != a && (err = nd6_if_prproxy(ifp,
4650 		    ((int32_t)(a - b) > 0))) != 0) {
4651 			goto done;
4652 		}
4653 	}
4654 done:
4655 	return err;
4656 }
4657 
4658 /*
4659  * Enable/disable IPv6 on an interface, called as part of
4660  * setting/clearing ND6_IFF_IFDISABLED, or during DAD failure.
4661  */
4662 int
nd6_if_disable(struct ifnet * ifp,boolean_t enable)4663 nd6_if_disable(struct ifnet *ifp, boolean_t enable)
4664 {
4665 	if (enable) {
4666 		if_set_eflags(ifp, IFEF_IPV6_DISABLED);
4667 	} else {
4668 		if_clear_eflags(ifp, IFEF_IPV6_DISABLED);
4669 	}
4670 
4671 	return 0;
4672 }
4673 
4674 static int
4675 nd6_sysctl_drlist SYSCTL_HANDLER_ARGS
4676 {
4677 #pragma unused(oidp, arg1, arg2)
4678 	char pbuf[MAX_IPv6_STR_LEN];
4679 	struct nd_defrouter *__single dr;
4680 	int error = 0;
4681 
4682 	if (req->newptr != USER_ADDR_NULL) {
4683 		return EPERM;
4684 	}
4685 
4686 	/* XXX Handle mapped defrouter entries */
4687 	lck_mtx_lock(nd6_mutex);
4688 	if (proc_is64bit(req->p)) {
4689 		struct in6_defrouter_64 d;
4690 
4691 		bzero(&d, sizeof(d));
4692 		d.rtaddr.sin6_family = AF_INET6;
4693 		d.rtaddr.sin6_len = sizeof(d.rtaddr);
4694 
4695 		TAILQ_FOREACH(dr, &nd_defrouter_list, dr_entry) {
4696 			d.rtaddr.sin6_addr = dr->rtaddr;
4697 			if (in6_recoverscope(&d.rtaddr,
4698 			    &dr->rtaddr, dr->ifp) != 0) {
4699 				log(LOG_ERR, "scope error in default router "
4700 				    "list (%s)\n", inet_ntop(AF_INET6,
4701 				    &dr->rtaddr, pbuf, sizeof(pbuf)));
4702 			}
4703 			d.flags = dr->flags;
4704 			d.stateflags = dr->stateflags;
4705 			d.rtlifetime = (u_short)dr->rtlifetime;
4706 			d.expire = (int)nddr_getexpire(dr);
4707 			d.if_index = dr->ifp->if_index;
4708 			error = SYSCTL_OUT(req, &d, sizeof(d));
4709 			if (error != 0) {
4710 				break;
4711 			}
4712 		}
4713 	} else {
4714 		struct in6_defrouter_32 d;
4715 
4716 		bzero(&d, sizeof(d));
4717 		d.rtaddr.sin6_family = AF_INET6;
4718 		d.rtaddr.sin6_len = sizeof(d.rtaddr);
4719 
4720 		TAILQ_FOREACH(dr, &nd_defrouter_list, dr_entry) {
4721 			d.rtaddr.sin6_addr = dr->rtaddr;
4722 			if (in6_recoverscope(&d.rtaddr,
4723 			    &dr->rtaddr, dr->ifp) != 0) {
4724 				log(LOG_ERR, "scope error in default router "
4725 				    "list (%s)\n", inet_ntop(AF_INET6,
4726 				    &dr->rtaddr, pbuf, sizeof(pbuf)));
4727 			}
4728 			d.flags = dr->flags;
4729 			d.stateflags = dr->stateflags;
4730 			d.rtlifetime = (u_short)dr->rtlifetime;
4731 			d.expire = (int)nddr_getexpire(dr);
4732 			d.if_index = dr->ifp->if_index;
4733 			error = SYSCTL_OUT(req, &d, sizeof(d));
4734 			if (error != 0) {
4735 				break;
4736 			}
4737 		}
4738 	}
4739 	lck_mtx_unlock(nd6_mutex);
4740 	return error;
4741 }
4742 
4743 static int
4744 nd6_sysctl_prlist SYSCTL_HANDLER_ARGS
4745 {
4746 #pragma unused(oidp, arg1, arg2)
4747 	char pbuf[MAX_IPv6_STR_LEN];
4748 	struct nd_pfxrouter *__single pfr;
4749 	struct sockaddr_in6 s6;
4750 	struct nd_prefix *__single pr;
4751 	int error = 0;
4752 
4753 	if (req->newptr != USER_ADDR_NULL) {
4754 		return EPERM;
4755 	}
4756 
4757 	SOCKADDR_ZERO(&s6, sizeof(s6));
4758 	s6.sin6_family = AF_INET6;
4759 	s6.sin6_len = sizeof(s6);
4760 
4761 	/* XXX Handle mapped defrouter entries */
4762 	lck_mtx_lock(nd6_mutex);
4763 	if (proc_is64bit(req->p)) {
4764 		struct in6_prefix_64 p;
4765 
4766 		bzero(&p, sizeof(p));
4767 		p.origin = PR_ORIG_RA;
4768 
4769 		LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
4770 			NDPR_LOCK(pr);
4771 			p.prefix = pr->ndpr_prefix;
4772 			if (in6_recoverscope(&p.prefix,
4773 			    &pr->ndpr_prefix.sin6_addr, pr->ndpr_ifp) != 0) {
4774 				log(LOG_ERR, "scope error in "
4775 				    "prefix list (%s)\n", inet_ntop(AF_INET6,
4776 				    &p.prefix.sin6_addr, pbuf, sizeof(pbuf)));
4777 			}
4778 			p.raflags = pr->ndpr_raf;
4779 			p.prefixlen = pr->ndpr_plen;
4780 			p.vltime = pr->ndpr_vltime;
4781 			p.pltime = pr->ndpr_pltime;
4782 			p.if_index = pr->ndpr_ifp->if_index;
4783 			p.expire = (u_long)ndpr_getexpire(pr);
4784 			p.refcnt = pr->ndpr_addrcnt;
4785 			p.flags = pr->ndpr_stateflags;
4786 			p.advrtrs = 0;
4787 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
4788 			p.advrtrs++;
4789 			error = SYSCTL_OUT(req, &p, sizeof(p));
4790 			if (error != 0) {
4791 				NDPR_UNLOCK(pr);
4792 				break;
4793 			}
4794 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
4795 				s6.sin6_addr = pfr->router->rtaddr;
4796 				if (in6_recoverscope(&s6, &pfr->router->rtaddr,
4797 				    pfr->router->ifp) != 0) {
4798 					log(LOG_ERR,
4799 					    "scope error in prefix list (%s)\n",
4800 					    inet_ntop(AF_INET6, &s6.sin6_addr,
4801 					    pbuf, sizeof(pbuf)));
4802 				}
4803 				error = SYSCTL_OUT(req, &s6, sizeof(s6));
4804 				if (error != 0) {
4805 					break;
4806 				}
4807 			}
4808 			NDPR_UNLOCK(pr);
4809 			if (error != 0) {
4810 				break;
4811 			}
4812 		}
4813 	} else {
4814 		struct in6_prefix_32 p;
4815 
4816 		bzero(&p, sizeof(p));
4817 		p.origin = PR_ORIG_RA;
4818 
4819 		LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
4820 			NDPR_LOCK(pr);
4821 			p.prefix = pr->ndpr_prefix;
4822 			if (in6_recoverscope(&p.prefix,
4823 			    &pr->ndpr_prefix.sin6_addr, pr->ndpr_ifp) != 0) {
4824 				log(LOG_ERR,
4825 				    "scope error in prefix list (%s)\n",
4826 				    inet_ntop(AF_INET6, &p.prefix.sin6_addr,
4827 				    pbuf, sizeof(pbuf)));
4828 			}
4829 			p.raflags = pr->ndpr_raf;
4830 			p.prefixlen = pr->ndpr_plen;
4831 			p.vltime = pr->ndpr_vltime;
4832 			p.pltime = pr->ndpr_pltime;
4833 			p.if_index = pr->ndpr_ifp->if_index;
4834 			p.expire = (u_int32_t)ndpr_getexpire(pr);
4835 			p.refcnt = pr->ndpr_addrcnt;
4836 			p.flags = pr->ndpr_stateflags;
4837 			p.advrtrs = 0;
4838 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
4839 			p.advrtrs++;
4840 			error = SYSCTL_OUT(req, &p, sizeof(p));
4841 			if (error != 0) {
4842 				NDPR_UNLOCK(pr);
4843 				break;
4844 			}
4845 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
4846 				s6.sin6_addr = pfr->router->rtaddr;
4847 				if (in6_recoverscope(&s6, &pfr->router->rtaddr,
4848 				    pfr->router->ifp) != 0) {
4849 					log(LOG_ERR,
4850 					    "scope error in prefix list (%s)\n",
4851 					    inet_ntop(AF_INET6, &s6.sin6_addr,
4852 					    pbuf, sizeof(pbuf)));
4853 				}
4854 				error = SYSCTL_OUT(req, &s6, sizeof(s6));
4855 				if (error != 0) {
4856 					break;
4857 				}
4858 			}
4859 			NDPR_UNLOCK(pr);
4860 			if (error != 0) {
4861 				break;
4862 			}
4863 		}
4864 	}
4865 	lck_mtx_unlock(nd6_mutex);
4866 
4867 	return error;
4868 }
4869 
4870 void
in6_ifaddr_set_dadprogress(struct in6_ifaddr * ia)4871 in6_ifaddr_set_dadprogress(struct in6_ifaddr *ia)
4872 {
4873 	ifnet_ref_t ifp = ia->ia_ifp;
4874 	uint32_t flags = IN6_IFF_TENTATIVE;
4875 	uint32_t optdad = nd6_optimistic_dad;
4876 	struct nd_ifinfo *__single ndi = NULL;
4877 
4878 	ndi = ND_IFINFO(ifp);
4879 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
4880 	if (!(ndi->flags & ND6_IFF_DAD)) {
4881 		return;
4882 	}
4883 
4884 	if (optdad) {
4885 		if (ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
4886 			optdad = 0;
4887 		} else {
4888 			lck_mtx_lock(&ndi->lock);
4889 			if ((ndi->flags & ND6_IFF_REPLICATED) != 0) {
4890 				optdad = 0;
4891 			}
4892 			lck_mtx_unlock(&ndi->lock);
4893 		}
4894 	}
4895 
4896 	if (optdad) {
4897 		if ((optdad & ND6_OPTIMISTIC_DAD_LINKLOCAL) &&
4898 		    IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr)) {
4899 			flags = IN6_IFF_OPTIMISTIC;
4900 		} else if ((optdad & ND6_OPTIMISTIC_DAD_AUTOCONF) &&
4901 		    (ia->ia6_flags & IN6_IFF_AUTOCONF)) {
4902 			if (ia->ia6_flags & IN6_IFF_TEMPORARY) {
4903 				if (optdad & ND6_OPTIMISTIC_DAD_TEMPORARY) {
4904 					flags = IN6_IFF_OPTIMISTIC;
4905 				}
4906 			} else if (ia->ia6_flags & IN6_IFF_SECURED) {
4907 				if (optdad & ND6_OPTIMISTIC_DAD_SECURED) {
4908 					flags = IN6_IFF_OPTIMISTIC;
4909 				}
4910 			} else {
4911 				/*
4912 				 * Keeping the behavior for temp and CGA
4913 				 * SLAAC addresses to have a knob for optimistic
4914 				 * DAD.
4915 				 * Other than that if ND6_OPTIMISTIC_DAD_AUTOCONF
4916 				 * is set, we should default to optimistic
4917 				 * DAD.
4918 				 * For now this means SLAAC addresses with interface
4919 				 * identifier derived from modified EUI-64 bit
4920 				 * identifiers.
4921 				 */
4922 				flags = IN6_IFF_OPTIMISTIC;
4923 			}
4924 		} else if ((optdad & ND6_OPTIMISTIC_DAD_DYNAMIC) &&
4925 		    (ia->ia6_flags & IN6_IFF_DYNAMIC)) {
4926 			if (ia->ia6_flags & IN6_IFF_TEMPORARY) {
4927 				if (optdad & ND6_OPTIMISTIC_DAD_TEMPORARY) {
4928 					flags = IN6_IFF_OPTIMISTIC;
4929 				}
4930 			} else {
4931 				flags = IN6_IFF_OPTIMISTIC;
4932 			}
4933 		} else if ((optdad & ND6_OPTIMISTIC_DAD_MANUAL) &&
4934 		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC)) {
4935 			/*
4936 			 * rdar://17483438
4937 			 * Bypass tentative for address assignments
4938 			 * not covered above (e.g. manual) upon request
4939 			 */
4940 			if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr) &&
4941 			    !(ia->ia6_flags & IN6_IFF_AUTOCONF) &&
4942 			    !(ia->ia6_flags & IN6_IFF_DYNAMIC)) {
4943 				flags = IN6_IFF_OPTIMISTIC;
4944 			}
4945 		}
4946 	}
4947 
4948 	ia->ia6_flags &= ~(IN6_IFF_DUPLICATED | IN6_IFF_DADPROGRESS);
4949 	ia->ia6_flags |= flags;
4950 
4951 	nd6log2(debug, "%s - %s ifp %s ia6_flags 0x%x\n",
4952 	    __func__,
4953 	    ip6_sprintf(&ia->ia_addr.sin6_addr),
4954 	    if_name(ia->ia_ifp),
4955 	    ia->ia6_flags);
4956 }
4957