xref: /xnu-8792.41.9/bsd/netinet6/nd6.c (revision 5c2921b07a2480ab43ec66f5b9e41cb872bc554f)
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 		/* check for duplicated secured address */
1465 		if (secured_address_is_duplicated(ia6->ia6_flags) &&
1466 		    nd6_handle_duplicated_ip6_addr(ia6)) {
1467 			/*
1468 			 * nd6_handle_duplicated_ip6_addr() unlocked
1469 			 * (in6_ifaddr_rwlock, ia6->ia_ifa) already.
1470 			 * Still need to release extra reference on
1471 			 * ia6->ia_ifa taken above.
1472 			 */
1473 			IFA_REMREF(&ia6->ia_ifa);
1474 			goto addrloop;
1475 		}
1476 
1477 		/* check address lifetime */
1478 		if (IFA6_IS_INVALID(ia6, timenow)) {
1479 			/*
1480 			 * If the expiring address is temporary, try
1481 			 * regenerating a new one.  This would be useful when
1482 			 * we suspended a laptop PC, then turned it on after a
1483 			 * period that could invalidate all temporary
1484 			 * addresses.  Although we may have to restart the
1485 			 * loop (see below), it must be after purging the
1486 			 * address.  Otherwise, we'd see an infinite loop of
1487 			 * regeneration.
1488 			 */
1489 			if (ip6_use_tempaddr &&
1490 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1491 				/*
1492 				 * NOTE: We have to drop the lock here
1493 				 * because regen_tmpaddr() eventually calls
1494 				 * in6_update_ifa(), which must take the lock
1495 				 * and would otherwise cause a hang.  This is
1496 				 * safe because the goto addrloop leads to a
1497 				 * re-evaluation of the in6_ifaddrs list
1498 				 */
1499 				IFA_UNLOCK(&ia6->ia_ifa);
1500 				lck_rw_done(&in6_ifaddr_rwlock);
1501 				(void) regen_tmpaddr(ia6);
1502 			} else {
1503 				IFA_UNLOCK(&ia6->ia_ifa);
1504 				lck_rw_done(&in6_ifaddr_rwlock);
1505 			}
1506 
1507 			/*
1508 			 * Purging the address would have caused
1509 			 * in6_ifaddr_rwlock to be dropped and reacquired;
1510 			 * therefore search again from the beginning
1511 			 * of in6_ifaddrs list.
1512 			 */
1513 			in6_purgeaddr(&ia6->ia_ifa);
1514 			ap->killed++;
1515 
1516 			if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) == 0) {
1517 				in6_ifstat_inc(ia6->ia_ifa.ifa_ifp, ifs6_addr_expiry_cnt);
1518 				in6_event_enqueue_nwk_wq_entry(IN6_NDP_ADDR_EXPIRY,
1519 				    ia6->ia_ifa.ifa_ifp, &ia6->ia_addr.sin6_addr,
1520 				    0);
1521 			}
1522 			/* Release extra reference taken above */
1523 			IFA_REMREF(&ia6->ia_ifa);
1524 			goto addrloop;
1525 		}
1526 		/*
1527 		 * The lazy timer runs every nd6_prune_lazy seconds with at
1528 		 * most "2 * nd6_prune_lazy - 1" leeway. We consider the worst
1529 		 * case here and make sure we schedule the regular timer if an
1530 		 * interface address is about to expire.
1531 		 */
1532 		if (IFA6_IS_INVALID(ia6, timenow + 3 * nd6_prune_lazy)) {
1533 			ap->aging++;
1534 		} else {
1535 			ap->aging_lazy++;
1536 		}
1537 		IFA_LOCK_ASSERT_HELD(&ia6->ia_ifa);
1538 		if (IFA6_IS_DEPRECATED(ia6, timenow)) {
1539 			ia6->ia6_flags |= IN6_IFF_DEPRECATED;
1540 
1541 			if ((oldflags & IN6_IFF_DEPRECATED) == 0) {
1542 #if SKYWALK
1543 				SK_NXS_MS_IF_ADDR_GENCNT_INC(ia6->ia_ifp);
1544 #endif /* SKYWALK */
1545 				/*
1546 				 * Only enqueue the Deprecated event when the address just
1547 				 * becomes deprecated.
1548 				 * Keep it limited to the stable address as it is common for
1549 				 * older temporary addresses to get deprecated while we generate
1550 				 * new ones.
1551 				 */
1552 				if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) == 0) {
1553 					in6_event_enqueue_nwk_wq_entry(IN6_ADDR_MARKED_DEPRECATED,
1554 					    ia6->ia_ifa.ifa_ifp, &ia6->ia_addr.sin6_addr,
1555 					    0);
1556 				}
1557 			}
1558 			/*
1559 			 * If a temporary address has just become deprecated,
1560 			 * regenerate a new one if possible.
1561 			 */
1562 			if (ip6_use_tempaddr &&
1563 			    (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1564 			    (oldflags & IN6_IFF_DEPRECATED) == 0) {
1565 				/* see NOTE above */
1566 				IFA_UNLOCK(&ia6->ia_ifa);
1567 				lck_rw_done(&in6_ifaddr_rwlock);
1568 				if (regen_tmpaddr(ia6) == 0) {
1569 					/*
1570 					 * A new temporary address is
1571 					 * generated.
1572 					 * XXX: this means the address chain
1573 					 * has changed while we are still in
1574 					 * the loop.  Although the change
1575 					 * would not cause disaster (because
1576 					 * it's not a deletion, but an
1577 					 * addition,) we'd rather restart the
1578 					 * loop just for safety.  Or does this
1579 					 * significantly reduce performance??
1580 					 */
1581 					/* Release extra reference */
1582 					IFA_REMREF(&ia6->ia_ifa);
1583 					goto addrloop;
1584 				}
1585 				lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1586 			} else {
1587 				IFA_UNLOCK(&ia6->ia_ifa);
1588 			}
1589 		} else {
1590 			/*
1591 			 * A new RA might have made a deprecated address
1592 			 * preferred.
1593 			 */
1594 			ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
1595 #if SKYWALK
1596 			if ((oldflags & IN6_IFF_DEPRECATED) != 0) {
1597 				SK_NXS_MS_IF_ADDR_GENCNT_INC(ia6->ia_ifp);
1598 			}
1599 #endif /* SKYWALK */
1600 			IFA_UNLOCK(&ia6->ia_ifa);
1601 		}
1602 		LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
1603 		/* Release extra reference taken above */
1604 		IFA_REMREF(&ia6->ia_ifa);
1605 	}
1606 	lck_rw_done(&in6_ifaddr_rwlock);
1607 }
1608 
1609 static void
nd6_service_expired_prefix(struct nd6svc_arg * ap,uint64_t timenow)1610 nd6_service_expired_prefix(struct nd6svc_arg *ap, uint64_t timenow)
1611 {
1612 	struct nd_prefix *pr = NULL;
1613 
1614 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1615 	lck_mtx_lock(nd6_mutex);
1616 	/* expire prefix list */
1617 	pr = nd_prefix.lh_first;
1618 	while (pr != NULL) {
1619 		ap->found++;
1620 		/*
1621 		 * Skip already processed or defunct prefixes
1622 		 * We may iterate the prefix list from head again
1623 		 * so, we are trying to not revisit the same prefix
1624 		 * for the same instance of nd6_service
1625 		 */
1626 		NDPR_LOCK(pr);
1627 		if (pr->ndpr_stateflags & NDPRF_PROCESSED_SERVICE ||
1628 		    pr->ndpr_stateflags & NDPRF_DEFUNCT) {
1629 			pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1630 			NDPR_UNLOCK(pr);
1631 			pr = pr->ndpr_next;
1632 			continue;
1633 		}
1634 
1635 		/*
1636 		 * If there are still manual addresses configured  in the system
1637 		 * that are associated with the prefix, ignore prefix expiry
1638 		 */
1639 		if (pr->ndpr_manual_addrcnt != 0) {
1640 			pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1641 			NDPR_UNLOCK(pr);
1642 			pr = pr->ndpr_next;
1643 			continue;
1644 		}
1645 
1646 		/*
1647 		 * check prefix lifetime.
1648 		 * since pltime is just for autoconf, pltime processing for
1649 		 * prefix is not necessary.
1650 		 */
1651 		if (pr->ndpr_expire != 0 && pr->ndpr_expire < timenow) {
1652 			/*
1653 			 * address expiration and prefix expiration are
1654 			 * separate. NEVER perform in6_purgeaddr here.
1655 			 */
1656 			pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1657 			NDPR_ADDREF(pr);
1658 			prelist_remove(pr);
1659 			NDPR_UNLOCK(pr);
1660 
1661 			in6_ifstat_inc(pr->ndpr_ifp, ifs6_pfx_expiry_cnt);
1662 			in6_event_enqueue_nwk_wq_entry(IN6_NDP_PFX_EXPIRY,
1663 			    pr->ndpr_ifp, &pr->ndpr_prefix.sin6_addr,
1664 			    0);
1665 			NDPR_REMREF(pr);
1666 			pfxlist_onlink_check();
1667 			pr = nd_prefix.lh_first;
1668 			ap->killed++;
1669 		} else {
1670 			if (pr->ndpr_expire == 0 ||
1671 			    (pr->ndpr_stateflags & NDPRF_STATIC)) {
1672 				ap->sticky++;
1673 			} else {
1674 				ap->aging_lazy++;
1675 			}
1676 			pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1677 			NDPR_UNLOCK(pr);
1678 			pr = pr->ndpr_next;
1679 		}
1680 	}
1681 	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
1682 		NDPR_LOCK(pr);
1683 		pr->ndpr_stateflags &= ~NDPRF_PROCESSED_SERVICE;
1684 		NDPR_UNLOCK(pr);
1685 	}
1686 	lck_mtx_unlock(nd6_mutex);
1687 }
1688 
1689 
1690 /*
1691  * ND6 service routine to expire default route list and prefix list
1692  */
1693 static void
nd6_service(void * arg)1694 nd6_service(void *arg)
1695 {
1696 	struct nd6svc_arg *ap = arg;
1697 	uint64_t timenow;
1698 
1699 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1700 	/*
1701 	 * Since we may drop rnh_lock and nd6_mutex below, we want
1702 	 * to run this entire operation single threaded.
1703 	 */
1704 	while (nd6_service_busy) {
1705 		nd6log2(debug, "%s: %s is blocked by %d waiters\n",
1706 		    __func__, ap->draining ? "drainer" : "timer",
1707 		    nd6_service_waiters);
1708 		nd6_service_waiters++;
1709 		(void) msleep(nd6_service_wc, rnh_lock, (PZERO - 1),
1710 		    __func__, NULL);
1711 		LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1712 	}
1713 
1714 	/* We are busy now; tell everyone else to go away */
1715 	nd6_service_busy = TRUE;
1716 	net_update_uptime();
1717 	timenow = net_uptime();
1718 
1719 	/* Iterate and service neighbor cache entries */
1720 	nd6_service_neighbor_cache(ap, timenow);
1721 
1722 	/*
1723 	 * There is lock ordering requirement and rnh_lock
1724 	 * has to be released before acquiring nd6_mutex.
1725 	 */
1726 	lck_mtx_unlock(rnh_lock);
1727 
1728 	/* Iterate and service expired default router */
1729 	nd6_service_expired_default_router(ap, timenow);
1730 	/* Iterate and service expired route information entries */
1731 	nd6_service_expired_route_info(ap, timenow);
1732 
1733 	/* Iterate and service expired/duplicated IPv6 address */
1734 	nd6_service_ip6_addr(ap, timenow);
1735 
1736 	/* Iterate and service expired IPv6 prefixes */
1737 	nd6_service_expired_prefix(ap, timenow);
1738 
1739 	lck_mtx_lock(rnh_lock);
1740 	/* We're done; let others enter */
1741 	nd6_service_busy = FALSE;
1742 	if (nd6_service_waiters > 0) {
1743 		nd6_service_waiters = 0;
1744 		wakeup(nd6_service_wc);
1745 	}
1746 }
1747 
1748 static int nd6_need_draining = 0;
1749 
1750 void
nd6_drain(void * arg)1751 nd6_drain(void *arg)
1752 {
1753 #pragma unused(arg)
1754 	nd6log2(debug, "%s: draining ND6 entries\n", __func__);
1755 
1756 	lck_mtx_lock(rnh_lock);
1757 	nd6_need_draining = 1;
1758 	nd6_sched_timeout(NULL, NULL);
1759 	lck_mtx_unlock(rnh_lock);
1760 }
1761 
1762 /*
1763  * We use the ``arg'' variable to decide whether or not the timer we're
1764  * running is the fast timer. We do this to reset the nd6_fast_timer_on
1765  * variable so that later we don't end up ignoring a ``fast timer''
1766  * request if the 5 second timer is running (see nd6_sched_timeout).
1767  */
1768 static void
nd6_timeout(void * arg)1769 nd6_timeout(void *arg)
1770 {
1771 	struct nd6svc_arg sarg;
1772 	uint32_t buf;
1773 
1774 	lck_mtx_lock(rnh_lock);
1775 	bzero(&sarg, sizeof(sarg));
1776 	if (nd6_need_draining != 0) {
1777 		nd6_need_draining = 0;
1778 		sarg.draining = 1;
1779 	}
1780 	nd6_service(&sarg);
1781 	nd6log2(debug, "%s: found %u, aging_lazy %u, aging %u, "
1782 	    "sticky %u, killed %u\n", __func__, sarg.found, sarg.aging_lazy,
1783 	    sarg.aging, sarg.sticky, sarg.killed);
1784 	/* re-arm the timer if there's work to do */
1785 	nd6_timeout_run--;
1786 	VERIFY(nd6_timeout_run >= 0 && nd6_timeout_run < 2);
1787 	if (arg == &nd6_fast_timer_on) {
1788 		nd6_fast_timer_on = FALSE;
1789 	}
1790 	if (sarg.aging_lazy > 0 || sarg.aging > 0 || nd6_sched_timeout_want) {
1791 		struct timeval atv, ltv, *leeway;
1792 		int lazy = nd6_prune_lazy;
1793 
1794 		if (sarg.aging > 0 || lazy < 1) {
1795 			atv.tv_usec = 0;
1796 			atv.tv_sec = nd6_prune;
1797 			leeway = NULL;
1798 		} else {
1799 			VERIFY(lazy >= 1);
1800 			atv.tv_usec = 0;
1801 			atv.tv_sec = MAX(nd6_prune, lazy);
1802 			ltv.tv_usec = 0;
1803 			read_frandom(&buf, sizeof(buf));
1804 			ltv.tv_sec = MAX(buf % lazy, 1) * 2;
1805 			leeway = &ltv;
1806 		}
1807 		nd6_sched_timeout(&atv, leeway);
1808 	} else if (nd6_debug) {
1809 		nd6log2(debug, "%s: not rescheduling timer\n", __func__);
1810 	}
1811 	lck_mtx_unlock(rnh_lock);
1812 }
1813 
1814 void
nd6_sched_timeout(struct timeval * atv,struct timeval * ltv)1815 nd6_sched_timeout(struct timeval *atv, struct timeval *ltv)
1816 {
1817 	struct timeval tv;
1818 
1819 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1820 	if (atv == NULL) {
1821 		tv.tv_usec = 0;
1822 		tv.tv_sec = MAX(nd6_prune, 1);
1823 		atv = &tv;
1824 		ltv = NULL;     /* ignore leeway */
1825 	}
1826 	/* see comments on top of this file */
1827 	if (nd6_timeout_run == 0) {
1828 		if (ltv == NULL) {
1829 			nd6log2(debug, "%s: timer scheduled in "
1830 			    "T+%llus.%lluu (demand %d)\n", __func__,
1831 			    (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1832 			    nd6_sched_timeout_want);
1833 			nd6_fast_timer_on = TRUE;
1834 			timeout(nd6_timeout, &nd6_fast_timer_on, tvtohz(atv));
1835 		} else {
1836 			nd6log2(debug, "%s: timer scheduled in "
1837 			    "T+%llus.%lluu with %llus.%lluu leeway "
1838 			    "(demand %d)\n", __func__, (uint64_t)atv->tv_sec,
1839 			    (uint64_t)atv->tv_usec, (uint64_t)ltv->tv_sec,
1840 			    (uint64_t)ltv->tv_usec, nd6_sched_timeout_want);
1841 			nd6_fast_timer_on = FALSE;
1842 			timeout_with_leeway(nd6_timeout, NULL,
1843 			    tvtohz(atv), tvtohz(ltv));
1844 		}
1845 		nd6_timeout_run++;
1846 		nd6_sched_timeout_want = 0;
1847 	} else if (nd6_timeout_run == 1 && ltv == NULL &&
1848 	    nd6_fast_timer_on == FALSE) {
1849 		nd6log2(debug, "%s: fast timer scheduled in "
1850 		    "T+%llus.%lluu (demand %d)\n", __func__,
1851 		    (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1852 		    nd6_sched_timeout_want);
1853 		nd6_fast_timer_on = TRUE;
1854 		nd6_sched_timeout_want = 0;
1855 		nd6_timeout_run++;
1856 		timeout(nd6_timeout, &nd6_fast_timer_on, tvtohz(atv));
1857 	} else {
1858 		if (ltv == NULL) {
1859 			nd6log2(debug, "%s: not scheduling timer: "
1860 			    "timers %d, fast_timer %d, T+%llus.%lluu\n",
1861 			    __func__, nd6_timeout_run, nd6_fast_timer_on,
1862 			    (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec);
1863 		} else {
1864 			nd6log2(debug, "%s: not scheduling timer: "
1865 			    "timers %d, fast_timer %d, T+%llus.%lluu "
1866 			    "with %llus.%lluu leeway\n", __func__,
1867 			    nd6_timeout_run, nd6_fast_timer_on,
1868 			    (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1869 			    (uint64_t)ltv->tv_sec, (uint64_t)ltv->tv_usec);
1870 		}
1871 	}
1872 }
1873 
1874 /*
1875  * ND6 router advertisement kernel notification
1876  */
1877 void
nd6_post_msg(u_int32_t code,struct nd_prefix_list * prefix_list,u_int32_t list_length,u_int32_t mtu)1878 nd6_post_msg(u_int32_t code, struct nd_prefix_list *prefix_list,
1879     u_int32_t list_length, u_int32_t mtu)
1880 {
1881 	struct kev_msg ev_msg;
1882 	struct kev_nd6_ra_data nd6_ra_msg_data;
1883 	struct nd_prefix_list *itr = prefix_list;
1884 
1885 	bzero(&ev_msg, sizeof(struct kev_msg));
1886 	ev_msg.vendor_code      = KEV_VENDOR_APPLE;
1887 	ev_msg.kev_class        = KEV_NETWORK_CLASS;
1888 	ev_msg.kev_subclass     = KEV_ND6_SUBCLASS;
1889 	ev_msg.event_code       = code;
1890 
1891 	bzero(&nd6_ra_msg_data, sizeof(nd6_ra_msg_data));
1892 
1893 	if (mtu > 0 && mtu >= IPV6_MMTU) {
1894 		nd6_ra_msg_data.mtu = mtu;
1895 		nd6_ra_msg_data.flags |= KEV_ND6_DATA_VALID_MTU;
1896 	}
1897 
1898 	if (list_length > 0 && prefix_list != NULL) {
1899 		nd6_ra_msg_data.list_length = list_length;
1900 		nd6_ra_msg_data.flags |= KEV_ND6_DATA_VALID_PREFIX;
1901 	}
1902 
1903 	while (itr != NULL && nd6_ra_msg_data.list_index < list_length) {
1904 		bcopy(&itr->pr.ndpr_prefix, &nd6_ra_msg_data.prefix.prefix,
1905 		    sizeof(nd6_ra_msg_data.prefix.prefix));
1906 		nd6_ra_msg_data.prefix.raflags = itr->pr.ndpr_raf;
1907 		nd6_ra_msg_data.prefix.prefixlen = itr->pr.ndpr_plen;
1908 		nd6_ra_msg_data.prefix.origin = PR_ORIG_RA;
1909 		nd6_ra_msg_data.prefix.vltime = itr->pr.ndpr_vltime;
1910 		nd6_ra_msg_data.prefix.pltime = itr->pr.ndpr_pltime;
1911 		nd6_ra_msg_data.prefix.expire = ndpr_getexpire(&itr->pr);
1912 		nd6_ra_msg_data.prefix.flags = itr->pr.ndpr_stateflags;
1913 		nd6_ra_msg_data.prefix.refcnt = itr->pr.ndpr_addrcnt;
1914 		nd6_ra_msg_data.prefix.if_index = itr->pr.ndpr_ifp->if_index;
1915 
1916 		/* send the message up */
1917 		ev_msg.dv[0].data_ptr           = &nd6_ra_msg_data;
1918 		ev_msg.dv[0].data_length        = sizeof(nd6_ra_msg_data);
1919 		ev_msg.dv[1].data_length        = 0;
1920 		dlil_post_complete_msg(NULL, &ev_msg);
1921 
1922 		/* clean up for the next prefix */
1923 		bzero(&nd6_ra_msg_data.prefix, sizeof(nd6_ra_msg_data.prefix));
1924 		itr = itr->next;
1925 		nd6_ra_msg_data.list_index++;
1926 	}
1927 }
1928 
1929 /*
1930  * Regenerate deprecated/invalidated temporary address
1931  */
1932 static int
regen_tmpaddr(struct in6_ifaddr * ia6)1933 regen_tmpaddr(struct in6_ifaddr *ia6)
1934 {
1935 	struct ifaddr *ifa;
1936 	struct ifnet *ifp;
1937 	struct in6_ifaddr *public_ifa6 = NULL;
1938 	uint64_t timenow = net_uptime();
1939 
1940 	ifp = ia6->ia_ifa.ifa_ifp;
1941 	ifnet_lock_shared(ifp);
1942 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1943 		struct in6_ifaddr *it6;
1944 
1945 		IFA_LOCK(ifa);
1946 		if (ifa->ifa_addr->sa_family != AF_INET6) {
1947 			IFA_UNLOCK(ifa);
1948 			continue;
1949 		}
1950 		it6 = (struct in6_ifaddr *)ifa;
1951 
1952 		/* ignore no autoconf addresses. */
1953 		if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0) {
1954 			IFA_UNLOCK(ifa);
1955 			continue;
1956 		}
1957 		/* ignore autoconf addresses with different prefixes. */
1958 		if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr) {
1959 			IFA_UNLOCK(ifa);
1960 			continue;
1961 		}
1962 		/*
1963 		 * Now we are looking at an autoconf address with the same
1964 		 * prefix as ours.  If the address is temporary and is still
1965 		 * preferred, do not create another one.  It would be rare, but
1966 		 * could happen, for example, when we resume a laptop PC after
1967 		 * a long period.
1968 		 */
1969 		if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1970 		    !IFA6_IS_DEPRECATED(it6, timenow)) {
1971 			IFA_UNLOCK(ifa);
1972 			if (public_ifa6 != NULL) {
1973 				IFA_REMREF(&public_ifa6->ia_ifa);
1974 			}
1975 			public_ifa6 = NULL;
1976 			break;
1977 		}
1978 
1979 		/*
1980 		 * This is a public autoconf address that has the same prefix
1981 		 * as ours.  If it is preferred, keep it.  We can't break the
1982 		 * loop here, because there may be a still-preferred temporary
1983 		 * address with the prefix.
1984 		 */
1985 		if (!IFA6_IS_DEPRECATED(it6, timenow)) {
1986 			IFA_ADDREF_LOCKED(ifa); /* for public_ifa6 */
1987 			IFA_UNLOCK(ifa);
1988 			if (public_ifa6 != NULL) {
1989 				IFA_REMREF(&public_ifa6->ia_ifa);
1990 			}
1991 			public_ifa6 = it6;
1992 		} else {
1993 			IFA_UNLOCK(ifa);
1994 		}
1995 	}
1996 	ifnet_lock_done(ifp);
1997 
1998 	if (public_ifa6 != NULL) {
1999 		int e;
2000 
2001 		if ((e = in6_tmpifadd(public_ifa6, 0)) != 0) {
2002 			log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
2003 			    " tmp addr,errno=%d\n", e);
2004 			IFA_REMREF(&public_ifa6->ia_ifa);
2005 			return -1;
2006 		}
2007 		IFA_REMREF(&public_ifa6->ia_ifa);
2008 		return 0;
2009 	}
2010 
2011 	return -1;
2012 }
2013 
2014 static void
nd6_purge_interface_default_routers(struct ifnet * ifp)2015 nd6_purge_interface_default_routers(struct ifnet *ifp)
2016 {
2017 	struct nd_defrouter *dr = NULL;
2018 	struct nd_defrouter *ndr = NULL;
2019 	struct nd_drhead nd_defrouter_tmp = {};
2020 
2021 	TAILQ_INIT(&nd_defrouter_tmp);
2022 
2023 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2024 
2025 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter_list, dr_entry, ndr) {
2026 		if (dr->ifp != ifp) {
2027 			continue;
2028 		}
2029 		/*
2030 		 * Remove the entry from default router list
2031 		 * and add it to the temp list.
2032 		 * nd_defrouter_tmp will be a local temporary
2033 		 * list as no one else can get the same
2034 		 * removed entry once it is removed from default
2035 		 * router list.
2036 		 * Remove the reference after calling defrtrlist_del.
2037 		 *
2038 		 * The uninstalled entries have to be iterated first
2039 		 * when we call defrtrlist_del.
2040 		 * This is to ensure that we don't end up calling
2041 		 * default router  selection when there are other
2042 		 * uninstalled candidate default routers on
2043 		 * the interface.
2044 		 * If we don't respect that order, we may end
2045 		 * up missing out on some entries.
2046 		 *
2047 		 * For that reason, installed ones must be inserted
2048 		 * at the tail and uninstalled ones at the head
2049 		 */
2050 		TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
2051 
2052 		if (dr->stateflags & NDDRF_INSTALLED) {
2053 			TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
2054 		} else {
2055 			TAILQ_INSERT_HEAD(&nd_defrouter_tmp, dr, dr_entry);
2056 		}
2057 	}
2058 
2059 	/*
2060 	 * The following call to defrtrlist_del should be
2061 	 * safe as we are iterating a local list of
2062 	 * default routers.
2063 	 *
2064 	 * We don't really need nd6_mutex here but keeping
2065 	 * it as it is to avoid changing assertios held in
2066 	 * the functions in the call-path.
2067 	 */
2068 	TAILQ_FOREACH_SAFE(dr, &nd_defrouter_tmp, dr_entry, ndr) {
2069 		TAILQ_REMOVE(&nd_defrouter_tmp, dr, dr_entry);
2070 		defrtrlist_del(dr, NULL);
2071 		NDDR_REMREF(dr);        /* remove list reference */
2072 	}
2073 }
2074 
2075 static void
nd6_purge_interface_prefixes(struct ifnet * ifp)2076 nd6_purge_interface_prefixes(struct ifnet *ifp)
2077 {
2078 	boolean_t removed = FALSE;
2079 	struct nd_prefix *pr = NULL;
2080 	struct nd_prefix *npr = NULL;
2081 
2082 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2083 
2084 	/* Nuke prefix list entries toward ifp */
2085 	for (pr = nd_prefix.lh_first; pr; pr = npr) {
2086 		NDPR_LOCK(pr);
2087 		npr = pr->ndpr_next;
2088 		if (pr->ndpr_ifp == ifp &&
2089 		    !(pr->ndpr_stateflags & NDPRF_DEFUNCT)) {
2090 			/*
2091 			 * Because if_detach() does *not* release prefixes
2092 			 * while purging addresses the reference count will
2093 			 * still be above zero. We therefore reset it to
2094 			 * make sure that the prefix really gets purged.
2095 			 */
2096 			pr->ndpr_addrcnt = 0;
2097 
2098 			/*
2099 			 * Previously, pr->ndpr_addr is removed as well,
2100 			 * but I strongly believe we don't have to do it.
2101 			 * nd6_purge() is only called from in6_ifdetach(),
2102 			 * which removes all the associated interface addresses
2103 			 * by itself.
2104 			 * ([email protected] 20010129)
2105 			 */
2106 			NDPR_ADDREF(pr);
2107 			prelist_remove(pr);
2108 			NDPR_UNLOCK(pr);
2109 			NDPR_REMREF(pr);
2110 			removed = TRUE;
2111 			npr = nd_prefix.lh_first;
2112 		} else {
2113 			NDPR_UNLOCK(pr);
2114 		}
2115 	}
2116 	if (removed) {
2117 		pfxlist_onlink_check();
2118 	}
2119 }
2120 
2121 static void
nd6_router_select_rti_entries(struct ifnet * ifp)2122 nd6_router_select_rti_entries(struct ifnet *ifp)
2123 {
2124 	struct nd_route_info *rti = NULL;
2125 	struct nd_route_info *rti_next = NULL;
2126 
2127 	nd6_rti_list_wait(__func__);
2128 
2129 	TAILQ_FOREACH_SAFE(rti, &nd_rti_list, nd_rti_entry, rti_next) {
2130 		defrouter_select(ifp, &rti->nd_rti_router_list);
2131 	}
2132 
2133 	nd6_rti_list_signal_done();
2134 }
2135 
2136 static void
nd6_purge_interface_rti_entries(struct ifnet * ifp)2137 nd6_purge_interface_rti_entries(struct ifnet *ifp)
2138 {
2139 	struct nd_route_info *rti = NULL;
2140 	struct nd_route_info *rti_next = NULL;
2141 
2142 	nd6_rti_list_wait(__func__);
2143 
2144 	TAILQ_FOREACH_SAFE(rti, &nd_rti_list, nd_rti_entry, rti_next) {
2145 		struct nd_route_info rti_tmp = {};
2146 		struct nd_defrouter *dr = NULL;
2147 		struct nd_defrouter *ndr = NULL;
2148 
2149 		rti_tmp.nd_rti_prefix = rti->nd_rti_prefix;
2150 		rti_tmp.nd_rti_prefixlen = rti->nd_rti_prefixlen;
2151 		TAILQ_INIT(&rti_tmp.nd_rti_router_list);
2152 
2153 		TAILQ_FOREACH_SAFE(dr, &rti->nd_rti_router_list, dr_entry, ndr) {
2154 			/*
2155 			 * If ifp is provided, skip the entries that don't match.
2156 			 * Else it is treated as a purge.
2157 			 */
2158 			if (ifp != NULL && dr->ifp != ifp) {
2159 				continue;
2160 			}
2161 
2162 			/*
2163 			 * Remove the entry from rti's router list
2164 			 * and add it to the temp list.
2165 			 * Remove the reference after calling defrtrlist_del.
2166 			 *
2167 			 * The uninstalled entries have to be iterated first
2168 			 * when we call defrtrlist_del.
2169 			 * This is to ensure that we don't end up calling
2170 			 * router  selection when there are other
2171 			 * uninstalled candidate default routers on
2172 			 * the interface.
2173 			 * If we don't respect that order, we may end
2174 			 * up missing out on some entries.
2175 			 *
2176 			 * For that reason, installed ones must be inserted
2177 			 * at the tail and uninstalled ones at the head
2178 			 */
2179 
2180 			TAILQ_REMOVE(&rti->nd_rti_router_list, dr, dr_entry);
2181 			if (dr->stateflags & NDDRF_INSTALLED) {
2182 				TAILQ_INSERT_TAIL(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2183 			} else {
2184 				TAILQ_INSERT_HEAD(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2185 			}
2186 		}
2187 
2188 		/*
2189 		 * The following call to defrtrlist_del should be
2190 		 * safe as we are iterating a local list of
2191 		 * routers.
2192 		 *
2193 		 * We don't really need nd6_mutex here but keeping
2194 		 * it as it is to avoid changing assertios held in
2195 		 * the functions in the call-path.
2196 		 */
2197 		TAILQ_FOREACH_SAFE(dr, &rti_tmp.nd_rti_router_list, dr_entry, ndr) {
2198 			TAILQ_REMOVE(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2199 			defrtrlist_del(dr, &rti->nd_rti_router_list);
2200 			NDDR_REMREF(dr);        /* remove list reference */
2201 		}
2202 		/*
2203 		 * The above may have removed an entry from default router list.
2204 		 * If it did and the list is now empty, remove the rti as well.
2205 		 */
2206 		if (TAILQ_EMPTY(&rti->nd_rti_router_list)) {
2207 			TAILQ_REMOVE(&nd_rti_list, rti, nd_rti_entry);
2208 			ndrti_free(rti);
2209 		}
2210 	}
2211 
2212 	nd6_rti_list_signal_done();
2213 }
2214 
2215 static void
nd6_purge_interface_llinfo(struct ifnet * ifp)2216 nd6_purge_interface_llinfo(struct ifnet *ifp)
2217 {
2218 	struct llinfo_nd6 *ln = NULL;
2219 	/* Note that rt->rt_ifp may not be the same as ifp,
2220 	 * due to KAME goto ours hack.  See RTM_RESOLVE case in
2221 	 * nd6_rtrequest(), and ip6_input().
2222 	 */
2223 again:
2224 	lck_mtx_lock(rnh_lock);
2225 	ln = llinfo_nd6.ln_next;
2226 	while (ln != NULL && ln != &llinfo_nd6) {
2227 		struct rtentry *rt;
2228 		struct llinfo_nd6 *nln;
2229 
2230 		nln = ln->ln_next;
2231 		rt = ln->ln_rt;
2232 		RT_LOCK(rt);
2233 		if (rt->rt_gateway != NULL &&
2234 		    rt->rt_gateway->sa_family == AF_LINK &&
2235 		    SDL(rt->rt_gateway)->sdl_index == ifp->if_index) {
2236 			RT_ADDREF_LOCKED(rt);
2237 			RT_UNLOCK(rt);
2238 			lck_mtx_unlock(rnh_lock);
2239 			/*
2240 			 * See comments on nd6_service() for reasons why
2241 			 * this loop is repeated; we bite the costs of
2242 			 * going thru the same llinfo_nd6 more than once
2243 			 * here, since this purge happens during detach,
2244 			 * and that unlike the timer case, it's possible
2245 			 * there's more than one purges happening at the
2246 			 * same time (thus a flag wouldn't buy anything).
2247 			 */
2248 			nd6_free(rt);
2249 			RT_REMREF(rt);
2250 			LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2251 			goto again;
2252 		} else {
2253 			RT_UNLOCK(rt);
2254 		}
2255 		ln = nln;
2256 	}
2257 	lck_mtx_unlock(rnh_lock);
2258 }
2259 
2260 /*
2261  * Nuke neighbor cache/prefix/default router management table, right before
2262  * ifp goes away.
2263  */
2264 void
nd6_purge(struct ifnet * ifp)2265 nd6_purge(struct ifnet *ifp)
2266 {
2267 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2268 	lck_mtx_lock(nd6_mutex);
2269 
2270 	/* Nuke default router list entries toward ifp */
2271 	nd6_purge_interface_default_routers(ifp);
2272 
2273 	/* Nuke prefix list entries toward ifp */
2274 	nd6_purge_interface_prefixes(ifp);
2275 
2276 	/* Nuke route info option entries toward ifp */
2277 	nd6_purge_interface_rti_entries(ifp);
2278 
2279 	lck_mtx_unlock(nd6_mutex);
2280 
2281 	/* cancel default outgoing interface setting */
2282 	if (nd6_defifindex == ifp->if_index) {
2283 		nd6_setdefaultiface(0);
2284 	}
2285 
2286 	/*
2287 	 * Perform default router selection even when we are a router,
2288 	 * if Scoped Routing is enabled.
2289 	 * XXX ?Should really not be needed since when defrouter_select
2290 	 * was changed to work on interface.
2291 	 */
2292 	lck_mtx_lock(nd6_mutex);
2293 	/* refresh default router list */
2294 	defrouter_select(ifp, NULL);
2295 	lck_mtx_unlock(nd6_mutex);
2296 
2297 	/* Nuke neighbor cache entries for the ifp. */
2298 	nd6_purge_interface_llinfo(ifp);
2299 }
2300 
2301 /*
2302  * Upon success, the returned route will be locked and the caller is
2303  * responsible for releasing the reference and doing RT_UNLOCK(rt).
2304  * This routine does not require rnh_lock to be held by the caller,
2305  * although it needs to be indicated of such a case in order to call
2306  * the correct variant of the relevant routing routines.
2307  */
2308 struct rtentry *
nd6_lookup(struct in6_addr * addr6,int create,struct ifnet * ifp,int rt_locked)2309 nd6_lookup(struct in6_addr *addr6, int create, struct ifnet *ifp, int rt_locked)
2310 {
2311 	struct rtentry *rt;
2312 	struct sockaddr_in6 sin6;
2313 	unsigned int ifscope;
2314 
2315 	bzero(&sin6, sizeof(sin6));
2316 	sin6.sin6_len = sizeof(struct sockaddr_in6);
2317 	sin6.sin6_family = AF_INET6;
2318 	sin6.sin6_addr = *addr6;
2319 
2320 	ifscope = (ifp != NULL) ? ifp->if_index : IFSCOPE_NONE;
2321 	if (rt_locked) {
2322 		LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2323 		rt = rtalloc1_scoped_locked(SA(&sin6), create, 0, ifscope);
2324 	} else {
2325 		rt = rtalloc1_scoped(SA(&sin6), create, 0, ifscope);
2326 	}
2327 
2328 	if (rt != NULL) {
2329 		RT_LOCK(rt);
2330 		if ((rt->rt_flags & RTF_LLINFO) == 0) {
2331 			/*
2332 			 * This is the case for the default route.
2333 			 * If we want to create a neighbor cache for the
2334 			 * address, we should free the route for the
2335 			 * destination and allocate an interface route.
2336 			 */
2337 			if (create) {
2338 				RT_UNLOCK(rt);
2339 				if (rt_locked) {
2340 					rtfree_locked(rt);
2341 				} else {
2342 					rtfree(rt);
2343 				}
2344 				rt = NULL;
2345 			}
2346 		}
2347 	}
2348 	if (rt == NULL) {
2349 		if (create && ifp) {
2350 			struct ifaddr *ifa;
2351 			u_int32_t ifa_flags;
2352 			int e;
2353 
2354 			/*
2355 			 * If no route is available and create is set,
2356 			 * we allocate a host route for the destination
2357 			 * and treat it like an interface route.
2358 			 * This hack is necessary for a neighbor which can't
2359 			 * be covered by our own prefix.
2360 			 */
2361 			ifa = ifaof_ifpforaddr(SA(&sin6), ifp);
2362 			if (ifa == NULL) {
2363 				return NULL;
2364 			}
2365 
2366 			/*
2367 			 * Create a new route.  RTF_LLINFO is necessary
2368 			 * to create a Neighbor Cache entry for the
2369 			 * destination in nd6_rtrequest which will be
2370 			 * called in rtrequest via ifa->ifa_rtrequest.
2371 			 */
2372 			if (!rt_locked) {
2373 				lck_mtx_lock(rnh_lock);
2374 			}
2375 			IFA_LOCK_SPIN(ifa);
2376 			ifa_flags = ifa->ifa_flags;
2377 			IFA_UNLOCK(ifa);
2378 			if ((e = rtrequest_scoped_locked(RTM_ADD,
2379 			    SA(&sin6), ifa->ifa_addr, SA(&all1_sa),
2380 			    (ifa_flags | RTF_HOST | RTF_LLINFO) &
2381 			    ~RTF_CLONING, &rt, ifscope)) != 0) {
2382 				if (e != EEXIST) {
2383 					log(LOG_ERR, "%s: failed to add route "
2384 					    "for a neighbor(%s), errno=%d\n",
2385 					    __func__, ip6_sprintf(addr6), e);
2386 				}
2387 			}
2388 			if (!rt_locked) {
2389 				lck_mtx_unlock(rnh_lock);
2390 			}
2391 			IFA_REMREF(ifa);
2392 			if (rt == NULL) {
2393 				return NULL;
2394 			}
2395 
2396 			RT_LOCK(rt);
2397 			if (rt->rt_llinfo) {
2398 				struct llinfo_nd6 *ln = rt->rt_llinfo;
2399 				boolean_t nud_enabled = FALSE;
2400 
2401 				/*
2402 				 * The IPv6 initialization of the loopback interface
2403 				 * may happen after another interface gets assigned
2404 				 * an IPv6 address.
2405 				 * To avoid asserting treat local routes as special
2406 				 * case.
2407 				 */
2408 				if (rt->rt_ifp != lo_ifp) {
2409 					struct nd_ifinfo *ndi = ND_IFINFO(rt->rt_ifp);
2410 					VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2411 					nud_enabled = !!(ndi->flags & ND6_IFF_PERFORMNUD);
2412 				}
2413 
2414 				/*
2415 				 * For interface's that do not perform NUD
2416 				 * neighbor cache entres must always be marked
2417 				 * reachable with no expiry
2418 				 */
2419 				if (nud_enabled) {
2420 					ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_NOSTATE);
2421 				} else {
2422 					ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2423 					ln_setexpire(ln, 0);
2424 				}
2425 			}
2426 		} else {
2427 			return NULL;
2428 		}
2429 	}
2430 	RT_LOCK_ASSERT_HELD(rt);
2431 	/*
2432 	 * Validation for the entry.
2433 	 * Note that the check for rt_llinfo is necessary because a cloned
2434 	 * route from a parent route that has the L flag (e.g. the default
2435 	 * route to a p2p interface) may have the flag, too, while the
2436 	 * destination is not actually a neighbor.
2437 	 * XXX: we can't use rt->rt_ifp to check for the interface, since
2438 	 *	it might be the loopback interface if the entry is for our
2439 	 *	own address on a non-loopback interface. Instead, we should
2440 	 *	use rt->rt_ifa->ifa_ifp, which would specify the REAL
2441 	 *	interface.
2442 	 * Note also that ifa_ifp and ifp may differ when we connect two
2443 	 * interfaces to a same link, install a link prefix to an interface,
2444 	 * and try to install a neighbor cache on an interface that does not
2445 	 * have a route to the prefix.
2446 	 *
2447 	 * If the address is from a proxied prefix, the ifa_ifp and ifp might
2448 	 * not match, because nd6_na_input() could have modified the ifp
2449 	 * of the route to point to the interface where the NA arrived on,
2450 	 * hence the test for RTF_PROXY.
2451 	 */
2452 	if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
2453 	    rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
2454 	    (ifp && rt->rt_ifa->ifa_ifp != ifp &&
2455 	    !(rt->rt_flags & RTF_PROXY))) {
2456 		RT_REMREF_LOCKED(rt);
2457 		RT_UNLOCK(rt);
2458 		if (create) {
2459 			log(LOG_DEBUG, "%s: failed to lookup %s "
2460 			    "(if = %s)\n", __func__, ip6_sprintf(addr6),
2461 			    ifp ? if_name(ifp) : "unspec");
2462 			/* xxx more logs... kazu */
2463 		}
2464 		return NULL;
2465 	}
2466 	/*
2467 	 * Caller needs to release reference and call RT_UNLOCK(rt).
2468 	 */
2469 	return rt;
2470 }
2471 
2472 /*
2473  * Test whether a given IPv6 address is a neighbor or not, ignoring
2474  * the actual neighbor cache.  The neighbor cache is ignored in order
2475  * to not reenter the routing code from within itself.
2476  */
2477 static int
nd6_is_new_addr_neighbor(struct sockaddr_in6 * addr,struct ifnet * ifp)2478 nd6_is_new_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
2479 {
2480 	struct nd_prefix *pr;
2481 	struct ifaddr *dstaddr;
2482 
2483 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2484 
2485 	/*
2486 	 * A link-local address is always a neighbor.
2487 	 * XXX: a link does not necessarily specify a single interface.
2488 	 */
2489 	if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
2490 		struct sockaddr_in6 sin6_copy;
2491 		u_int32_t zone;
2492 
2493 		/*
2494 		 * We need sin6_copy since sa6_recoverscope() may modify the
2495 		 * content (XXX).
2496 		 */
2497 		sin6_copy = *addr;
2498 		if (sa6_recoverscope(&sin6_copy, FALSE)) {
2499 			return 0; /* XXX: should be impossible */
2500 		}
2501 		if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone)) {
2502 			return 0;
2503 		}
2504 		if (sin6_copy.sin6_scope_id == zone) {
2505 			return 1;
2506 		} else {
2507 			return 0;
2508 		}
2509 	}
2510 
2511 	/*
2512 	 * If the address matches one of our addresses,
2513 	 * it should be a neighbor.
2514 	 * If the address matches one of our on-link prefixes, it should be a
2515 	 * neighbor.
2516 	 */
2517 	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
2518 		NDPR_LOCK(pr);
2519 		if (pr->ndpr_ifp != ifp) {
2520 			NDPR_UNLOCK(pr);
2521 			continue;
2522 		}
2523 		if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
2524 			NDPR_UNLOCK(pr);
2525 			continue;
2526 		}
2527 		if (in6_are_masked_addr_scope_equal(&pr->ndpr_prefix.sin6_addr, pr->ndpr_prefix.sin6_scope_id,
2528 		    &addr->sin6_addr, addr->sin6_scope_id, &pr->ndpr_mask)) {
2529 			NDPR_UNLOCK(pr);
2530 			return 1;
2531 		}
2532 		NDPR_UNLOCK(pr);
2533 	}
2534 
2535 	/*
2536 	 * If the address is assigned on the node of the other side of
2537 	 * a p2p interface, the address should be a neighbor.
2538 	 */
2539 	dstaddr = ifa_ifwithdstaddr(SA(addr));
2540 	if (dstaddr != NULL) {
2541 		if (dstaddr->ifa_ifp == ifp) {
2542 			IFA_REMREF(dstaddr);
2543 			return 1;
2544 		}
2545 		IFA_REMREF(dstaddr);
2546 		dstaddr = NULL;
2547 	}
2548 
2549 	return 0;
2550 }
2551 
2552 
2553 /*
2554  * Detect if a given IPv6 address identifies a neighbor on a given link.
2555  * XXX: should take care of the destination of a p2p link?
2556  */
2557 int
nd6_is_addr_neighbor(struct sockaddr_in6 * addr,struct ifnet * ifp,int rt_locked)2558 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp,
2559     int rt_locked)
2560 {
2561 	struct rtentry *rt;
2562 
2563 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2564 	lck_mtx_lock(nd6_mutex);
2565 	if (nd6_is_new_addr_neighbor(addr, ifp)) {
2566 		lck_mtx_unlock(nd6_mutex);
2567 		return 1;
2568 	}
2569 	lck_mtx_unlock(nd6_mutex);
2570 
2571 	/*
2572 	 * Even if the address matches none of our addresses, it might be
2573 	 * in the neighbor cache.
2574 	 */
2575 	if ((rt = nd6_lookup(&addr->sin6_addr, 0, ifp, rt_locked)) != NULL) {
2576 		RT_LOCK_ASSERT_HELD(rt);
2577 		RT_REMREF_LOCKED(rt);
2578 		RT_UNLOCK(rt);
2579 		return 1;
2580 	}
2581 
2582 	return 0;
2583 }
2584 
2585 /*
2586  * Free an nd6 llinfo entry.
2587  * Since the function would cause significant changes in the kernel, DO NOT
2588  * make it global, unless you have a strong reason for the change, and are sure
2589  * that the change is safe.
2590  */
2591 void
nd6_free(struct rtentry * rt)2592 nd6_free(struct rtentry *rt)
2593 {
2594 	struct llinfo_nd6 *ln = NULL;
2595 	struct in6_addr in6 = {};
2596 	struct nd_defrouter *dr = NULL;
2597 
2598 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2599 	RT_LOCK_ASSERT_NOTHELD(rt);
2600 	lck_mtx_lock(nd6_mutex);
2601 
2602 	RT_LOCK(rt);
2603 	RT_ADDREF_LOCKED(rt);   /* Extra ref */
2604 	ln = rt->rt_llinfo;
2605 	in6 = SIN6(rt_key(rt))->sin6_addr;
2606 
2607 	/*
2608 	 * Prevent another thread from modifying rt_key, rt_gateway
2609 	 * via rt_setgate() after the rt_lock is dropped by marking
2610 	 * the route as defunct.
2611 	 */
2612 	rt->rt_flags |= RTF_CONDEMNED;
2613 
2614 	/*
2615 	 * We used to have pfctlinput(PRC_HOSTDEAD) here.  Even though it is
2616 	 * not harmful, it was not really necessary.  Perform default router
2617 	 * selection even when we are a router, if Scoped Routing is enabled.
2618 	 */
2619 	/* XXX TDB Handle lists in route information option as well */
2620 	dr = defrouter_lookup(NULL, &SIN6(rt_key(rt))->sin6_addr, rt->rt_ifp);
2621 
2622 	if ((ln && ln->ln_router) || dr) {
2623 		/*
2624 		 * rt6_flush must be called whether or not the neighbor
2625 		 * is in the Default Router List.
2626 		 * See a corresponding comment in nd6_na_input().
2627 		 */
2628 		RT_UNLOCK(rt);
2629 		lck_mtx_unlock(nd6_mutex);
2630 		rt6_flush(&in6, rt->rt_ifp);
2631 		lck_mtx_lock(nd6_mutex);
2632 	} else {
2633 		RT_UNLOCK(rt);
2634 	}
2635 
2636 	if (dr) {
2637 		NDDR_REMREF(dr);
2638 		/*
2639 		 * Unreachablity of a router might affect the default
2640 		 * router selection and on-link detection of advertised
2641 		 * prefixes.
2642 		 */
2643 
2644 		/*
2645 		 * Temporarily fake the state to choose a new default
2646 		 * router and to perform on-link determination of
2647 		 * prefixes correctly.
2648 		 * Below the state will be set correctly,
2649 		 * or the entry itself will be deleted.
2650 		 */
2651 		RT_LOCK_SPIN(rt);
2652 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_INCOMPLETE);
2653 
2654 		/*
2655 		 * Since defrouter_select() does not affect the
2656 		 * on-link determination and MIP6 needs the check
2657 		 * before the default router selection, we perform
2658 		 * the check now.
2659 		 */
2660 		RT_UNLOCK(rt);
2661 		pfxlist_onlink_check();
2662 
2663 		/*
2664 		 * refresh default router list
2665 		 */
2666 		defrouter_select(rt->rt_ifp, NULL);
2667 
2668 		/* Loop through all RTI's as well and trigger router selection. */
2669 		nd6_router_select_rti_entries(rt->rt_ifp);
2670 	}
2671 	RT_LOCK_ASSERT_NOTHELD(rt);
2672 	lck_mtx_unlock(nd6_mutex);
2673 	/*
2674 	 * Detach the route from the routing tree and the list of neighbor
2675 	 * caches, and disable the route entry not to be used in already
2676 	 * cached routes.
2677 	 */
2678 	(void) rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt), 0, NULL);
2679 
2680 	/* Extra ref held above; now free it */
2681 	rtfree(rt);
2682 }
2683 
2684 void
nd6_rtrequest(int req,struct rtentry * rt,struct sockaddr * sa)2685 nd6_rtrequest(int req, struct rtentry *rt, struct sockaddr *sa)
2686 {
2687 #pragma unused(sa)
2688 	struct sockaddr *gate = rt->rt_gateway;
2689 	struct llinfo_nd6 *ln = rt->rt_llinfo;
2690 	static struct sockaddr_dl null_sdl =
2691 	{ .sdl_len = sizeof(null_sdl), .sdl_family = AF_LINK };
2692 	struct ifnet *ifp = rt->rt_ifp;
2693 	struct ifaddr *ifa;
2694 	uint64_t timenow;
2695 	char buf[MAX_IPv6_STR_LEN];
2696 	boolean_t nud_enabled = FALSE;
2697 
2698 	/*
2699 	 * The IPv6 initialization of the loopback interface
2700 	 * may happen after another interface gets assigned
2701 	 * an IPv6 address.
2702 	 * To avoid asserting treat local routes as special
2703 	 * case.
2704 	 */
2705 	if (rt->rt_ifp != lo_ifp) {
2706 		struct nd_ifinfo *ndi = ND_IFINFO(rt->rt_ifp);
2707 		VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2708 		nud_enabled = !!(ndi->flags & ND6_IFF_PERFORMNUD);
2709 	}
2710 
2711 	VERIFY(nd6_init_done);
2712 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2713 	RT_LOCK_ASSERT_HELD(rt);
2714 
2715 	/*
2716 	 * We have rnh_lock held, see if we need to schedule the timer;
2717 	 * we might do this again below during RTM_RESOLVE, but doing it
2718 	 * now handles all other cases.
2719 	 */
2720 	if (nd6_sched_timeout_want) {
2721 		nd6_sched_timeout(NULL, NULL);
2722 	}
2723 
2724 	if (rt->rt_flags & RTF_GATEWAY) {
2725 		return;
2726 	}
2727 
2728 	if (!nd6_need_cache(ifp) && !(rt->rt_flags & RTF_HOST)) {
2729 		/*
2730 		 * This is probably an interface direct route for a link
2731 		 * which does not need neighbor caches (e.g. fe80::%lo0/64).
2732 		 * We do not need special treatment below for such a route.
2733 		 * Moreover, the RTF_LLINFO flag which would be set below
2734 		 * would annoy the ndp(8) command.
2735 		 */
2736 		return;
2737 	}
2738 
2739 	if (req == RTM_RESOLVE) {
2740 		int no_nd_cache;
2741 
2742 		if (!nd6_need_cache(ifp)) {     /* stf case */
2743 			no_nd_cache = 1;
2744 		} else {
2745 			struct sockaddr_in6 sin6;
2746 
2747 			rtkey_to_sa6(rt, &sin6);
2748 			/*
2749 			 * nd6_is_addr_neighbor() may call nd6_lookup(),
2750 			 * therefore we drop rt_lock to avoid deadlock
2751 			 * during the lookup.
2752 			 */
2753 			RT_ADDREF_LOCKED(rt);
2754 			RT_UNLOCK(rt);
2755 			no_nd_cache = !nd6_is_addr_neighbor(&sin6, ifp, 1);
2756 			RT_LOCK(rt);
2757 			RT_REMREF_LOCKED(rt);
2758 		}
2759 
2760 		/*
2761 		 * FreeBSD and BSD/OS often make a cloned host route based
2762 		 * on a less-specific route (e.g. the default route).
2763 		 * If the less specific route does not have a "gateway"
2764 		 * (this is the case when the route just goes to a p2p or an
2765 		 * stf interface), we'll mistakenly make a neighbor cache for
2766 		 * the host route, and will see strange neighbor solicitation
2767 		 * for the corresponding destination.  In order to avoid the
2768 		 * confusion, we check if the destination of the route is
2769 		 * a neighbor in terms of neighbor discovery, and stop the
2770 		 * process if not.  Additionally, we remove the LLINFO flag
2771 		 * so that ndp(8) will not try to get the neighbor information
2772 		 * of the destination.
2773 		 */
2774 		if (no_nd_cache) {
2775 			rt->rt_flags &= ~RTF_LLINFO;
2776 			return;
2777 		}
2778 	}
2779 
2780 	timenow = net_uptime();
2781 
2782 	switch (req) {
2783 	case RTM_ADD:
2784 		/*
2785 		 * There is no backward compatibility :)
2786 		 *
2787 		 * if ((rt->rt_flags & RTF_HOST) == 0 &&
2788 		 *      SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
2789 		 *              rt->rt_flags |= RTF_CLONING;
2790 		 */
2791 		if ((rt->rt_flags & RTF_CLONING) ||
2792 		    ((rt->rt_flags & RTF_LLINFO) && ln == NULL)) {
2793 			/*
2794 			 * Case 1: This route should come from a route to
2795 			 * interface (RTF_CLONING case) or the route should be
2796 			 * treated as on-link but is currently not
2797 			 * (RTF_LLINFO && ln == NULL case).
2798 			 */
2799 			if (rt_setgate(rt, rt_key(rt), SA(&null_sdl)) == 0) {
2800 				gate = rt->rt_gateway;
2801 				SDL(gate)->sdl_type = ifp->if_type;
2802 				SDL(gate)->sdl_index = ifp->if_index;
2803 				/*
2804 				 * In case we're called before 1.0 sec.
2805 				 * has elapsed.
2806 				 */
2807 				if (ln != NULL) {
2808 					ln_setexpire(ln,
2809 					    (ifp->if_eflags & IFEF_IPV6_ND6ALT)
2810 					    ? 0 : MAX(timenow, 1));
2811 				}
2812 			}
2813 			if (rt->rt_flags & RTF_CLONING) {
2814 				break;
2815 			}
2816 		}
2817 		/*
2818 		 * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
2819 		 * We don't do that here since llinfo is not ready yet.
2820 		 *
2821 		 * There are also couple of other things to be discussed:
2822 		 * - unsolicited NA code needs improvement beforehand
2823 		 * - RFC4861 says we MAY send multicast unsolicited NA
2824 		 *   (7.2.6 paragraph 4), however, it also says that we
2825 		 *   SHOULD provide a mechanism to prevent multicast NA storm.
2826 		 *   we don't have anything like it right now.
2827 		 *   note that the mechanism needs a mutual agreement
2828 		 *   between proxies, which means that we need to implement
2829 		 *   a new protocol, or a new kludge.
2830 		 * - from RFC4861 6.2.4, host MUST NOT send an unsolicited RA.
2831 		 *   we need to check ip6forwarding before sending it.
2832 		 *   (or should we allow proxy ND configuration only for
2833 		 *   routers?  there's no mention about proxy ND from hosts)
2834 		 */
2835 		OS_FALLTHROUGH;
2836 	case RTM_RESOLVE:
2837 		if (!(ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK))) {
2838 			/*
2839 			 * Address resolution isn't necessary for a point to
2840 			 * point link, so we can skip this test for a p2p link.
2841 			 */
2842 			if (gate->sa_family != AF_LINK ||
2843 			    gate->sa_len < sizeof(null_sdl)) {
2844 				/* Don't complain in case of RTM_ADD */
2845 				if (req == RTM_RESOLVE) {
2846 					log(LOG_ERR, "%s: route to %s has bad "
2847 					    "gateway address (sa_family %u "
2848 					    "sa_len %u) on %s\n", __func__,
2849 					    inet_ntop(AF_INET6,
2850 					    &SIN6(rt_key(rt))->sin6_addr, buf,
2851 					    sizeof(buf)), gate->sa_family,
2852 					    gate->sa_len, if_name(ifp));
2853 				}
2854 				break;
2855 			}
2856 			SDL(gate)->sdl_type = ifp->if_type;
2857 			SDL(gate)->sdl_index = ifp->if_index;
2858 		}
2859 		if (ln != NULL) {
2860 			break;  /* This happens on a route change */
2861 		}
2862 		/*
2863 		 * Case 2: This route may come from cloning, or a manual route
2864 		 * add with a LL address.
2865 		 */
2866 		rt->rt_llinfo = ln = nd6_llinfo_alloc(Z_WAITOK);
2867 
2868 		nd6_allocated++;
2869 		rt->rt_llinfo_get_ri    = nd6_llinfo_get_ri;
2870 		rt->rt_llinfo_get_iflri = nd6_llinfo_get_iflri;
2871 		rt->rt_llinfo_purge     = nd6_llinfo_purge;
2872 		rt->rt_llinfo_free      = nd6_llinfo_free;
2873 		rt->rt_llinfo_refresh   = nd6_llinfo_refresh;
2874 		rt->rt_flags |= RTF_LLINFO;
2875 		ln->ln_rt = rt;
2876 		/* this is required for "ndp" command. - shin */
2877 		/*
2878 		 * For interface's that do not perform NUD
2879 		 * neighbor cache entries must always be marked
2880 		 * reachable with no expiry
2881 		 */
2882 		if ((req == RTM_ADD) || !nud_enabled) {
2883 			/*
2884 			 * gate should have some valid AF_LINK entry,
2885 			 * and ln->ln_expire should have some lifetime
2886 			 * which is specified by ndp command.
2887 			 */
2888 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2889 			ln_setexpire(ln, 0);
2890 		} else {
2891 			/*
2892 			 * When req == RTM_RESOLVE, rt is created and
2893 			 * initialized in rtrequest(), so rt_expire is 0.
2894 			 */
2895 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_NOSTATE);
2896 			/* In case we're called before 1.0 sec. has elapsed */
2897 			ln_setexpire(ln, (ifp->if_eflags & IFEF_IPV6_ND6ALT) ?
2898 			    0 : MAX(timenow, 1));
2899 		}
2900 		LN_INSERTHEAD(ln);
2901 		nd6_inuse++;
2902 
2903 		/* We have at least one entry; arm the timer if not already */
2904 		nd6_sched_timeout(NULL, NULL);
2905 
2906 		/*
2907 		 * If we have too many cache entries, initiate immediate
2908 		 * purging for some "less recently used" entries.  Note that
2909 		 * we cannot directly call nd6_free() here because it would
2910 		 * cause re-entering rtable related routines triggering an LOR
2911 		 * problem.
2912 		 */
2913 		if (ip6_neighborgcthresh > 0 &&
2914 		    nd6_inuse >= ip6_neighborgcthresh) {
2915 			int i;
2916 
2917 			for (i = 0; i < 10 && llinfo_nd6.ln_prev != ln; i++) {
2918 				struct llinfo_nd6 *ln_end = llinfo_nd6.ln_prev;
2919 				struct rtentry *rt_end = ln_end->ln_rt;
2920 
2921 				/* Move this entry to the head */
2922 				RT_LOCK(rt_end);
2923 				LN_DEQUEUE(ln_end);
2924 				LN_INSERTHEAD(ln_end);
2925 
2926 				if (ln_end->ln_expire == 0) {
2927 					RT_UNLOCK(rt_end);
2928 					continue;
2929 				}
2930 				if (ln_end->ln_state > ND6_LLINFO_INCOMPLETE) {
2931 					ND6_CACHE_STATE_TRANSITION(ln_end, ND6_LLINFO_STALE);
2932 				} else {
2933 					ND6_CACHE_STATE_TRANSITION(ln_end, ND6_LLINFO_PURGE);
2934 				}
2935 				ln_setexpire(ln_end, timenow);
2936 				RT_UNLOCK(rt_end);
2937 			}
2938 		}
2939 
2940 		/*
2941 		 * check if rt_key(rt) is one of my address assigned
2942 		 * to the interface.
2943 		 */
2944 		ifa = (struct ifaddr *)in6ifa_ifpwithaddr(rt->rt_ifp,
2945 		    &SIN6(rt_key(rt))->sin6_addr);
2946 		if (ifa != NULL) {
2947 			caddr_t macp = nd6_ifptomac(ifp);
2948 			ln_setexpire(ln, 0);
2949 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2950 			if (macp != NULL) {
2951 				Bcopy(macp, LLADDR(SDL(gate)), ifp->if_addrlen);
2952 				SDL(gate)->sdl_alen = ifp->if_addrlen;
2953 			}
2954 			if (nd6_useloopback) {
2955 				if (rt->rt_ifp != lo_ifp) {
2956 					/*
2957 					 * Purge any link-layer info caching.
2958 					 */
2959 					if (rt->rt_llinfo_purge != NULL) {
2960 						rt->rt_llinfo_purge(rt);
2961 					}
2962 
2963 					/*
2964 					 * Adjust route ref count for the
2965 					 * interfaces.
2966 					 */
2967 					if (rt->rt_if_ref_fn != NULL) {
2968 						rt->rt_if_ref_fn(lo_ifp, 1);
2969 						rt->rt_if_ref_fn(rt->rt_ifp,
2970 						    -1);
2971 					}
2972 				}
2973 				rt->rt_ifp = lo_ifp;
2974 				/*
2975 				 * If rmx_mtu is not locked, update it
2976 				 * to the MTU used by the new interface.
2977 				 */
2978 				if (!(rt->rt_rmx.rmx_locks & RTV_MTU)) {
2979 					rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
2980 				}
2981 				/*
2982 				 * Make sure rt_ifa be equal to the ifaddr
2983 				 * corresponding to the address.
2984 				 * We need this because when we refer
2985 				 * rt_ifa->ia6_flags in ip6_input, we assume
2986 				 * that the rt_ifa points to the address instead
2987 				 * of the loopback address.
2988 				 */
2989 				if (ifa != rt->rt_ifa) {
2990 					rtsetifa(rt, ifa);
2991 				}
2992 			}
2993 			IFA_REMREF(ifa);
2994 		} else if (rt->rt_flags & RTF_ANNOUNCE) {
2995 			ln_setexpire(ln, 0);
2996 			ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2997 
2998 			/* join solicited node multicast for proxy ND */
2999 			if (ifp->if_flags & IFF_MULTICAST) {
3000 				struct in6_addr llsol;
3001 				struct in6_multi *in6m;
3002 				int error;
3003 
3004 				llsol = SIN6(rt_key(rt))->sin6_addr;
3005 				llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
3006 				llsol.s6_addr32[1] = 0;
3007 				llsol.s6_addr32[2] = htonl(1);
3008 				llsol.s6_addr8[12] = 0xff;
3009 				if (in6_setscope(&llsol, ifp, NULL)) {
3010 					break;
3011 				}
3012 				error = in6_mc_join(ifp, &llsol,
3013 				    NULL, &in6m, 0);
3014 				if (error) {
3015 					nd6log(error, "%s: failed to join "
3016 					    "%s (errno=%d)\n", if_name(ifp),
3017 					    ip6_sprintf(&llsol), error);
3018 				} else {
3019 					IN6M_REMREF(in6m);
3020 				}
3021 			}
3022 		}
3023 		break;
3024 
3025 	case RTM_DELETE:
3026 		if (ln == NULL) {
3027 			break;
3028 		}
3029 		/* leave from solicited node multicast for proxy ND */
3030 		if ((rt->rt_flags & RTF_ANNOUNCE) &&
3031 		    (ifp->if_flags & IFF_MULTICAST)) {
3032 			struct in6_addr llsol;
3033 			struct in6_multi *in6m;
3034 
3035 			llsol = SIN6(rt_key(rt))->sin6_addr;
3036 			llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
3037 			llsol.s6_addr32[1] = 0;
3038 			llsol.s6_addr32[2] = htonl(1);
3039 			llsol.s6_addr8[12] = 0xff;
3040 			if (in6_setscope(&llsol, ifp, NULL) == 0) {
3041 				in6_multihead_lock_shared();
3042 				IN6_LOOKUP_MULTI(&llsol, ifp, in6m);
3043 				in6_multihead_lock_done();
3044 				if (in6m != NULL) {
3045 					in6_mc_leave(in6m, NULL);
3046 					IN6M_REMREF(in6m);
3047 				}
3048 			}
3049 		}
3050 		nd6_inuse--;
3051 		/*
3052 		 * Unchain it but defer the actual freeing until the route
3053 		 * itself is to be freed.  rt->rt_llinfo still points to
3054 		 * llinfo_nd6, and likewise, ln->ln_rt stil points to this
3055 		 * route entry, except that RTF_LLINFO is now cleared.
3056 		 */
3057 		if (ln->ln_flags & ND6_LNF_IN_USE) {
3058 			LN_DEQUEUE(ln);
3059 		}
3060 
3061 		/*
3062 		 * Purge any link-layer info caching.
3063 		 */
3064 		if (rt->rt_llinfo_purge != NULL) {
3065 			rt->rt_llinfo_purge(rt);
3066 		}
3067 
3068 		rt->rt_flags &= ~RTF_LLINFO;
3069 		if (ln->ln_hold != NULL) {
3070 			m_freem_list(ln->ln_hold);
3071 			ln->ln_hold = NULL;
3072 		}
3073 	}
3074 }
3075 
3076 static int
nd6_siocgdrlst(void * data,int data_is_64)3077 nd6_siocgdrlst(void *data, int data_is_64)
3078 {
3079 	struct in6_drlist_32 *drl_32;
3080 	struct nd_defrouter *dr;
3081 	int i = 0;
3082 
3083 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3084 
3085 	dr = TAILQ_FIRST(&nd_defrouter_list);
3086 
3087 	/* XXX Handle mapped defrouter entries */
3088 	/* For 64-bit process */
3089 	if (data_is_64) {
3090 		struct in6_drlist_64 *drl_64;
3091 
3092 		drl_64 = kalloc_type(struct in6_drlist_64,
3093 		    Z_WAITOK | Z_ZERO | Z_NOFAIL);
3094 
3095 		/* preserve the interface name */
3096 		bcopy(data, drl_64, sizeof(drl_64->ifname));
3097 
3098 		while (dr && i < DRLSTSIZ) {
3099 			drl_64->defrouter[i].rtaddr = dr->rtaddr;
3100 			if (IN6_IS_ADDR_LINKLOCAL(
3101 				    &drl_64->defrouter[i].rtaddr)) {
3102 				/* XXX: need to this hack for KAME stack */
3103 				drl_64->defrouter[i].rtaddr.s6_addr16[1] = 0;
3104 			} else {
3105 				log(LOG_ERR,
3106 				    "default router list contains a "
3107 				    "non-linklocal address(%s)\n",
3108 				    ip6_sprintf(&drl_64->defrouter[i].rtaddr));
3109 			}
3110 			drl_64->defrouter[i].flags = dr->flags;
3111 			drl_64->defrouter[i].rtlifetime = (u_short)dr->rtlifetime;
3112 			drl_64->defrouter[i].expire = (u_long)nddr_getexpire(dr);
3113 			drl_64->defrouter[i].if_index = dr->ifp->if_index;
3114 			i++;
3115 			dr = TAILQ_NEXT(dr, dr_entry);
3116 		}
3117 		bcopy(drl_64, data, sizeof(*drl_64));
3118 		kfree_type(struct in6_drlist_64, drl_64);
3119 		return 0;
3120 	}
3121 
3122 	/* For 32-bit process */
3123 	drl_32 = kalloc_type(struct in6_drlist_32, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3124 
3125 	/* preserve the interface name */
3126 	bcopy(data, drl_32, sizeof(drl_32->ifname));
3127 
3128 	while (dr != NULL && i < DRLSTSIZ) {
3129 		drl_32->defrouter[i].rtaddr = dr->rtaddr;
3130 		if (IN6_IS_ADDR_LINKLOCAL(&drl_32->defrouter[i].rtaddr)) {
3131 			/* XXX: need to this hack for KAME stack */
3132 			drl_32->defrouter[i].rtaddr.s6_addr16[1] = 0;
3133 		} else {
3134 			log(LOG_ERR,
3135 			    "default router list contains a "
3136 			    "non-linklocal address(%s)\n",
3137 			    ip6_sprintf(&drl_32->defrouter[i].rtaddr));
3138 		}
3139 		drl_32->defrouter[i].flags = dr->flags;
3140 		drl_32->defrouter[i].rtlifetime = (u_short)dr->rtlifetime;
3141 		drl_32->defrouter[i].expire = (u_int32_t)nddr_getexpire(dr);
3142 		drl_32->defrouter[i].if_index = dr->ifp->if_index;
3143 		i++;
3144 		dr = TAILQ_NEXT(dr, dr_entry);
3145 	}
3146 	bcopy(drl_32, data, sizeof(*drl_32));
3147 	kfree_type(struct in6_drlist_32, drl_32);
3148 	return 0;
3149 }
3150 
3151 /*
3152  * XXX meaning of fields, especialy "raflags", is very
3153  * differnet between RA prefix list and RR/static prefix list.
3154  * how about separating ioctls into two?
3155  */
3156 static int
nd6_siocgprlst(void * data,int data_is_64)3157 nd6_siocgprlst(void *data, int data_is_64)
3158 {
3159 	struct in6_prlist_32 *prl_32;
3160 	struct nd_prefix *pr;
3161 	int i = 0;
3162 
3163 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3164 
3165 	pr = nd_prefix.lh_first;
3166 
3167 	/* XXX Handle mapped defrouter entries */
3168 	/* For 64-bit process */
3169 	if (data_is_64) {
3170 		struct in6_prlist_64 *prl_64;
3171 
3172 		prl_64 = kalloc_type(struct in6_prlist_64,
3173 		    Z_WAITOK | Z_ZERO | Z_NOFAIL);
3174 
3175 		/* preserve the interface name */
3176 		bcopy(data, prl_64, sizeof(prl_64->ifname));
3177 
3178 		while (pr && i < PRLSTSIZ) {
3179 			struct nd_pfxrouter *pfr;
3180 			int j;
3181 			uint32_t ifscope;
3182 
3183 			NDPR_LOCK(pr);
3184 			(void) in6_embedscope(&prl_64->prefix[i].prefix,
3185 			    &pr->ndpr_prefix, NULL, NULL, NULL, &ifscope);
3186 			prl_64->prefix[i].prefix.s6_addr16[1] = htons((uint16_t)ifscope);
3187 			prl_64->prefix[i].raflags = pr->ndpr_raf;
3188 			prl_64->prefix[i].prefixlen = pr->ndpr_plen;
3189 			prl_64->prefix[i].vltime = pr->ndpr_vltime;
3190 			prl_64->prefix[i].pltime = pr->ndpr_pltime;
3191 			prl_64->prefix[i].if_index = pr->ndpr_ifp->if_index;
3192 			prl_64->prefix[i].expire = (u_long)ndpr_getexpire(pr);
3193 
3194 			pfr = pr->ndpr_advrtrs.lh_first;
3195 			j = 0;
3196 			while (pfr) {
3197 				if (j < DRLSTSIZ) {
3198 #define RTRADDR prl_64->prefix[i].advrtr[j]
3199 					RTRADDR = pfr->router->rtaddr;
3200 					if (IN6_IS_ADDR_LINKLOCAL(&RTRADDR)) {
3201 						/* XXX: hack for KAME */
3202 						RTRADDR.s6_addr16[1] = 0;
3203 					} else {
3204 						log(LOG_ERR,
3205 						    "a router(%s) advertises "
3206 						    "a prefix with "
3207 						    "non-link local address\n",
3208 						    ip6_sprintf(&RTRADDR));
3209 					}
3210 #undef RTRADDR
3211 				}
3212 				j++;
3213 				pfr = pfr->pfr_next;
3214 			}
3215 			ASSERT(j <= USHRT_MAX);
3216 			prl_64->prefix[i].advrtrs = (u_short)j;
3217 			prl_64->prefix[i].origin = PR_ORIG_RA;
3218 			NDPR_UNLOCK(pr);
3219 
3220 			i++;
3221 			pr = pr->ndpr_next;
3222 		}
3223 		bcopy(prl_64, data, sizeof(*prl_64));
3224 		kfree_type(struct in6_prlist_64, prl_64);
3225 		return 0;
3226 	}
3227 
3228 	/* For 32-bit process */
3229 	prl_32 = kalloc_type(struct in6_prlist_32, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3230 
3231 	/* preserve the interface name */
3232 	bcopy(data, prl_32, sizeof(prl_32->ifname));
3233 
3234 	while (pr && i < PRLSTSIZ) {
3235 		struct nd_pfxrouter *pfr;
3236 		int j;
3237 		uint32_t ifscope;
3238 
3239 		NDPR_LOCK(pr);
3240 		(void) in6_embedscope(&prl_32->prefix[i].prefix,
3241 		    &pr->ndpr_prefix, NULL, NULL, NULL, &ifscope);
3242 		prl_32->prefix[i].prefix.s6_addr16[1] = htons((uint16_t)ifscope);
3243 		prl_32->prefix[i].raflags = pr->ndpr_raf;
3244 		prl_32->prefix[i].prefixlen = pr->ndpr_plen;
3245 		prl_32->prefix[i].vltime = pr->ndpr_vltime;
3246 		prl_32->prefix[i].pltime = pr->ndpr_pltime;
3247 		prl_32->prefix[i].if_index = pr->ndpr_ifp->if_index;
3248 		prl_32->prefix[i].expire = (u_int32_t)ndpr_getexpire(pr);
3249 
3250 		pfr = pr->ndpr_advrtrs.lh_first;
3251 		j = 0;
3252 		while (pfr) {
3253 			if (j < DRLSTSIZ) {
3254 #define RTRADDR prl_32->prefix[i].advrtr[j]
3255 				RTRADDR = pfr->router->rtaddr;
3256 				if (IN6_IS_ADDR_LINKLOCAL(&RTRADDR)) {
3257 					/* XXX: hack for KAME */
3258 					RTRADDR.s6_addr16[1] = 0;
3259 				} else {
3260 					log(LOG_ERR,
3261 					    "a router(%s) advertises "
3262 					    "a prefix with "
3263 					    "non-link local address\n",
3264 					    ip6_sprintf(&RTRADDR));
3265 				}
3266 #undef RTRADDR
3267 			}
3268 			j++;
3269 			pfr = pfr->pfr_next;
3270 		}
3271 		ASSERT(j <= USHRT_MAX);
3272 		prl_32->prefix[i].advrtrs = (u_short)j;
3273 		prl_32->prefix[i].origin = PR_ORIG_RA;
3274 		NDPR_UNLOCK(pr);
3275 
3276 		i++;
3277 		pr = pr->ndpr_next;
3278 	}
3279 	bcopy(prl_32, data, sizeof(*prl_32));
3280 	kfree_type(struct in6_prlist_32, prl_32);
3281 	return 0;
3282 }
3283 
3284 int
nd6_ioctl(u_long cmd,caddr_t data,struct ifnet * ifp)3285 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
3286 {
3287 	struct nd_defrouter *dr;
3288 	struct nd_prefix *pr;
3289 	struct rtentry *rt;
3290 	int error = 0;
3291 
3292 	VERIFY(ifp != NULL);
3293 
3294 	switch (cmd) {
3295 	case SIOCGDRLST_IN6_32:         /* struct in6_drlist_32 */
3296 	case SIOCGDRLST_IN6_64:         /* struct in6_drlist_64 */
3297 		/*
3298 		 * obsolete API, use sysctl under net.inet6.icmp6
3299 		 */
3300 		lck_mtx_lock(nd6_mutex);
3301 		error = nd6_siocgdrlst(data, cmd == SIOCGDRLST_IN6_64);
3302 		lck_mtx_unlock(nd6_mutex);
3303 		break;
3304 
3305 	case SIOCGPRLST_IN6_32:         /* struct in6_prlist_32 */
3306 	case SIOCGPRLST_IN6_64:         /* struct in6_prlist_64 */
3307 		/*
3308 		 * obsolete API, use sysctl under net.inet6.icmp6
3309 		 */
3310 		lck_mtx_lock(nd6_mutex);
3311 		error = nd6_siocgprlst(data, cmd == SIOCGPRLST_IN6_64);
3312 		lck_mtx_unlock(nd6_mutex);
3313 		break;
3314 
3315 	case OSIOCGIFINFO_IN6:          /* struct in6_ondireq */
3316 	case SIOCGIFINFO_IN6: {         /* struct in6_ondireq */
3317 		u_int32_t linkmtu;
3318 		struct in6_ondireq *ondi = (struct in6_ondireq *)(void *)data;
3319 		struct nd_ifinfo *ndi;
3320 		/*
3321 		 * SIOCGIFINFO_IN6 ioctl is encoded with in6_ondireq
3322 		 * instead of in6_ndireq, so we treat it as such.
3323 		 */
3324 		ndi = ND_IFINFO(ifp);
3325 		if ((NULL == ndi) || (FALSE == ndi->initialized)) {
3326 			error = EINVAL;
3327 			break;
3328 		}
3329 		lck_mtx_lock(&ndi->lock);
3330 		linkmtu = IN6_LINKMTU(ifp);
3331 		bcopy(&linkmtu, &ondi->ndi.linkmtu, sizeof(linkmtu));
3332 		bcopy(&ndi->maxmtu, &ondi->ndi.maxmtu,
3333 		    sizeof(u_int32_t));
3334 		bcopy(&ndi->basereachable, &ondi->ndi.basereachable,
3335 		    sizeof(u_int32_t));
3336 		bcopy(&ndi->reachable, &ondi->ndi.reachable,
3337 		    sizeof(u_int32_t));
3338 		bcopy(&ndi->retrans, &ondi->ndi.retrans,
3339 		    sizeof(u_int32_t));
3340 		bcopy(&ndi->flags, &ondi->ndi.flags,
3341 		    sizeof(u_int32_t));
3342 		bcopy(&ndi->recalctm, &ondi->ndi.recalctm,
3343 		    sizeof(int));
3344 		ondi->ndi.chlim = ndi->chlim;
3345 		/*
3346 		 * The below truncation is fine as we mostly use it for
3347 		 * debugging purpose.
3348 		 */
3349 		ondi->ndi.receivedra = (uint8_t)ndi->ndefrouters;
3350 		ondi->ndi.collision_count = (uint8_t)ndi->cga_collision_count;
3351 		lck_mtx_unlock(&ndi->lock);
3352 		break;
3353 	}
3354 
3355 	case SIOCSIFINFO_FLAGS: {       /* struct in6_ndireq */
3356 		/*
3357 		 * XXX BSD has a bunch of checks here to ensure
3358 		 * that interface disabled flag is not reset if
3359 		 * link local address has failed DAD.
3360 		 * Investigate that part.
3361 		 */
3362 		struct in6_ndireq *cndi = (struct in6_ndireq *)(void *)data;
3363 		u_int32_t oflags, flags;
3364 		struct nd_ifinfo *ndi = ND_IFINFO(ifp);
3365 
3366 		/* XXX: almost all other fields of cndi->ndi is unused */
3367 		if ((NULL == ndi) || !ndi->initialized) {
3368 			error = EINVAL;
3369 			break;
3370 		}
3371 
3372 		lck_mtx_lock(&ndi->lock);
3373 		oflags = ndi->flags;
3374 		bcopy(&cndi->ndi.flags, &(ndi->flags), sizeof(flags));
3375 		flags = ndi->flags;
3376 		lck_mtx_unlock(&ndi->lock);
3377 
3378 		if (oflags == flags) {
3379 			break;
3380 		}
3381 
3382 		error = nd6_setifinfo(ifp, oflags, flags);
3383 		break;
3384 	}
3385 
3386 	case SIOCSNDFLUSH_IN6:          /* struct in6_ifreq */
3387 		/* flush default router list */
3388 		/*
3389 		 * xxx sumikawa: should not delete route if default
3390 		 * route equals to the top of default router list
3391 		 *
3392 		 * XXX TODO: Needs to be done for RTI as well
3393 		 * Is very specific flush command with ndp for default routers.
3394 		 */
3395 		lck_mtx_lock(nd6_mutex);
3396 		defrouter_reset();
3397 		defrouter_select(ifp, NULL);
3398 		lck_mtx_unlock(nd6_mutex);
3399 		/* xxx sumikawa: flush prefix list */
3400 		break;
3401 
3402 	case SIOCSPFXFLUSH_IN6: {       /* struct in6_ifreq */
3403 		/* flush all the prefix advertised by routers */
3404 		struct nd_prefix *next = NULL;
3405 
3406 		lck_mtx_lock(nd6_mutex);
3407 		for (pr = nd_prefix.lh_first; pr; pr = next) {
3408 			struct in6_ifaddr *ia = NULL;
3409 			bool iterate_pfxlist_again = false;
3410 
3411 			next = pr->ndpr_next;
3412 
3413 			NDPR_LOCK(pr);
3414 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
3415 				NDPR_UNLOCK(pr);
3416 				continue; /* XXX */
3417 			}
3418 			if (ifp != lo_ifp && pr->ndpr_ifp != ifp) {
3419 				NDPR_UNLOCK(pr);
3420 				continue;
3421 			}
3422 			/* do we really have to remove addresses as well? */
3423 			NDPR_ADDREF(pr);
3424 			NDPR_UNLOCK(pr);
3425 			lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
3426 			bool from_begining = true;
3427 			while (from_begining) {
3428 				from_begining = false;
3429 				TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
3430 					IFA_LOCK(&ia->ia_ifa);
3431 					if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0) {
3432 						IFA_UNLOCK(&ia->ia_ifa);
3433 						continue;
3434 					}
3435 
3436 					if (ia->ia6_ndpr == pr) {
3437 						IFA_ADDREF_LOCKED(&ia->ia_ifa);
3438 						IFA_UNLOCK(&ia->ia_ifa);
3439 						lck_rw_done(&in6_ifaddr_rwlock);
3440 						lck_mtx_unlock(nd6_mutex);
3441 						in6_purgeaddr(&ia->ia_ifa);
3442 						IFA_REMREF(&ia->ia_ifa);
3443 						lck_mtx_lock(nd6_mutex);
3444 						lck_rw_lock_exclusive(
3445 							&in6_ifaddr_rwlock);
3446 						/*
3447 						 * Purging the address caused
3448 						 * in6_ifaddr_rwlock to be
3449 						 * dropped and
3450 						 * reacquired; therefore search again
3451 						 * from the beginning of in6_ifaddrs.
3452 						 * The same applies for the prefix list.
3453 						 */
3454 						iterate_pfxlist_again = true;
3455 						from_begining = true;
3456 						break;
3457 					}
3458 					IFA_UNLOCK(&ia->ia_ifa);
3459 				}
3460 			}
3461 			lck_rw_done(&in6_ifaddr_rwlock);
3462 			NDPR_LOCK(pr);
3463 			prelist_remove(pr);
3464 			NDPR_UNLOCK(pr);
3465 			pfxlist_onlink_check();
3466 			NDPR_REMREF(pr);
3467 			if (iterate_pfxlist_again) {
3468 				next = nd_prefix.lh_first;
3469 			}
3470 		}
3471 		lck_mtx_unlock(nd6_mutex);
3472 		break;
3473 	}
3474 
3475 	case SIOCSRTRFLUSH_IN6: {       /* struct in6_ifreq */
3476 		/* flush all the default routers */
3477 		struct nd_defrouter *next;
3478 		struct nd_drhead nd_defrouter_tmp;
3479 
3480 		TAILQ_INIT(&nd_defrouter_tmp);
3481 		lck_mtx_lock(nd6_mutex);
3482 		if ((dr = TAILQ_FIRST(&nd_defrouter_list)) != NULL) {
3483 			/*
3484 			 * The first entry of the list may be stored in
3485 			 * the routing table, so we'll delete it later.
3486 			 */
3487 			for (dr = TAILQ_NEXT(dr, dr_entry); dr; dr = next) {
3488 				next = TAILQ_NEXT(dr, dr_entry);
3489 				if (ifp == lo_ifp || dr->ifp == ifp) {
3490 					/*
3491 					 * Remove the entry from default router list
3492 					 * and add it to the temp list.
3493 					 * nd_defrouter_tmp will be a local temporary
3494 					 * list as no one else can get the same
3495 					 * removed entry once it is removed from default
3496 					 * router list.
3497 					 * Remove the reference after calling defrtrlist_de
3498 					 */
3499 					TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
3500 					TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
3501 				}
3502 			}
3503 
3504 			dr = TAILQ_FIRST(&nd_defrouter_list);
3505 			if (ifp == lo_ifp ||
3506 			    dr->ifp == ifp) {
3507 				TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
3508 				TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
3509 			}
3510 		}
3511 
3512 		/*
3513 		 * Keep the following separate from the above iteration of
3514 		 * nd_defrouter because it's not safe to call
3515 		 * defrtrlist_del while iterating global default
3516 		 * router list. Global list has to be traversed
3517 		 * while holding nd6_mutex throughout.
3518 		 *
3519 		 * The following call to defrtrlist_del should be
3520 		 * safe as we are iterating a local list of
3521 		 * default routers.
3522 		 */
3523 		TAILQ_FOREACH_SAFE(dr, &nd_defrouter_tmp, dr_entry, next) {
3524 			TAILQ_REMOVE(&nd_defrouter_tmp, dr, dr_entry);
3525 			defrtrlist_del(dr, NULL);
3526 			NDDR_REMREF(dr);        /* remove list reference */
3527 		}
3528 
3529 		/* For now flush RTI routes here as well to avoid any regressions */
3530 		nd6_purge_interface_rti_entries((ifp == lo_ifp) ? NULL : ifp);
3531 
3532 		lck_mtx_unlock(nd6_mutex);
3533 		break;
3534 	}
3535 
3536 	case SIOCGNBRINFO_IN6_32: {     /* struct in6_nbrinfo_32 */
3537 		struct llinfo_nd6 *ln;
3538 		struct in6_nbrinfo_32 nbi_32;
3539 		struct in6_addr nb_addr; /* make local for safety */
3540 
3541 		bcopy(data, &nbi_32, sizeof(nbi_32));
3542 		nb_addr = nbi_32.addr;
3543 		/*
3544 		 * XXX: KAME specific hack for scoped addresses
3545 		 *      XXXX: for other scopes than link-local?
3546 		 */
3547 		if (in6_embedded_scope && (IN6_IS_ADDR_LINKLOCAL(&nbi_32.addr) ||
3548 		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi_32.addr))) {
3549 			u_int16_t *idp =
3550 			    (u_int16_t *)(void *)&nb_addr.s6_addr[2];
3551 
3552 			if (*idp == 0) {
3553 				*idp = htons(ifp->if_index);
3554 			}
3555 		}
3556 
3557 		/* Callee returns a locked route upon success */
3558 		if ((rt = nd6_lookup(&nb_addr, 0, ifp, 0)) == NULL) {
3559 			error = EINVAL;
3560 			break;
3561 		}
3562 		RT_LOCK_ASSERT_HELD(rt);
3563 		ln = rt->rt_llinfo;
3564 		nbi_32.state = ln->ln_state;
3565 		nbi_32.asked = ln->ln_asked;
3566 		nbi_32.isrouter = ln->ln_router;
3567 		nbi_32.expire = (int)ln_getexpire(ln);
3568 		RT_REMREF_LOCKED(rt);
3569 		RT_UNLOCK(rt);
3570 		bcopy(&nbi_32, data, sizeof(nbi_32));
3571 		break;
3572 	}
3573 
3574 	case SIOCGNBRINFO_IN6_64: {     /* struct in6_nbrinfo_64 */
3575 		struct llinfo_nd6 *ln;
3576 		struct in6_nbrinfo_64 nbi_64;
3577 		struct in6_addr nb_addr; /* make local for safety */
3578 
3579 		bcopy(data, &nbi_64, sizeof(nbi_64));
3580 		nb_addr = nbi_64.addr;
3581 		/*
3582 		 * XXX: KAME specific hack for scoped addresses
3583 		 *      XXXX: for other scopes than link-local?
3584 		 */
3585 		if (in6_embedded_scope && (IN6_IS_ADDR_LINKLOCAL(&nbi_64.addr) ||
3586 		    IN6_IS_ADDR_MC_LINKLOCAL(&nbi_64.addr))) {
3587 			u_int16_t *idp =
3588 			    (u_int16_t *)(void *)&nb_addr.s6_addr[2];
3589 
3590 			if (*idp == 0) {
3591 				*idp = htons(ifp->if_index);
3592 			}
3593 		}
3594 
3595 		/* Callee returns a locked route upon success */
3596 		if ((rt = nd6_lookup(&nb_addr, 0, ifp, 0)) == NULL) {
3597 			error = EINVAL;
3598 			break;
3599 		}
3600 		RT_LOCK_ASSERT_HELD(rt);
3601 		ln = rt->rt_llinfo;
3602 		nbi_64.state = ln->ln_state;
3603 		nbi_64.asked = ln->ln_asked;
3604 		nbi_64.isrouter = ln->ln_router;
3605 		nbi_64.expire = (int)ln_getexpire(ln);
3606 		RT_REMREF_LOCKED(rt);
3607 		RT_UNLOCK(rt);
3608 		bcopy(&nbi_64, data, sizeof(nbi_64));
3609 		break;
3610 	}
3611 
3612 	case SIOCGDEFIFACE_IN6_32:      /* struct in6_ndifreq_32 */
3613 	case SIOCGDEFIFACE_IN6_64: {    /* struct in6_ndifreq_64 */
3614 		struct in6_ndifreq_64 *ndif_64 =
3615 		    (struct in6_ndifreq_64 *)(void *)data;
3616 		struct in6_ndifreq_32 *ndif_32 =
3617 		    (struct in6_ndifreq_32 *)(void *)data;
3618 
3619 		if (cmd == SIOCGDEFIFACE_IN6_64) {
3620 			u_int64_t j = nd6_defifindex;
3621 			__nochk_bcopy(&j, &ndif_64->ifindex, sizeof(j));
3622 		} else {
3623 			bcopy(&nd6_defifindex, &ndif_32->ifindex,
3624 			    sizeof(u_int32_t));
3625 		}
3626 		break;
3627 	}
3628 
3629 	case SIOCSDEFIFACE_IN6_32:      /* struct in6_ndifreq_32 */
3630 	case SIOCSDEFIFACE_IN6_64: {    /* struct in6_ndifreq_64 */
3631 		struct in6_ndifreq_64 *ndif_64 =
3632 		    (struct in6_ndifreq_64 *)(void *)data;
3633 		struct in6_ndifreq_32 *ndif_32 =
3634 		    (struct in6_ndifreq_32 *)(void *)data;
3635 		u_int32_t idx;
3636 
3637 		if (cmd == SIOCSDEFIFACE_IN6_64) {
3638 			u_int64_t j;
3639 			__nochk_bcopy(&ndif_64->ifindex, &j, sizeof(j));
3640 			idx = (u_int32_t)j;
3641 		} else {
3642 			bcopy(&ndif_32->ifindex, &idx, sizeof(idx));
3643 		}
3644 
3645 		error = nd6_setdefaultiface(idx);
3646 		return error;
3647 		/* NOTREACHED */
3648 	}
3649 	case SIOCGIFCGAPREP_IN6_32:
3650 	case SIOCGIFCGAPREP_IN6_64: {
3651 		/* get CGA parameters */
3652 		union {
3653 			struct in6_cgareq_32    *cga32;
3654 			struct in6_cgareq_64    *cga64;
3655 			void                    *data;
3656 		} cgareq_u;
3657 		struct nd_ifinfo        *ndi;
3658 		struct in6_cga_modifier *ndi_cga_mod;
3659 		struct in6_cga_modifier *req_cga_mod;
3660 
3661 		ndi = ND_IFINFO(ifp);
3662 		if ((NULL == ndi) || !ndi->initialized) {
3663 			error = EINVAL;
3664 			break;
3665 		}
3666 		cgareq_u.data = data;
3667 		req_cga_mod = (cmd == SIOCGIFCGAPREP_IN6_64)
3668 		    ? &(cgareq_u.cga64->cgar_cgaprep.cga_modifier)
3669 		    : &(cgareq_u.cga32->cgar_cgaprep.cga_modifier);
3670 		lck_mtx_lock(&ndi->lock);
3671 		ndi_cga_mod = &(ndi->local_cga_modifier);
3672 		bcopy(ndi_cga_mod, req_cga_mod, sizeof(*req_cga_mod));
3673 		lck_mtx_unlock(&ndi->lock);
3674 		break;
3675 	}
3676 	case SIOCSIFCGAPREP_IN6_32:
3677 	case SIOCSIFCGAPREP_IN6_64:
3678 	{
3679 		/* set CGA parameters */
3680 		struct in6_cgareq       cgareq;
3681 		int                     is64;
3682 		struct nd_ifinfo        *ndi;
3683 		struct in6_cga_modifier *ndi_cga_mod;
3684 		struct in6_cga_modifier *req_cga_mod;
3685 
3686 		ndi = ND_IFINFO(ifp);
3687 		if ((NULL == ndi) || !ndi->initialized) {
3688 			error = EINVAL;
3689 			break;
3690 		}
3691 		is64 = (cmd == SIOCSIFCGAPREP_IN6_64);
3692 		in6_cgareq_copy_from_user(data, is64, &cgareq);
3693 		req_cga_mod = &cgareq.cgar_cgaprep.cga_modifier;
3694 		lck_mtx_lock(&ndi->lock);
3695 		ndi_cga_mod = &(ndi->local_cga_modifier);
3696 		bcopy(req_cga_mod, ndi_cga_mod, sizeof(*ndi_cga_mod));
3697 		ndi->cga_initialized = TRUE;
3698 		ndi->cga_collision_count = 0;
3699 		lck_mtx_unlock(&ndi->lock);
3700 		break;
3701 	}
3702 	default:
3703 		break;
3704 	}
3705 	return error;
3706 }
3707 
3708 /*
3709  * Create neighbor cache entry and cache link-layer address,
3710  * on reception of inbound ND6 packets. (RS/RA/NS/redirect)
3711  */
3712 void
nd6_cache_lladdr(struct ifnet * ifp,struct in6_addr * from,char * lladdr,int lladdrlen,int type,int code,int * did_update)3713 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
3714     int lladdrlen, int type, int code, int *did_update)
3715 {
3716 #pragma unused(lladdrlen)
3717 	struct rtentry *rt = NULL;
3718 	struct llinfo_nd6 *ln = NULL;
3719 	int is_newentry;
3720 	struct sockaddr_dl *sdl = NULL;
3721 	int do_update;
3722 	int olladdr;
3723 	int llchange;
3724 	short newstate = 0;
3725 	uint64_t timenow;
3726 	boolean_t sched_timeout = FALSE;
3727 	struct nd_ifinfo *ndi = NULL;
3728 
3729 	if (ifp == NULL) {
3730 		panic("ifp == NULL in nd6_cache_lladdr");
3731 	}
3732 	if (from == NULL) {
3733 		panic("from == NULL in nd6_cache_lladdr");
3734 	}
3735 
3736 	if (did_update != NULL) {
3737 		did_update = 0;
3738 	}
3739 
3740 	/* nothing must be updated for unspecified address */
3741 	if (IN6_IS_ADDR_UNSPECIFIED(from)) {
3742 		return;
3743 	}
3744 
3745 	/*
3746 	 * Validation about ifp->if_addrlen and lladdrlen must be done in
3747 	 * the caller.
3748 	 */
3749 	timenow = net_uptime();
3750 
3751 	rt = nd6_lookup(from, 0, ifp, 0);
3752 	if (rt == NULL) {
3753 		if ((rt = nd6_lookup(from, 1, ifp, 0)) == NULL) {
3754 			return;
3755 		}
3756 		RT_LOCK_ASSERT_HELD(rt);
3757 		is_newentry = 1;
3758 	} else {
3759 		RT_LOCK_ASSERT_HELD(rt);
3760 		/* do nothing if static ndp is set */
3761 		if (rt->rt_flags & RTF_STATIC) {
3762 			RT_REMREF_LOCKED(rt);
3763 			RT_UNLOCK(rt);
3764 			return;
3765 		}
3766 		is_newentry = 0;
3767 	}
3768 
3769 	if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
3770 fail:
3771 		RT_UNLOCK(rt);
3772 		nd6_free(rt);
3773 		rtfree(rt);
3774 		return;
3775 	}
3776 	ln = (struct llinfo_nd6 *)rt->rt_llinfo;
3777 	if (ln == NULL) {
3778 		goto fail;
3779 	}
3780 	if (rt->rt_gateway == NULL) {
3781 		goto fail;
3782 	}
3783 	if (rt->rt_gateway->sa_family != AF_LINK) {
3784 		goto fail;
3785 	}
3786 	sdl = SDL(rt->rt_gateway);
3787 
3788 	olladdr = (sdl->sdl_alen) ? 1 : 0;
3789 	if (olladdr && lladdr) {
3790 		if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen)) {
3791 			llchange = 1;
3792 		} else {
3793 			llchange = 0;
3794 		}
3795 	} else {
3796 		llchange = 0;
3797 	}
3798 
3799 	/*
3800 	 * newentry olladdr  lladdr  llchange	(*=record)
3801 	 *	0	n	n	--	(1)
3802 	 *	0	y	n	--	(2)
3803 	 *	0	n	y	--	(3) * STALE
3804 	 *	0	y	y	n	(4) *
3805 	 *	0	y	y	y	(5) * STALE
3806 	 *	1	--	n	--	(6)   NOSTATE(= PASSIVE)
3807 	 *	1	--	y	--	(7) * STALE
3808 	 */
3809 
3810 	if (lladdr != NULL) {           /* (3-5) and (7) */
3811 		/*
3812 		 * Record source link-layer address
3813 		 * XXX is it dependent to ifp->if_type?
3814 		 */
3815 		sdl->sdl_alen = ifp->if_addrlen;
3816 		bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
3817 
3818 		/* cache the gateway (sender HW) address */
3819 		nd6_llreach_alloc(rt, ifp, LLADDR(sdl), sdl->sdl_alen, FALSE);
3820 	}
3821 
3822 	if (is_newentry == 0) {
3823 		if ((!olladdr && lladdr != NULL) ||     /* (3) */
3824 		    (olladdr && lladdr != NULL && llchange)) {  /* (5) */
3825 			do_update = 1;
3826 			newstate = ND6_LLINFO_STALE;
3827 		} else {                                /* (1-2,4) */
3828 			do_update = 0;
3829 		}
3830 	} else {
3831 		do_update = 1;
3832 		if (lladdr == NULL) {                   /* (6) */
3833 			newstate = ND6_LLINFO_NOSTATE;
3834 		} else {                                /* (7) */
3835 			newstate = ND6_LLINFO_STALE;
3836 		}
3837 	}
3838 
3839 	/*
3840 	 * For interface's that do not perform NUD or NDP
3841 	 * neighbor cache entres must always be marked
3842 	 * reachable with no expiry
3843 	 */
3844 	ndi = ND_IFINFO(ifp);
3845 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
3846 
3847 	if ((ndi && !(ndi->flags & ND6_IFF_PERFORMNUD)) ||
3848 	    (ifp->if_eflags & IFEF_IPV6_ND6ALT)) {
3849 		newstate = ND6_LLINFO_REACHABLE;
3850 		ln_setexpire(ln, 0);
3851 	}
3852 
3853 	if (do_update) {
3854 		/*
3855 		 * Update the state of the neighbor cache.
3856 		 */
3857 		ND6_CACHE_STATE_TRANSITION(ln, newstate);
3858 
3859 		if ((ln->ln_state == ND6_LLINFO_STALE) ||
3860 		    (ln->ln_state == ND6_LLINFO_REACHABLE)) {
3861 			struct mbuf *m = ln->ln_hold;
3862 			/*
3863 			 * XXX: since nd6_output() below will cause
3864 			 * state tansition to DELAY and reset the timer,
3865 			 * we must set the timer now, although it is actually
3866 			 * meaningless.
3867 			 */
3868 			if (ln->ln_state == ND6_LLINFO_STALE) {
3869 				ln_setexpire(ln, timenow + nd6_gctimer);
3870 			}
3871 
3872 			ln->ln_hold = NULL;
3873 			if (m != NULL) {
3874 				struct sockaddr_in6 sin6;
3875 
3876 				rtkey_to_sa6(rt, &sin6);
3877 				/*
3878 				 * we assume ifp is not a p2p here, so just
3879 				 * set the 2nd argument as the 1st one.
3880 				 */
3881 				RT_UNLOCK(rt);
3882 				nd6_output_list(ifp, ifp, m, &sin6, rt, NULL);
3883 				RT_LOCK(rt);
3884 			}
3885 		} else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
3886 			/* probe right away */
3887 			ln_setexpire(ln, timenow);
3888 			sched_timeout = TRUE;
3889 		}
3890 	}
3891 
3892 	/*
3893 	 * ICMP6 type dependent behavior.
3894 	 *
3895 	 * NS: clear IsRouter if new entry
3896 	 * RS: clear IsRouter
3897 	 * RA: set IsRouter if there's lladdr
3898 	 * redir: clear IsRouter if new entry
3899 	 *
3900 	 * RA case, (1):
3901 	 * The spec says that we must set IsRouter in the following cases:
3902 	 * - If lladdr exist, set IsRouter.  This means (1-5).
3903 	 * - If it is old entry (!newentry), set IsRouter.  This means (7).
3904 	 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
3905 	 * A quetion arises for (1) case.  (1) case has no lladdr in the
3906 	 * neighbor cache, this is similar to (6).
3907 	 * This case is rare but we figured that we MUST NOT set IsRouter.
3908 	 *
3909 	 * newentry olladdr  lladdr  llchange	    NS  RS	RA	redir
3910 	 *								D R
3911 	 *	0	n	n	--	(1)	c	?	s
3912 	 *	0	y	n	--	(2)	c	s	s
3913 	 *	0	n	y	--	(3)	c	s	s
3914 	 *	0	y	y	n	(4)	c	s	s
3915 	 *	0	y	y	y	(5)	c	s	s
3916 	 *	1	--	n	--	(6) c	c		c s
3917 	 *	1	--	y	--	(7) c	c	s	c s
3918 	 *
3919 	 *					(c=clear s=set)
3920 	 */
3921 	switch (type & 0xff) {
3922 	case ND_NEIGHBOR_SOLICIT:
3923 		/*
3924 		 * New entry must have is_router flag cleared.
3925 		 */
3926 		if (is_newentry) {      /* (6-7) */
3927 			ln->ln_router = 0;
3928 		}
3929 		break;
3930 	case ND_REDIRECT:
3931 		/*
3932 		 * If the ICMP message is a Redirect to a better router, always
3933 		 * set the is_router flag.  Otherwise, if the entry is newly
3934 		 * created, then clear the flag.  [RFC 4861, sec 8.3]
3935 		 */
3936 		if (code == ND_REDIRECT_ROUTER) {
3937 			ln->ln_router = 1;
3938 		} else if (is_newentry) { /* (6-7) */
3939 			ln->ln_router = 0;
3940 		}
3941 		break;
3942 	case ND_ROUTER_SOLICIT:
3943 		/*
3944 		 * is_router flag must always be cleared.
3945 		 */
3946 		ln->ln_router = 0;
3947 		break;
3948 	case ND_ROUTER_ADVERT:
3949 		/*
3950 		 * Mark an entry with lladdr as a router.
3951 		 */
3952 		if ((!is_newentry && (olladdr || lladdr)) ||    /* (2-5) */
3953 		    (is_newentry && lladdr)) {                  /* (7) */
3954 			ln->ln_router = 1;
3955 		}
3956 		break;
3957 	}
3958 
3959 	if (do_update) {
3960 		int route_ev_code = 0;
3961 
3962 		if (llchange) {
3963 			route_ev_code = ROUTE_LLENTRY_CHANGED;
3964 		} else {
3965 			route_ev_code = ROUTE_LLENTRY_RESOLVED;
3966 		}
3967 
3968 		/* Enqueue work item to invoke callback for this route entry */
3969 		route_event_enqueue_nwk_wq_entry(rt, NULL, route_ev_code, NULL, TRUE);
3970 
3971 		if (ln->ln_router || (rt->rt_flags & RTF_ROUTER)) {
3972 			struct radix_node_head  *rnh = NULL;
3973 			struct in6_addr rt_addr = SIN6(rt_key(rt))->sin6_addr;
3974 			struct ifnet *rt_ifp = rt->rt_ifp;
3975 			struct route_event rt_ev;
3976 			route_event_init(&rt_ev, rt, NULL, llchange ? ROUTE_LLENTRY_CHANGED :
3977 			    ROUTE_LLENTRY_RESOLVED);
3978 			/*
3979 			 * We already have a valid reference on rt.
3980 			 * The function frees that before returning.
3981 			 * We therefore don't need an extra reference here
3982 			 */
3983 			RT_UNLOCK(rt);
3984 			defrouter_set_reachability(&rt_addr, rt_ifp, TRUE);
3985 			lck_mtx_lock(rnh_lock);
3986 
3987 			rnh = rt_tables[AF_INET6];
3988 			if (rnh != NULL) {
3989 				(void) rnh->rnh_walktree(rnh, route_event_walktree,
3990 				    (void *)&rt_ev);
3991 			}
3992 			lck_mtx_unlock(rnh_lock);
3993 			RT_LOCK(rt);
3994 		}
3995 	}
3996 
3997 	if (did_update != NULL) {
3998 		*did_update = do_update;
3999 	}
4000 
4001 	/*
4002 	 * When the link-layer address of a router changes, select the
4003 	 * best router again.  In particular, when the neighbor entry is newly
4004 	 * created, it might affect the selection policy.
4005 	 * Question: can we restrict the first condition to the "is_newentry"
4006 	 * case?
4007 	 *
4008 	 * Note: Perform default router selection even when we are a router,
4009 	 * if Scoped Routing is enabled.
4010 	 */
4011 	if (do_update && ln->ln_router) {
4012 		/*
4013 		 * XXX TODO: This should also be iterated over router list
4014 		 * for route information option's router lists as well.
4015 		 */
4016 		RT_REMREF_LOCKED(rt);
4017 		RT_UNLOCK(rt);
4018 		lck_mtx_lock(nd6_mutex);
4019 		defrouter_select(ifp, NULL);
4020 		nd6_router_select_rti_entries(ifp);
4021 		lck_mtx_unlock(nd6_mutex);
4022 	} else {
4023 		RT_REMREF_LOCKED(rt);
4024 		RT_UNLOCK(rt);
4025 	}
4026 	if (sched_timeout) {
4027 		lck_mtx_lock(rnh_lock);
4028 		nd6_sched_timeout(NULL, NULL);
4029 		lck_mtx_unlock(rnh_lock);
4030 	}
4031 }
4032 
4033 static void
nd6_slowtimo(void * arg)4034 nd6_slowtimo(void *arg)
4035 {
4036 #pragma unused(arg)
4037 	struct nd_ifinfo *nd6if = NULL;
4038 	struct ifnet *ifp = NULL;
4039 
4040 	ifnet_head_lock_shared();
4041 	for (ifp = ifnet_head.tqh_first; ifp;
4042 	    ifp = ifp->if_link.tqe_next) {
4043 		nd6if = ND_IFINFO(ifp);
4044 		if ((NULL == nd6if) || (FALSE == nd6if->initialized)) {
4045 			continue;
4046 		}
4047 
4048 		lck_mtx_lock(&nd6if->lock);
4049 		if (nd6if->basereachable && /* already initialized */
4050 		    (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
4051 			/*
4052 			 * Since reachable time rarely changes by router
4053 			 * advertisements, we SHOULD insure that a new random
4054 			 * value gets recomputed at least once every few hours.
4055 			 * (RFC 4861, 6.3.4)
4056 			 */
4057 			nd6if->recalctm = nd6_recalc_reachtm_interval;
4058 			nd6if->reachable =
4059 			    ND_COMPUTE_RTIME(nd6if->basereachable);
4060 		}
4061 		lck_mtx_unlock(&nd6if->lock);
4062 	}
4063 	ifnet_head_done();
4064 	timeout(nd6_slowtimo, NULL, ND6_SLOWTIMER_INTERVAL * hz);
4065 }
4066 
4067 int
nd6_output(struct ifnet * ifp,struct ifnet * origifp,struct mbuf * m0,struct sockaddr_in6 * dst,struct rtentry * hint0,struct flowadv * adv)4068 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
4069     struct sockaddr_in6 *dst, struct rtentry *hint0, struct flowadv *adv)
4070 {
4071 	return nd6_output_list(ifp, origifp, m0, dst, hint0, adv);
4072 }
4073 
4074 /*
4075  * nd6_output_list()
4076  *
4077  * Assumption: route determination for first packet can be correctly applied to
4078  * all packets in the chain.
4079  */
4080 #define senderr(e) { error = (e); goto bad; }
4081 int
nd6_output_list(struct ifnet * ifp,struct ifnet * origifp,struct mbuf * m0,struct sockaddr_in6 * dst,struct rtentry * hint0,struct flowadv * adv)4082 nd6_output_list(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
4083     struct sockaddr_in6 *dst, struct rtentry *hint0, struct flowadv *adv)
4084 {
4085 	struct rtentry *rt = hint0, *hint = hint0;
4086 	struct llinfo_nd6 *ln = NULL;
4087 	int error = 0;
4088 	uint64_t timenow;
4089 	struct rtentry *rtrele = NULL;
4090 	struct nd_ifinfo *ndi = NULL;
4091 
4092 	if (rt != NULL) {
4093 		RT_LOCK_SPIN(rt);
4094 		RT_ADDREF_LOCKED(rt);
4095 	}
4096 
4097 	if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr) || !nd6_need_cache(ifp)) {
4098 		if (rt != NULL) {
4099 			RT_UNLOCK(rt);
4100 		}
4101 		goto sendpkt;
4102 	}
4103 
4104 	/*
4105 	 * Next hop determination.  Because we may involve the gateway route
4106 	 * in addition to the original route, locking is rather complicated.
4107 	 * The general concept is that regardless of whether the route points
4108 	 * to the original route or to the gateway route, this routine takes
4109 	 * an extra reference on such a route.  This extra reference will be
4110 	 * released at the end.
4111 	 *
4112 	 * Care must be taken to ensure that the "hint0" route never gets freed
4113 	 * via rtfree(), since the caller may have stored it inside a struct
4114 	 * route with a reference held for that placeholder.
4115 	 *
4116 	 * This logic is similar to, though not exactly the same as the one
4117 	 * used by route_to_gwroute().
4118 	 */
4119 	if (rt != NULL) {
4120 		/*
4121 		 * We have a reference to "rt" by now (or below via rtalloc1),
4122 		 * which will either be released or freed at the end of this
4123 		 * routine.
4124 		 */
4125 		RT_LOCK_ASSERT_HELD(rt);
4126 		if (!(rt->rt_flags & RTF_UP)) {
4127 			RT_REMREF_LOCKED(rt);
4128 			RT_UNLOCK(rt);
4129 			if ((hint = rt = rtalloc1_scoped(SA(dst), 1, 0,
4130 			    ifp->if_index)) != NULL) {
4131 				RT_LOCK_SPIN(rt);
4132 				if (rt->rt_ifp != ifp) {
4133 					/* XXX: loop care? */
4134 					RT_UNLOCK(rt);
4135 					error = nd6_output_list(ifp, origifp, m0,
4136 					    dst, rt, adv);
4137 					rtfree(rt);
4138 					return error;
4139 				}
4140 			} else {
4141 				senderr(EHOSTUNREACH);
4142 			}
4143 		}
4144 
4145 		if (rt->rt_flags & RTF_GATEWAY) {
4146 			struct rtentry *gwrt;
4147 			struct in6_ifaddr *ia6 = NULL;
4148 			struct sockaddr_in6 gw6;
4149 
4150 			rtgw_to_sa6(rt, &gw6);
4151 			/*
4152 			 * Must drop rt_lock since nd6_is_addr_neighbor()
4153 			 * calls nd6_lookup() and acquires rnh_lock.
4154 			 */
4155 			RT_UNLOCK(rt);
4156 
4157 			/*
4158 			 * We skip link-layer address resolution and NUD
4159 			 * if the gateway is not a neighbor from ND point
4160 			 * of view, regardless of the value of nd_ifinfo.flags.
4161 			 * The second condition is a bit tricky; we skip
4162 			 * if the gateway is our own address, which is
4163 			 * sometimes used to install a route to a p2p link.
4164 			 */
4165 			if (!nd6_is_addr_neighbor(&gw6, ifp, 0) ||
4166 			    (ia6 = in6ifa_ifpwithaddr(ifp, &gw6.sin6_addr))) {
4167 				/*
4168 				 * We allow this kind of tricky route only
4169 				 * when the outgoing interface is p2p.
4170 				 * XXX: we may need a more generic rule here.
4171 				 */
4172 				if (ia6 != NULL) {
4173 					IFA_REMREF(&ia6->ia_ifa);
4174 				}
4175 				if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
4176 					senderr(EHOSTUNREACH);
4177 				}
4178 				goto sendpkt;
4179 			}
4180 
4181 			RT_LOCK_SPIN(rt);
4182 			gw6 = *(SIN6(rt->rt_gateway));
4183 
4184 			/* If hint is now down, give up */
4185 			if (!(rt->rt_flags & RTF_UP)) {
4186 				RT_UNLOCK(rt);
4187 				senderr(EHOSTUNREACH);
4188 			}
4189 
4190 			/* If there's no gateway route, look it up */
4191 			if ((gwrt = rt->rt_gwroute) == NULL) {
4192 				RT_UNLOCK(rt);
4193 				goto lookup;
4194 			}
4195 			/* Become a regular mutex */
4196 			RT_CONVERT_LOCK(rt);
4197 
4198 			/*
4199 			 * Take gwrt's lock while holding route's lock;
4200 			 * this is okay since gwrt never points back
4201 			 * to rt, so no lock ordering issues.
4202 			 */
4203 			RT_LOCK_SPIN(gwrt);
4204 			if (!(gwrt->rt_flags & RTF_UP)) {
4205 				rt->rt_gwroute = NULL;
4206 				RT_UNLOCK(gwrt);
4207 				RT_UNLOCK(rt);
4208 				rtfree(gwrt);
4209 lookup:
4210 				lck_mtx_lock(rnh_lock);
4211 				gwrt = rtalloc1_scoped_locked(SA(&gw6), 1, 0,
4212 				    ifp->if_index);
4213 
4214 				RT_LOCK(rt);
4215 				/*
4216 				 * Bail out if the route is down, no route
4217 				 * to gateway, circular route, or if the
4218 				 * gateway portion of "rt" has changed.
4219 				 */
4220 				if (!(rt->rt_flags & RTF_UP) ||
4221 				    gwrt == NULL || gwrt == rt ||
4222 				    !equal(SA(&gw6), rt->rt_gateway)) {
4223 					if (gwrt == rt) {
4224 						RT_REMREF_LOCKED(gwrt);
4225 						gwrt = NULL;
4226 					}
4227 					RT_UNLOCK(rt);
4228 					if (gwrt != NULL) {
4229 						rtfree_locked(gwrt);
4230 					}
4231 					lck_mtx_unlock(rnh_lock);
4232 					senderr(EHOSTUNREACH);
4233 				}
4234 				VERIFY(gwrt != NULL);
4235 				/*
4236 				 * Set gateway route; callee adds ref to gwrt;
4237 				 * gwrt has an extra ref from rtalloc1() for
4238 				 * this routine.
4239 				 */
4240 				rt_set_gwroute(rt, rt_key(rt), gwrt);
4241 				RT_UNLOCK(rt);
4242 				lck_mtx_unlock(rnh_lock);
4243 				/* Remember to release/free "rt" at the end */
4244 				rtrele = rt;
4245 				rt = gwrt;
4246 			} else {
4247 				RT_ADDREF_LOCKED(gwrt);
4248 				RT_UNLOCK(gwrt);
4249 				RT_UNLOCK(rt);
4250 				/* Remember to release/free "rt" at the end */
4251 				rtrele = rt;
4252 				rt = gwrt;
4253 			}
4254 			VERIFY(rt == gwrt);
4255 
4256 			/*
4257 			 * This is an opportunity to revalidate the parent
4258 			 * route's gwroute, in case it now points to a dead
4259 			 * route entry.  Parent route won't go away since the
4260 			 * clone (hint) holds a reference to it.  rt == gwrt.
4261 			 */
4262 			RT_LOCK_SPIN(hint);
4263 			if ((hint->rt_flags & (RTF_WASCLONED | RTF_UP)) ==
4264 			    (RTF_WASCLONED | RTF_UP)) {
4265 				struct rtentry *prt = hint->rt_parent;
4266 				VERIFY(prt != NULL);
4267 
4268 				RT_CONVERT_LOCK(hint);
4269 				RT_ADDREF(prt);
4270 				RT_UNLOCK(hint);
4271 				rt_revalidate_gwroute(prt, rt);
4272 				RT_REMREF(prt);
4273 			} else {
4274 				RT_UNLOCK(hint);
4275 			}
4276 
4277 			RT_LOCK_SPIN(rt);
4278 			/* rt == gwrt; if it is now down, give up */
4279 			if (!(rt->rt_flags & RTF_UP)) {
4280 				RT_UNLOCK(rt);
4281 				rtfree(rt);
4282 				rt = NULL;
4283 				/* "rtrele" == original "rt" */
4284 				senderr(EHOSTUNREACH);
4285 			}
4286 		}
4287 
4288 		/* Become a regular mutex */
4289 		RT_CONVERT_LOCK(rt);
4290 	}
4291 
4292 	/*
4293 	 * Address resolution or Neighbor Unreachability Detection
4294 	 * for the next hop.
4295 	 * At this point, the destination of the packet must be a unicast
4296 	 * or an anycast address(i.e. not a multicast).
4297 	 */
4298 
4299 	/* Look up the neighbor cache for the nexthop */
4300 	if (rt && (rt->rt_flags & RTF_LLINFO) != 0) {
4301 		ln = rt->rt_llinfo;
4302 	} else {
4303 		struct sockaddr_in6 sin6;
4304 		/*
4305 		 * Clear out Scope ID field in case it is set.
4306 		 */
4307 		sin6 = *dst;
4308 		if (in6_embedded_scope) {
4309 			sin6.sin6_scope_id = 0;
4310 		}
4311 		/*
4312 		 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
4313 		 * the condition below is not very efficient.  But we believe
4314 		 * it is tolerable, because this should be a rare case.
4315 		 * Must drop rt_lock since nd6_is_addr_neighbor() calls
4316 		 * nd6_lookup() and acquires rnh_lock.
4317 		 */
4318 		if (rt != NULL) {
4319 			RT_UNLOCK(rt);
4320 		}
4321 		if (nd6_is_addr_neighbor(&sin6, ifp, 0)) {
4322 			/* "rtrele" may have been used, so clean up "rt" now */
4323 			if (rt != NULL) {
4324 				/* Don't free "hint0" */
4325 				if (rt == hint0) {
4326 					RT_REMREF(rt);
4327 				} else {
4328 					rtfree(rt);
4329 				}
4330 			}
4331 			/* Callee returns a locked route upon success */
4332 			rt = nd6_lookup(&dst->sin6_addr, 1, ifp, 0);
4333 			if (rt != NULL) {
4334 				RT_LOCK_ASSERT_HELD(rt);
4335 				ln = rt->rt_llinfo;
4336 			}
4337 		} else if (rt != NULL) {
4338 			RT_LOCK(rt);
4339 		}
4340 	}
4341 
4342 	if (!ln || !rt) {
4343 		if (rt != NULL) {
4344 			RT_UNLOCK(rt);
4345 		}
4346 		ndi = ND_IFINFO(ifp);
4347 		VERIFY(ndi != NULL && ndi->initialized);
4348 		lck_mtx_lock(&ndi->lock);
4349 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
4350 		    !(ndi->flags & ND6_IFF_PERFORMNUD)) {
4351 			lck_mtx_unlock(&ndi->lock);
4352 			log(LOG_DEBUG,
4353 			    "nd6_output: can't allocate llinfo for %s "
4354 			    "(ln=0x%llx, rt=0x%llx)\n",
4355 			    ip6_sprintf(&dst->sin6_addr),
4356 			    (uint64_t)VM_KERNEL_ADDRPERM(ln),
4357 			    (uint64_t)VM_KERNEL_ADDRPERM(rt));
4358 			senderr(EIO);   /* XXX: good error? */
4359 		}
4360 		lck_mtx_unlock(&ndi->lock);
4361 
4362 		goto sendpkt;   /* send anyway */
4363 	}
4364 
4365 	net_update_uptime();
4366 	timenow = net_uptime();
4367 
4368 	/* We don't have to do link-layer address resolution on a p2p link. */
4369 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
4370 	    ln->ln_state < ND6_LLINFO_REACHABLE) {
4371 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);
4372 		ln_setexpire(ln, timenow + nd6_gctimer);
4373 	}
4374 
4375 	/*
4376 	 * The first time we send a packet to a neighbor whose entry is
4377 	 * STALE, we have to change the state to DELAY and a sets a timer to
4378 	 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
4379 	 * neighbor unreachability detection on expiration.
4380 	 * (RFC 4861 7.3.3)
4381 	 */
4382 	if (ln->ln_state == ND6_LLINFO_STALE) {
4383 		ln->ln_asked = 0;
4384 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_DELAY);
4385 		ln_setexpire(ln, timenow + nd6_delay);
4386 		/* N.B.: we will re-arm the timer below. */
4387 		_CASSERT(ND6_LLINFO_DELAY > ND6_LLINFO_INCOMPLETE);
4388 	}
4389 
4390 	/*
4391 	 * If the neighbor cache entry has a state other than INCOMPLETE
4392 	 * (i.e. its link-layer address is already resolved), just
4393 	 * send the packet.
4394 	 */
4395 	if (ln->ln_state > ND6_LLINFO_INCOMPLETE) {
4396 		RT_UNLOCK(rt);
4397 		/*
4398 		 * Move this entry to the head of the queue so that it is
4399 		 * less likely for this entry to be a target of forced
4400 		 * garbage collection (see nd6_rtrequest()).  Do this only
4401 		 * if the entry is non-permanent (as permanent ones will
4402 		 * never be purged), and if the number of active entries
4403 		 * is at least half of the threshold.
4404 		 */
4405 		if (ln->ln_state == ND6_LLINFO_DELAY ||
4406 		    (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4407 		    nd6_inuse >= (ip6_neighborgcthresh >> 1))) {
4408 			lck_mtx_lock(rnh_lock);
4409 			if (ln->ln_state == ND6_LLINFO_DELAY) {
4410 				nd6_sched_timeout(NULL, NULL);
4411 			}
4412 			if (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4413 			    nd6_inuse >= (ip6_neighborgcthresh >> 1)) {
4414 				RT_LOCK_SPIN(rt);
4415 				if (ln->ln_flags & ND6_LNF_IN_USE) {
4416 					LN_DEQUEUE(ln);
4417 					LN_INSERTHEAD(ln);
4418 				}
4419 				RT_UNLOCK(rt);
4420 			}
4421 			lck_mtx_unlock(rnh_lock);
4422 		}
4423 		goto sendpkt;
4424 	}
4425 
4426 	/*
4427 	 * If this is a prefix proxy route, record the inbound interface
4428 	 * so that it can be excluded from the list of interfaces eligible
4429 	 * for forwarding the proxied NS in nd6_prproxy_ns_output().
4430 	 */
4431 	if (rt->rt_flags & RTF_PROXY) {
4432 		ln->ln_exclifp = ((origifp == ifp) ? NULL : origifp);
4433 	}
4434 
4435 	/*
4436 	 * There is a neighbor cache entry, but no ethernet address
4437 	 * response yet.  Replace the held mbuf (if any) with this
4438 	 * latest one.
4439 	 *
4440 	 * This code conforms to the rate-limiting rule described in Section
4441 	 * 7.2.2 of RFC 4861, because the timer is set correctly after sending
4442 	 * an NS below.
4443 	 */
4444 	if (ln->ln_state == ND6_LLINFO_NOSTATE) {
4445 		ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_INCOMPLETE);
4446 	}
4447 	if (ln->ln_hold) {
4448 		m_freem_list(ln->ln_hold);
4449 	}
4450 	ln->ln_hold = m0;
4451 	if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
4452 		ln->ln_asked++;
4453 		ndi = ND_IFINFO(ifp);
4454 		VERIFY(ndi != NULL && ndi->initialized);
4455 		lck_mtx_lock(&ndi->lock);
4456 		ln_setexpire(ln, timenow + ndi->retrans / 1000);
4457 		lck_mtx_unlock(&ndi->lock);
4458 		RT_UNLOCK(rt);
4459 		/* We still have a reference on rt (for ln) */
4460 		if (ip6_forwarding) {
4461 			nd6_prproxy_ns_output(ifp, origifp, NULL,
4462 			    &dst->sin6_addr, ln);
4463 		} else {
4464 			nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, NULL);
4465 		}
4466 		lck_mtx_lock(rnh_lock);
4467 		nd6_sched_timeout(NULL, NULL);
4468 		lck_mtx_unlock(rnh_lock);
4469 	} else {
4470 		RT_UNLOCK(rt);
4471 	}
4472 	/*
4473 	 * Move this entry to the head of the queue so that it is
4474 	 * less likely for this entry to be a target of forced
4475 	 * garbage collection (see nd6_rtrequest()).  Do this only
4476 	 * if the entry is non-permanent (as permanent ones will
4477 	 * never be purged), and if the number of active entries
4478 	 * is at least half of the threshold.
4479 	 */
4480 	if (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4481 	    nd6_inuse >= (ip6_neighborgcthresh >> 1)) {
4482 		lck_mtx_lock(rnh_lock);
4483 		RT_LOCK_SPIN(rt);
4484 		if (ln->ln_flags & ND6_LNF_IN_USE) {
4485 			LN_DEQUEUE(ln);
4486 			LN_INSERTHEAD(ln);
4487 		}
4488 		/* Clean up "rt" now while we can */
4489 		if (rt == hint0) {
4490 			RT_REMREF_LOCKED(rt);
4491 			RT_UNLOCK(rt);
4492 		} else {
4493 			RT_UNLOCK(rt);
4494 			rtfree_locked(rt);
4495 		}
4496 		rt = NULL;      /* "rt" has been taken care of */
4497 		lck_mtx_unlock(rnh_lock);
4498 	}
4499 	error = 0;
4500 	goto release;
4501 
4502 sendpkt:
4503 	if (rt != NULL) {
4504 		RT_LOCK_ASSERT_NOTHELD(rt);
4505 	}
4506 
4507 	/* discard the packet if IPv6 operation is disabled on the interface */
4508 	if (ifp->if_eflags & IFEF_IPV6_DISABLED) {
4509 		error = ENETDOWN; /* better error? */
4510 		goto bad;
4511 	}
4512 
4513 	if (ifp->if_flags & IFF_LOOPBACK) {
4514 		/* forwarding rules require the original scope_id */
4515 		m0->m_pkthdr.rcvif = origifp;
4516 		error = dlil_output(origifp, PF_INET6, m0, (caddr_t)rt,
4517 		    SA(dst), 0, adv);
4518 		goto release;
4519 	} else {
4520 		/* Do not allow loopback address to wind up on a wire */
4521 		struct ip6_hdr *ip6 = mtod(m0, struct ip6_hdr *);
4522 
4523 		if ((IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) ||
4524 		    IN6_IS_ADDR_LOOPBACK(&ip6->ip6_dst))) {
4525 			ip6stat.ip6s_badscope++;
4526 			error = EADDRNOTAVAIL;
4527 			goto bad;
4528 		}
4529 	}
4530 
4531 	if (rt != NULL) {
4532 		RT_LOCK_SPIN(rt);
4533 		/* Mark use timestamp */
4534 		if (rt->rt_llinfo != NULL) {
4535 			nd6_llreach_use(rt->rt_llinfo);
4536 		}
4537 		RT_UNLOCK(rt);
4538 	}
4539 
4540 	struct mbuf *mcur = m0;
4541 	uint32_t pktcnt = 0;
4542 
4543 	while (mcur) {
4544 		if (hint != NULL && nstat_collect) {
4545 			int scnt;
4546 
4547 			if ((mcur->m_pkthdr.csum_flags & CSUM_TSO_IPV6) &&
4548 			    (mcur->m_pkthdr.tso_segsz > 0)) {
4549 				scnt = mcur->m_pkthdr.len / mcur->m_pkthdr.tso_segsz;
4550 			} else {
4551 				scnt = 1;
4552 			}
4553 
4554 			nstat_route_tx(hint, scnt, mcur->m_pkthdr.len, 0);
4555 		}
4556 		pktcnt++;
4557 
4558 		mcur->m_pkthdr.rcvif = NULL;
4559 		mcur = mcur->m_nextpkt;
4560 	}
4561 	if (pktcnt > ip6_maxchainsent) {
4562 		ip6_maxchainsent = pktcnt;
4563 	}
4564 	error = dlil_output(ifp, PF_INET6, m0, (caddr_t)rt, SA(dst), 0, adv);
4565 	goto release;
4566 
4567 bad:
4568 	if (m0 != NULL) {
4569 		m_freem_list(m0);
4570 	}
4571 
4572 release:
4573 	/* Clean up "rt" unless it's already been done */
4574 	if (rt != NULL) {
4575 		RT_LOCK_SPIN(rt);
4576 		if (rt == hint0) {
4577 			RT_REMREF_LOCKED(rt);
4578 			RT_UNLOCK(rt);
4579 		} else {
4580 			RT_UNLOCK(rt);
4581 			rtfree(rt);
4582 		}
4583 	}
4584 	/* And now clean up "rtrele" if there is any */
4585 	if (rtrele != NULL) {
4586 		RT_LOCK_SPIN(rtrele);
4587 		if (rtrele == hint0) {
4588 			RT_REMREF_LOCKED(rtrele);
4589 			RT_UNLOCK(rtrele);
4590 		} else {
4591 			RT_UNLOCK(rtrele);
4592 			rtfree(rtrele);
4593 		}
4594 	}
4595 	return error;
4596 }
4597 #undef senderr
4598 
4599 int
nd6_need_cache(struct ifnet * ifp)4600 nd6_need_cache(struct ifnet *ifp)
4601 {
4602 	/*
4603 	 * XXX: we currently do not make neighbor cache on any interface
4604 	 * other than ARCnet, Ethernet, FDDI and GIF.
4605 	 *
4606 	 * RFC2893 says:
4607 	 * - unidirectional tunnels needs no ND
4608 	 */
4609 	switch (ifp->if_type) {
4610 	case IFT_ARCNET:
4611 	case IFT_ETHER:
4612 	case IFT_FDDI:
4613 	case IFT_IEEE1394:
4614 	case IFT_L2VLAN:
4615 	case IFT_IEEE8023ADLAG:
4616 #if IFT_IEEE80211
4617 	case IFT_IEEE80211:
4618 #endif
4619 	case IFT_GIF:           /* XXX need more cases? */
4620 	case IFT_PPP:
4621 #if IFT_TUNNEL
4622 	case IFT_TUNNEL:
4623 #endif
4624 	case IFT_BRIDGE:
4625 	case IFT_CELLULAR:
4626 		return 1;
4627 	default:
4628 		return 0;
4629 	}
4630 }
4631 
4632 int
nd6_storelladdr(struct ifnet * ifp,struct rtentry * rt,struct mbuf * m,struct sockaddr * dst,u_char * desten)4633 nd6_storelladdr(struct ifnet *ifp, struct rtentry *rt, struct mbuf *m,
4634     struct sockaddr *dst, u_char *desten)
4635 {
4636 	int i;
4637 	struct sockaddr_dl *sdl;
4638 
4639 	if (m->m_flags & M_MCAST) {
4640 		switch (ifp->if_type) {
4641 		case IFT_ETHER:
4642 		case IFT_FDDI:
4643 		case IFT_L2VLAN:
4644 		case IFT_IEEE8023ADLAG:
4645 #if IFT_IEEE80211
4646 		case IFT_IEEE80211:
4647 #endif
4648 		case IFT_BRIDGE:
4649 			ETHER_MAP_IPV6_MULTICAST(&SIN6(dst)->sin6_addr, desten);
4650 			return 1;
4651 		case IFT_IEEE1394:
4652 			for (i = 0; i < ifp->if_addrlen; i++) {
4653 				desten[i] = ~0;
4654 			}
4655 			return 1;
4656 		case IFT_ARCNET:
4657 			*desten = 0;
4658 			return 1;
4659 		default:
4660 			return 0; /* caller will free mbuf */
4661 		}
4662 	}
4663 
4664 	if (rt == NULL) {
4665 		/* this could happen, if we could not allocate memory */
4666 		return 0; /* caller will free mbuf */
4667 	}
4668 	RT_LOCK(rt);
4669 	if (rt->rt_gateway->sa_family != AF_LINK) {
4670 		printf("nd6_storelladdr: something odd happens\n");
4671 		RT_UNLOCK(rt);
4672 		return 0; /* caller will free mbuf */
4673 	}
4674 	sdl = SDL(rt->rt_gateway);
4675 	if (sdl->sdl_alen == 0) {
4676 		/* this should be impossible, but we bark here for debugging */
4677 		printf("nd6_storelladdr: sdl_alen == 0\n");
4678 		RT_UNLOCK(rt);
4679 		return 0; /* caller will free mbuf */
4680 	}
4681 
4682 	bcopy(LLADDR(sdl), desten, sdl->sdl_alen);
4683 	RT_UNLOCK(rt);
4684 	return 1;
4685 }
4686 
4687 /*
4688  * This is the ND pre-output routine; care must be taken to ensure that
4689  * the "hint" route never gets freed via rtfree(), since the caller may
4690  * have stored it inside a struct route with a reference held for that
4691  * placeholder.
4692  */
4693 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)4694 nd6_lookup_ipv6(ifnet_t  ifp, const struct sockaddr_in6 *ip6_dest,
4695     struct sockaddr_dl *ll_dest, size_t ll_dest_len, route_t hint,
4696     mbuf_t packet)
4697 {
4698 	route_t route = hint;
4699 	errno_t result = 0;
4700 	struct sockaddr_dl *sdl = NULL;
4701 	size_t  copy_len;
4702 
4703 	if (ifp == NULL || ip6_dest == NULL) {
4704 		return EINVAL;
4705 	}
4706 
4707 	if (ip6_dest->sin6_family != AF_INET6) {
4708 		return EAFNOSUPPORT;
4709 	}
4710 
4711 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING)) {
4712 		return ENETDOWN;
4713 	}
4714 
4715 	if (hint != NULL) {
4716 		/*
4717 		 * Callee holds a reference on the route and returns
4718 		 * with the route entry locked, upon success.
4719 		 */
4720 		result = route_to_gwroute((const struct sockaddr *)ip6_dest,
4721 		    hint, &route);
4722 		if (result != 0) {
4723 			return result;
4724 		}
4725 		if (route != NULL) {
4726 			RT_LOCK_ASSERT_HELD(route);
4727 		}
4728 	}
4729 
4730 	if ((packet != NULL && (packet->m_flags & M_MCAST) != 0) ||
4731 	    ((ifp->if_flags & IFF_MULTICAST) &&
4732 	    IN6_IS_ADDR_MULTICAST(&ip6_dest->sin6_addr))) {
4733 		if (route != NULL) {
4734 			RT_UNLOCK(route);
4735 		}
4736 		result = dlil_resolve_multi(ifp,
4737 		    (const struct sockaddr *)ip6_dest,
4738 		    SA(ll_dest), ll_dest_len);
4739 		if (route != NULL) {
4740 			RT_LOCK(route);
4741 		}
4742 		goto release;
4743 	} else if (route == NULL) {
4744 		/*
4745 		 * rdar://24596652
4746 		 * For unicast, lookup existing ND6 entries but
4747 		 * do not trigger a resolution
4748 		 */
4749 		lck_mtx_lock(rnh_lock);
4750 		route = rt_lookup(TRUE,
4751 		    __DECONST(struct sockaddr *, ip6_dest), NULL,
4752 		    rt_tables[AF_INET6], ifp->if_index);
4753 		lck_mtx_unlock(rnh_lock);
4754 
4755 		if (route != NULL) {
4756 			RT_LOCK(route);
4757 		}
4758 	}
4759 
4760 	if (route == NULL) {
4761 		/*
4762 		 * This could happen, if we could not allocate memory or
4763 		 * if route_to_gwroute() didn't return a route.
4764 		 */
4765 		result = ENOBUFS;
4766 		goto release;
4767 	}
4768 
4769 	if (route->rt_gateway->sa_family != AF_LINK) {
4770 		nd6log0(error, "%s: route %s on %s%d gateway address not AF_LINK\n",
4771 		    __func__, ip6_sprintf(&ip6_dest->sin6_addr),
4772 		    route->rt_ifp->if_name, route->rt_ifp->if_unit);
4773 		result = EADDRNOTAVAIL;
4774 		goto release;
4775 	}
4776 
4777 	sdl = SDL(route->rt_gateway);
4778 	if (sdl->sdl_alen == 0) {
4779 		/* this should be impossible, but we bark here for debugging */
4780 		nd6log(error, "%s: route %s on %s%d sdl_alen == 0\n", __func__,
4781 		    ip6_sprintf(&ip6_dest->sin6_addr), route->rt_ifp->if_name,
4782 		    route->rt_ifp->if_unit);
4783 		result = EHOSTUNREACH;
4784 		goto release;
4785 	}
4786 
4787 	copy_len = sdl->sdl_len <= ll_dest_len ? sdl->sdl_len : ll_dest_len;
4788 	bcopy(sdl, ll_dest, copy_len);
4789 
4790 release:
4791 	if (route != NULL) {
4792 		if (route == hint) {
4793 			RT_REMREF_LOCKED(route);
4794 			RT_UNLOCK(route);
4795 		} else {
4796 			RT_UNLOCK(route);
4797 			rtfree(route);
4798 		}
4799 	}
4800 	return result;
4801 }
4802 
4803 #if (DEVELOPMENT || DEBUG)
4804 
4805 static int sysctl_nd6_lookup_ipv6 SYSCTL_HANDLER_ARGS;
4806 SYSCTL_PROC(_net_inet6_icmp6, OID_AUTO, nd6_lookup_ipv6,
4807     CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_LOCKED, 0, 0,
4808     sysctl_nd6_lookup_ipv6, "S", "");
4809 
4810 int
4811 sysctl_nd6_lookup_ipv6 SYSCTL_HANDLER_ARGS
4812 {
4813 #pragma unused(oidp, arg1, arg2)
4814 	int error = 0;
4815 	struct nd6_lookup_ipv6_args nd6_lookup_ipv6_args;
4816 	ifnet_t ifp = NULL;
4817 
4818 	/*
4819 	 * Only root can lookup MAC addresses
4820 	 */
4821 	error = proc_suser(current_proc());
4822 	if (error != 0) {
4823 		nd6log0(error, "%s: proc_suser() error %d\n",
4824 		    __func__, error);
4825 		goto done;
4826 	}
4827 	if (req->oldptr == USER_ADDR_NULL) {
4828 		req->oldidx = sizeof(struct nd6_lookup_ipv6_args);
4829 	}
4830 	if (req->newptr == USER_ADDR_NULL) {
4831 		goto done;
4832 	}
4833 	if (req->oldlen != sizeof(struct nd6_lookup_ipv6_args) ||
4834 	    req->newlen != sizeof(struct nd6_lookup_ipv6_args)) {
4835 		error = EINVAL;
4836 		nd6log0(error, "%s: bad req, error %d\n",
4837 		    __func__, error);
4838 		goto done;
4839 	}
4840 	error = SYSCTL_IN(req, &nd6_lookup_ipv6_args,
4841 	    sizeof(struct nd6_lookup_ipv6_args));
4842 	if (error != 0) {
4843 		nd6log0(error, "%s: SYSCTL_IN() error %d\n",
4844 		    __func__, error);
4845 		goto done;
4846 	}
4847 
4848 	if (nd6_lookup_ipv6_args.ll_dest_len > sizeof(nd6_lookup_ipv6_args.ll_dest_)) {
4849 		error = EINVAL;
4850 		nd6log0(error, "%s: bad ll_dest_len, error %d\n",
4851 		    __func__, error);
4852 		goto done;
4853 	}
4854 
4855 	/* Make sure to terminate the string */
4856 	nd6_lookup_ipv6_args.ifname[IFNAMSIZ - 1] = 0;
4857 
4858 	error = ifnet_find_by_name(nd6_lookup_ipv6_args.ifname, &ifp);
4859 	if (error != 0) {
4860 		nd6log0(error, "%s: ifnet_find_by_name() error %d\n",
4861 		    __func__, error);
4862 		goto done;
4863 	}
4864 
4865 	error = nd6_lookup_ipv6(ifp, &nd6_lookup_ipv6_args.ip6_dest,
4866 	    &nd6_lookup_ipv6_args.ll_dest_._sdl,
4867 	    nd6_lookup_ipv6_args.ll_dest_len, NULL, NULL);
4868 	if (error != 0) {
4869 		nd6log0(error, "%s: nd6_lookup_ipv6() error %d\n",
4870 		    __func__, error);
4871 		goto done;
4872 	}
4873 
4874 	error = SYSCTL_OUT(req, &nd6_lookup_ipv6_args,
4875 	    sizeof(struct nd6_lookup_ipv6_args));
4876 	if (error != 0) {
4877 		nd6log0(error, "%s: SYSCTL_OUT() error %d\n",
4878 		    __func__, error);
4879 		goto done;
4880 	}
4881 done:
4882 	return error;
4883 }
4884 
4885 #endif /* (DEVELOPEMENT || DEBUG) */
4886 
4887 int
nd6_setifinfo(struct ifnet * ifp,u_int32_t before,u_int32_t after)4888 nd6_setifinfo(struct ifnet *ifp, u_int32_t before, u_int32_t after)
4889 {
4890 	uint32_t b, a;
4891 	int err = 0;
4892 
4893 	/*
4894 	 * Handle ND6_IFF_IFDISABLED
4895 	 */
4896 	if ((before & ND6_IFF_IFDISABLED) ||
4897 	    (after & ND6_IFF_IFDISABLED)) {
4898 		b = (before & ND6_IFF_IFDISABLED);
4899 		a = (after & ND6_IFF_IFDISABLED);
4900 
4901 		if (b != a && (err = nd6_if_disable(ifp,
4902 		    ((int32_t)(a - b) > 0))) != 0) {
4903 			goto done;
4904 		}
4905 	}
4906 
4907 	/*
4908 	 * Handle ND6_IFF_PROXY_PREFIXES
4909 	 */
4910 	if ((before & ND6_IFF_PROXY_PREFIXES) ||
4911 	    (after & ND6_IFF_PROXY_PREFIXES)) {
4912 		b = (before & ND6_IFF_PROXY_PREFIXES);
4913 		a = (after & ND6_IFF_PROXY_PREFIXES);
4914 
4915 		if (b != a && (err = nd6_if_prproxy(ifp,
4916 		    ((int32_t)(a - b) > 0))) != 0) {
4917 			goto done;
4918 		}
4919 	}
4920 done:
4921 	return err;
4922 }
4923 
4924 /*
4925  * Enable/disable IPv6 on an interface, called as part of
4926  * setting/clearing ND6_IFF_IFDISABLED, or during DAD failure.
4927  */
4928 int
nd6_if_disable(struct ifnet * ifp,boolean_t enable)4929 nd6_if_disable(struct ifnet *ifp, boolean_t enable)
4930 {
4931 	if (enable) {
4932 		if_set_eflags(ifp, IFEF_IPV6_DISABLED);
4933 	} else {
4934 		if_clear_eflags(ifp, IFEF_IPV6_DISABLED);
4935 	}
4936 
4937 	return 0;
4938 }
4939 
4940 static int
4941 nd6_sysctl_drlist SYSCTL_HANDLER_ARGS
4942 {
4943 #pragma unused(oidp, arg1, arg2)
4944 	char pbuf[MAX_IPv6_STR_LEN];
4945 	struct nd_defrouter *dr;
4946 	int error = 0;
4947 
4948 	if (req->newptr != USER_ADDR_NULL) {
4949 		return EPERM;
4950 	}
4951 
4952 	/* XXX Handle mapped defrouter entries */
4953 	lck_mtx_lock(nd6_mutex);
4954 	if (proc_is64bit(req->p)) {
4955 		struct in6_defrouter_64 d;
4956 
4957 		bzero(&d, sizeof(d));
4958 		d.rtaddr.sin6_family = AF_INET6;
4959 		d.rtaddr.sin6_len = sizeof(d.rtaddr);
4960 
4961 		TAILQ_FOREACH(dr, &nd_defrouter_list, dr_entry) {
4962 			d.rtaddr.sin6_addr = dr->rtaddr;
4963 			if (in6_recoverscope(&d.rtaddr,
4964 			    &dr->rtaddr, dr->ifp) != 0) {
4965 				log(LOG_ERR, "scope error in default router "
4966 				    "list (%s)\n", inet_ntop(AF_INET6,
4967 				    &dr->rtaddr, pbuf, sizeof(pbuf)));
4968 			}
4969 			d.flags = dr->flags;
4970 			d.stateflags = dr->stateflags;
4971 			d.rtlifetime = (u_short)dr->rtlifetime;
4972 			d.expire = (int)nddr_getexpire(dr);
4973 			d.if_index = dr->ifp->if_index;
4974 			error = SYSCTL_OUT(req, &d, sizeof(d));
4975 			if (error != 0) {
4976 				break;
4977 			}
4978 		}
4979 	} else {
4980 		struct in6_defrouter_32 d;
4981 
4982 		bzero(&d, sizeof(d));
4983 		d.rtaddr.sin6_family = AF_INET6;
4984 		d.rtaddr.sin6_len = sizeof(d.rtaddr);
4985 
4986 		TAILQ_FOREACH(dr, &nd_defrouter_list, dr_entry) {
4987 			d.rtaddr.sin6_addr = dr->rtaddr;
4988 			if (in6_recoverscope(&d.rtaddr,
4989 			    &dr->rtaddr, dr->ifp) != 0) {
4990 				log(LOG_ERR, "scope error in default router "
4991 				    "list (%s)\n", inet_ntop(AF_INET6,
4992 				    &dr->rtaddr, pbuf, sizeof(pbuf)));
4993 			}
4994 			d.flags = dr->flags;
4995 			d.stateflags = dr->stateflags;
4996 			d.rtlifetime = (u_short)dr->rtlifetime;
4997 			d.expire = (int)nddr_getexpire(dr);
4998 			d.if_index = dr->ifp->if_index;
4999 			error = SYSCTL_OUT(req, &d, sizeof(d));
5000 			if (error != 0) {
5001 				break;
5002 			}
5003 		}
5004 	}
5005 	lck_mtx_unlock(nd6_mutex);
5006 	return error;
5007 }
5008 
5009 static int
5010 nd6_sysctl_prlist SYSCTL_HANDLER_ARGS
5011 {
5012 #pragma unused(oidp, arg1, arg2)
5013 	char pbuf[MAX_IPv6_STR_LEN];
5014 	struct nd_pfxrouter *pfr;
5015 	struct sockaddr_in6 s6;
5016 	struct nd_prefix *pr;
5017 	int error = 0;
5018 
5019 	if (req->newptr != USER_ADDR_NULL) {
5020 		return EPERM;
5021 	}
5022 
5023 	bzero(&s6, sizeof(s6));
5024 	s6.sin6_family = AF_INET6;
5025 	s6.sin6_len = sizeof(s6);
5026 
5027 	/* XXX Handle mapped defrouter entries */
5028 	lck_mtx_lock(nd6_mutex);
5029 	if (proc_is64bit(req->p)) {
5030 		struct in6_prefix_64 p;
5031 
5032 		bzero(&p, sizeof(p));
5033 		p.origin = PR_ORIG_RA;
5034 
5035 		LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
5036 			NDPR_LOCK(pr);
5037 			p.prefix = pr->ndpr_prefix;
5038 			if (in6_recoverscope(&p.prefix,
5039 			    &pr->ndpr_prefix.sin6_addr, pr->ndpr_ifp) != 0) {
5040 				log(LOG_ERR, "scope error in "
5041 				    "prefix list (%s)\n", inet_ntop(AF_INET6,
5042 				    &p.prefix.sin6_addr, pbuf, sizeof(pbuf)));
5043 			}
5044 			p.raflags = pr->ndpr_raf;
5045 			p.prefixlen = pr->ndpr_plen;
5046 			p.vltime = pr->ndpr_vltime;
5047 			p.pltime = pr->ndpr_pltime;
5048 			p.if_index = pr->ndpr_ifp->if_index;
5049 			p.expire = (u_long)ndpr_getexpire(pr);
5050 			p.refcnt = pr->ndpr_addrcnt;
5051 			p.flags = pr->ndpr_stateflags;
5052 			p.advrtrs = 0;
5053 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
5054 			p.advrtrs++;
5055 			error = SYSCTL_OUT(req, &p, sizeof(p));
5056 			if (error != 0) {
5057 				NDPR_UNLOCK(pr);
5058 				break;
5059 			}
5060 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
5061 				s6.sin6_addr = pfr->router->rtaddr;
5062 				if (in6_recoverscope(&s6, &pfr->router->rtaddr,
5063 				    pfr->router->ifp) != 0) {
5064 					log(LOG_ERR,
5065 					    "scope error in prefix list (%s)\n",
5066 					    inet_ntop(AF_INET6, &s6.sin6_addr,
5067 					    pbuf, sizeof(pbuf)));
5068 				}
5069 				error = SYSCTL_OUT(req, &s6, sizeof(s6));
5070 				if (error != 0) {
5071 					break;
5072 				}
5073 			}
5074 			NDPR_UNLOCK(pr);
5075 			if (error != 0) {
5076 				break;
5077 			}
5078 		}
5079 	} else {
5080 		struct in6_prefix_32 p;
5081 
5082 		bzero(&p, sizeof(p));
5083 		p.origin = PR_ORIG_RA;
5084 
5085 		LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
5086 			NDPR_LOCK(pr);
5087 			p.prefix = pr->ndpr_prefix;
5088 			if (in6_recoverscope(&p.prefix,
5089 			    &pr->ndpr_prefix.sin6_addr, pr->ndpr_ifp) != 0) {
5090 				log(LOG_ERR,
5091 				    "scope error in prefix list (%s)\n",
5092 				    inet_ntop(AF_INET6, &p.prefix.sin6_addr,
5093 				    pbuf, sizeof(pbuf)));
5094 			}
5095 			p.raflags = pr->ndpr_raf;
5096 			p.prefixlen = pr->ndpr_plen;
5097 			p.vltime = pr->ndpr_vltime;
5098 			p.pltime = pr->ndpr_pltime;
5099 			p.if_index = pr->ndpr_ifp->if_index;
5100 			p.expire = (u_int32_t)ndpr_getexpire(pr);
5101 			p.refcnt = pr->ndpr_addrcnt;
5102 			p.flags = pr->ndpr_stateflags;
5103 			p.advrtrs = 0;
5104 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
5105 			p.advrtrs++;
5106 			error = SYSCTL_OUT(req, &p, sizeof(p));
5107 			if (error != 0) {
5108 				NDPR_UNLOCK(pr);
5109 				break;
5110 			}
5111 			LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
5112 				s6.sin6_addr = pfr->router->rtaddr;
5113 				if (in6_recoverscope(&s6, &pfr->router->rtaddr,
5114 				    pfr->router->ifp) != 0) {
5115 					log(LOG_ERR,
5116 					    "scope error in prefix list (%s)\n",
5117 					    inet_ntop(AF_INET6, &s6.sin6_addr,
5118 					    pbuf, sizeof(pbuf)));
5119 				}
5120 				error = SYSCTL_OUT(req, &s6, sizeof(s6));
5121 				if (error != 0) {
5122 					break;
5123 				}
5124 			}
5125 			NDPR_UNLOCK(pr);
5126 			if (error != 0) {
5127 				break;
5128 			}
5129 		}
5130 	}
5131 	lck_mtx_unlock(nd6_mutex);
5132 
5133 	return error;
5134 }
5135 
5136 void
in6_ifaddr_set_dadprogress(struct in6_ifaddr * ia)5137 in6_ifaddr_set_dadprogress(struct in6_ifaddr *ia)
5138 {
5139 	struct ifnet* ifp = ia->ia_ifp;
5140 	uint32_t flags = IN6_IFF_TENTATIVE;
5141 	uint32_t optdad = nd6_optimistic_dad;
5142 	struct nd_ifinfo *ndi = NULL;
5143 
5144 	ndi = ND_IFINFO(ifp);
5145 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
5146 	if (!(ndi->flags & ND6_IFF_DAD)) {
5147 		return;
5148 	}
5149 
5150 	if (optdad) {
5151 		if (ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
5152 			optdad = 0;
5153 		} else {
5154 			lck_mtx_lock(&ndi->lock);
5155 			if ((ndi->flags & ND6_IFF_REPLICATED) != 0) {
5156 				optdad = 0;
5157 			}
5158 			lck_mtx_unlock(&ndi->lock);
5159 		}
5160 	}
5161 
5162 	if (optdad) {
5163 		if ((optdad & ND6_OPTIMISTIC_DAD_LINKLOCAL) &&
5164 		    IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr)) {
5165 			flags = IN6_IFF_OPTIMISTIC;
5166 		} else if ((optdad & ND6_OPTIMISTIC_DAD_AUTOCONF) &&
5167 		    (ia->ia6_flags & IN6_IFF_AUTOCONF)) {
5168 			if (ia->ia6_flags & IN6_IFF_TEMPORARY) {
5169 				if (optdad & ND6_OPTIMISTIC_DAD_TEMPORARY) {
5170 					flags = IN6_IFF_OPTIMISTIC;
5171 				}
5172 			} else if (ia->ia6_flags & IN6_IFF_SECURED) {
5173 				if (optdad & ND6_OPTIMISTIC_DAD_SECURED) {
5174 					flags = IN6_IFF_OPTIMISTIC;
5175 				}
5176 			} else {
5177 				/*
5178 				 * Keeping the behavior for temp and CGA
5179 				 * SLAAC addresses to have a knob for optimistic
5180 				 * DAD.
5181 				 * Other than that if ND6_OPTIMISTIC_DAD_AUTOCONF
5182 				 * is set, we should default to optimistic
5183 				 * DAD.
5184 				 * For now this means SLAAC addresses with interface
5185 				 * identifier derived from modified EUI-64 bit
5186 				 * identifiers.
5187 				 */
5188 				flags = IN6_IFF_OPTIMISTIC;
5189 			}
5190 		} else if ((optdad & ND6_OPTIMISTIC_DAD_DYNAMIC) &&
5191 		    (ia->ia6_flags & IN6_IFF_DYNAMIC)) {
5192 			if (ia->ia6_flags & IN6_IFF_TEMPORARY) {
5193 				if (optdad & ND6_OPTIMISTIC_DAD_TEMPORARY) {
5194 					flags = IN6_IFF_OPTIMISTIC;
5195 				}
5196 			} else {
5197 				flags = IN6_IFF_OPTIMISTIC;
5198 			}
5199 		} else if ((optdad & ND6_OPTIMISTIC_DAD_MANUAL) &&
5200 		    (ia->ia6_flags & IN6_IFF_OPTIMISTIC)) {
5201 			/*
5202 			 * rdar://17483438
5203 			 * Bypass tentative for address assignments
5204 			 * not covered above (e.g. manual) upon request
5205 			 */
5206 			if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr) &&
5207 			    !(ia->ia6_flags & IN6_IFF_AUTOCONF) &&
5208 			    !(ia->ia6_flags & IN6_IFF_DYNAMIC)) {
5209 				flags = IN6_IFF_OPTIMISTIC;
5210 			}
5211 		}
5212 	}
5213 
5214 	ia->ia6_flags &= ~(IN6_IFF_DUPLICATED | IN6_IFF_DADPROGRESS);
5215 	ia->ia6_flags |= flags;
5216 
5217 	nd6log2(debug, "%s - %s ifp %s ia6_flags 0x%x\n",
5218 	    __func__,
5219 	    ip6_sprintf(&ia->ia_addr.sin6_addr),
5220 	    if_name(ia->ia_ifp),
5221 	    ia->ia6_flags);
5222 }
5223