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