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