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