2 * Copyright (c) 2000-2011 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1980, 1986, 1991, 1993
30 * The Regents of the University of California. All rights reserved.
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * @(#)route.c 8.2 (Berkeley) 11/15/93
61 * $FreeBSD: src/sys/net/route.c,v 1.59.2.3 2001/07/29 19:18:02 ume Exp $
64 #include <sys/param.h>
65 #include <sys/sysctl.h>
66 #include <sys/systm.h>
67 #include <sys/malloc.h>
69 #include <sys/socket.h>
70 #include <sys/domain.h>
71 #include <sys/syslog.h>
72 #include <sys/queue.h>
73 #include <sys/mcache.h>
74 #include <sys/protosw.h>
75 #include <kern/lock.h>
76 #include <kern/zalloc.h>
79 #include <net/route.h>
80 #include <net/ntstat.h>
82 #include <netinet/in.h>
83 #include <netinet/in_var.h>
84 #include <netinet/ip_mroute.h>
85 #include <netinet/ip_var.h>
86 #include <netinet/ip6.h>
89 #include <netinet6/ip6_var.h>
90 #include <netinet6/in6_var.h>
93 #include <net/if_dl.h>
95 #include <libkern/OSAtomic.h>
96 #include <libkern/OSDebug.h>
98 #include <pexpert/pexpert.h>
101 * Synchronization notes:
103 * Routing entries fall under two locking domains: the global routing table
104 * lock (rnh_lock) and the per-entry lock (rt_lock); the latter is a mutex that
105 * resides (statically defined) in the rtentry structure.
107 * The locking domains for routing are defined as follows:
109 * The global routing lock is used to serialize all accesses to the radix
110 * trees defined by rt_tables[], as well as the tree of masks. This includes
111 * lookups, insertions and removals of nodes to/from the respective tree.
112 * It is also used to protect certain fields in the route entry that aren't
113 * often modified and/or require global serialization (more details below.)
115 * The per-route entry lock is used to serialize accesses to several routing
116 * entry fields (more details below.) Acquiring and releasing this lock is
117 * done via RT_LOCK() and RT_UNLOCK() routines.
119 * In cases where both rnh_lock and rt_lock must be held, the former must be
120 * acquired first in order to maintain lock ordering. It is not a requirement
121 * that rnh_lock be acquired first before rt_lock, but in case both must be
122 * acquired in succession, the correct lock ordering must be followed.
124 * The fields of the rtentry structure are protected in the following way:
128 * - Routing table lock (rnh_lock).
130 * rt_parent, rt_mask, rt_llinfo_free
132 * - Set once during creation and never changes; no locks to read.
134 * rt_flags, rt_genmask, rt_llinfo, rt_rmx, rt_refcnt, rt_gwroute
136 * - Routing entry lock (rt_lock) for read/write access.
138 * - Some values of rt_flags are either set once at creation time,
139 * or aren't currently used, and thus checking against them can
140 * be done without rt_lock: RTF_GATEWAY, RTF_HOST, RTF_DYNAMIC,
141 * RTF_DONE, RTF_XRESOLVE, RTF_STATIC, RTF_BLACKHOLE, RTF_ANNOUNCE,
142 * RTF_USETRAILERS, RTF_WASCLONED, RTF_PINNED, RTF_LOCAL,
143 * RTF_BROADCAST, RTF_MULTICAST, RTF_IFSCOPE, RTF_IFREF.
145 * rt_key, rt_gateway, rt_ifp, rt_ifa
147 * - Always written/modified with both rnh_lock and rt_lock held.
149 * - May be read freely with rnh_lock held, else must hold rt_lock
150 * for read access; holding both locks for read is also okay.
152 * - In the event rnh_lock is not acquired, or is not possible to be
153 * acquired across the operation, setting RTF_CONDEMNED on a route
154 * entry will prevent its rt_key, rt_gateway, rt_ifp and rt_ifa
155 * from being modified. This is typically done on a route that
156 * has been chosen for a removal (from the tree) prior to dropping
157 * the rt_lock, so that those values will remain the same until
158 * the route is freed.
160 * When rnh_lock is held rt_setgate(), rt_setif(), and rtsetifa() are
161 * single-threaded, thus exclusive. This flag will also prevent the
162 * route from being looked up via rt_lookup().
166 * - Assumes that 32-bit writes are atomic; no locks.
170 * - Currently unused; no locks.
172 * Operations on a route entry can be described as follows:
174 * CREATE an entry with reference count set to 0 as part of RTM_ADD/RESOLVE.
176 * INSERTION of an entry into the radix tree holds the rnh_lock, checks
177 * for duplicates and then adds the entry. rtrequest returns the entry
178 * after bumping up the reference count to 1 (for the caller).
180 * LOOKUP of an entry holds the rnh_lock and bumps up the reference count
181 * before returning; it is valid to also bump up the reference count using
182 * RT_ADDREF after the lookup has returned an entry.
184 * REMOVAL of an entry from the radix tree holds the rnh_lock, removes the
185 * entry but does not decrement the reference count. Removal happens when
186 * the route is explicitly deleted (RTM_DELETE) or when it is in the cached
187 * state and it expires. The route is said to be "down" when it is no
188 * longer present in the tree. Freeing the entry will happen on the last
189 * reference release of such a "down" route.
191 * RT_ADDREF/RT_REMREF operates on the routing entry which increments/
192 * decrements the reference count, rt_refcnt, atomically on the rtentry.
193 * rt_refcnt is modified only using this routine. The general rule is to
194 * do RT_ADDREF in the function that is passing the entry as an argument,
195 * in order to prevent the entry from being freed by the callee.
198 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
200 extern void kdp_set_gateway_mac (void *gatewaymac
);
202 extern struct domain routedomain
;
203 struct route_cb route_cb
;
204 __private_extern__
struct rtstat rtstat
= { 0, 0, 0, 0, 0 };
205 struct radix_node_head
*rt_tables
[AF_MAX
+1];
207 lck_mtx_t
*rnh_lock
; /* global routing tables mutex */
208 static lck_attr_t
*rnh_lock_attr
;
209 static lck_grp_t
*rnh_lock_grp
;
210 static lck_grp_attr_t
*rnh_lock_grp_attr
;
212 /* Lock group and attribute for routing entry locks */
213 static lck_attr_t
*rte_mtx_attr
;
214 static lck_grp_t
*rte_mtx_grp
;
215 static lck_grp_attr_t
*rte_mtx_grp_attr
;
217 lck_mtx_t
*route_domain_mtx
; /*### global routing tables mutex for now */
218 int rttrash
= 0; /* routes not in table but not freed */
220 unsigned int rte_debug
;
222 /* Possible flags for rte_debug */
223 #define RTD_DEBUG 0x1 /* enable or disable rtentry debug facility */
224 #define RTD_TRACE 0x2 /* trace alloc, free, refcnt and lock */
225 #define RTD_NO_FREE 0x4 /* don't free (good to catch corruptions) */
227 #define RTE_NAME "rtentry" /* name for zone and rt_lock */
229 static struct zone
*rte_zone
; /* special zone for rtentry */
230 #define RTE_ZONE_MAX 65536 /* maximum elements in zone */
231 #define RTE_ZONE_NAME RTE_NAME /* name of rtentry zone */
233 #define RTD_INUSE 0xFEEDFACE /* entry is in use */
234 #define RTD_FREED 0xDEADBEEF /* entry is freed */
237 __private_extern__
unsigned int ctrace_stack_size
= CTRACE_STACK_SIZE
;
238 __private_extern__
unsigned int ctrace_hist_size
= CTRACE_HIST_SIZE
;
241 * Debug variant of rtentry structure.
244 struct rtentry rtd_entry
; /* rtentry */
245 struct rtentry rtd_entry_saved
; /* saved rtentry */
246 uint32_t rtd_inuse
; /* in use pattern */
247 uint16_t rtd_refhold_cnt
; /* # of rtref */
248 uint16_t rtd_refrele_cnt
; /* # of rtunref */
249 uint32_t rtd_lock_cnt
; /* # of locks */
250 uint32_t rtd_unlock_cnt
; /* # of unlocks */
252 * Alloc and free callers.
257 * Circular lists of rtref and rtunref callers.
259 ctrace_t rtd_refhold
[CTRACE_HIST_SIZE
];
260 ctrace_t rtd_refrele
[CTRACE_HIST_SIZE
];
262 * Circular lists of locks and unlocks.
264 ctrace_t rtd_lock
[CTRACE_HIST_SIZE
];
265 ctrace_t rtd_unlock
[CTRACE_HIST_SIZE
];
269 TAILQ_ENTRY(rtentry_dbg
) rtd_trash_link
;
272 /* List of trash route entries protected by rnh_lock */
273 static TAILQ_HEAD(, rtentry_dbg
) rttrash_head
;
275 static void rte_lock_init(struct rtentry
*);
276 static void rte_lock_destroy(struct rtentry
*);
277 static inline struct rtentry
*rte_alloc_debug(void);
278 static inline void rte_free_debug(struct rtentry
*);
279 static inline void rte_lock_debug(struct rtentry_dbg
*);
280 static inline void rte_unlock_debug(struct rtentry_dbg
*);
281 static void rt_maskedcopy(struct sockaddr
*,
282 struct sockaddr
*, struct sockaddr
*);
283 static void rtable_init(void **);
284 static inline void rtref_audit(struct rtentry_dbg
*);
285 static inline void rtunref_audit(struct rtentry_dbg
*);
286 static struct rtentry
*rtalloc1_common_locked(struct sockaddr
*, int, uint32_t,
288 static int rtrequest_common_locked(int, struct sockaddr
*,
289 struct sockaddr
*, struct sockaddr
*, int, struct rtentry
**,
291 static struct rtentry
*rtalloc1_locked(struct sockaddr
*, int, uint32_t);
292 static void rtalloc_ign_common_locked(struct route
*, uint32_t, unsigned int);
293 static inline void sin6_set_ifscope(struct sockaddr
*, unsigned int);
294 static inline void sin6_set_embedded_ifscope(struct sockaddr
*, unsigned int);
295 static inline unsigned int sin6_get_embedded_ifscope(struct sockaddr
*);
296 static struct sockaddr
*sa_copy(struct sockaddr
*, struct sockaddr_storage
*,
298 static struct sockaddr
*ma_copy(int, struct sockaddr
*,
299 struct sockaddr_storage
*, unsigned int);
300 static struct sockaddr
*sa_trim(struct sockaddr
*, int);
301 static struct radix_node
*node_lookup(struct sockaddr
*, struct sockaddr
*,
303 static struct radix_node
*node_lookup_default(int);
304 static int rn_match_ifscope(struct radix_node
*, void *);
305 static struct ifaddr
*ifa_ifwithroute_common_locked(int,
306 const struct sockaddr
*, const struct sockaddr
*, unsigned int);
307 static struct rtentry
*rte_alloc(void);
308 static void rte_free(struct rtentry
*);
309 static void rtfree_common(struct rtentry
*, boolean_t
);
310 static void rte_if_ref(struct ifnet
*, int);
312 uint32_t route_generation
= 0;
315 * sockaddr_in with scope ID field; this is used internally to keep
316 * track of scoped route entries in the routing table. The fact that
317 * such a value is embedded in the structure is an artifact of the
318 * current implementation which could change in future.
320 struct sockaddr_inifscope
{
322 sa_family_t sin_family
;
324 struct in_addr sin_addr
;
326 * To avoid possible conflict with an overlaid sockaddr_inarp
327 * having sin_other set to SIN_PROXY, we use the first 4-bytes
328 * of sin_zero since sin_srcaddr is one of the unused fields
337 #define sin_scope_id un._in_index.ifscope
340 #define SA(sa) ((struct sockaddr *)(size_t)(sa))
341 #define SIN(sa) ((struct sockaddr_in *)(size_t)(sa))
342 #define SIN6(sa) ((struct sockaddr_in6 *)(size_t)(sa))
343 #define SINIFSCOPE(sa) ((struct sockaddr_inifscope *)(size_t)(sa))
344 #define SIN6IFSCOPE(sa) SIN6(sa)
346 #define ASSERT_SINIFSCOPE(sa) { \
347 if ((sa)->sa_family != AF_INET || \
348 (sa)->sa_len < sizeof (struct sockaddr_in)) \
349 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
352 #define ASSERT_SIN6IFSCOPE(sa) { \
353 if ((sa)->sa_family != AF_INET6 || \
354 (sa)->sa_len < sizeof (struct sockaddr_in6)) \
355 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
359 * Argument to leaf-matching routine; at present it is scoped routing
360 * specific but can be expanded in future to include other search filters.
362 struct matchleaf_arg
{
363 unsigned int ifscope
; /* interface scope */
367 * For looking up the non-scoped default route (sockaddr instead
368 * of sockaddr_in for convenience).
370 static struct sockaddr sin_def
= {
371 sizeof (struct sockaddr_in
), AF_INET
, { 0, }
374 static struct sockaddr_in6 sin6_def
= {
375 sizeof (struct sockaddr_in6
), AF_INET6
, 0, 0, IN6ADDR_ANY_INIT
, 0
379 * Interface index (scope) of the primary interface; determined at
380 * the time when the default, non-scoped route gets added, changed
381 * or deleted. Protected by rnh_lock.
383 static unsigned int primary_ifscope
= IFSCOPE_NONE
;
384 static unsigned int primary6_ifscope
= IFSCOPE_NONE
;
386 #define INET_DEFAULT(sa) \
387 ((sa)->sa_family == AF_INET && SIN(sa)->sin_addr.s_addr == 0)
389 #define INET6_DEFAULT(sa) \
390 ((sa)->sa_family == AF_INET6 && \
391 IN6_IS_ADDR_UNSPECIFIED(&SIN6(sa)->sin6_addr))
393 #define SA_DEFAULT(sa) (INET_DEFAULT(sa) || INET6_DEFAULT(sa))
394 #define RT(r) ((struct rtentry *)r)
395 #define RN(r) ((struct radix_node *)r)
396 #define RT_HOST(r) (RT(r)->rt_flags & RTF_HOST)
398 SYSCTL_DECL(_net_idle_route
);
400 static int rt_if_idle_expire_timeout
= RT_IF_IDLE_EXPIRE_TIMEOUT
;
401 SYSCTL_INT(_net_idle_route
, OID_AUTO
, expire_timeout
, CTLFLAG_RW
,
402 &rt_if_idle_expire_timeout
, 0, "Default expiration time on routes for "
403 "interface idle reference counting");
406 * Given a route, determine whether or not it is the non-scoped default
407 * route; dst typically comes from rt_key(rt) but may be coming from
408 * a separate place when rt is in the process of being created.
411 rt_primary_default(struct rtentry
*rt
, struct sockaddr
*dst
)
413 return (SA_DEFAULT(dst
) && !(rt
->rt_flags
& RTF_IFSCOPE
));
417 * Set the ifscope of the primary interface; caller holds rnh_lock.
420 set_primary_ifscope(int af
, unsigned int ifscope
)
423 primary_ifscope
= ifscope
;
425 primary6_ifscope
= ifscope
;
429 * Return the ifscope of the primary interface; caller holds rnh_lock.
432 get_primary_ifscope(int af
)
434 return (af
== AF_INET
? primary_ifscope
: primary6_ifscope
);
438 * Set the scope ID of a given a sockaddr_in.
441 sin_set_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
443 /* Caller must pass in sockaddr_in */
444 ASSERT_SINIFSCOPE(sa
);
446 SINIFSCOPE(sa
)->sin_scope_id
= ifscope
;
450 * Set the scope ID of given a sockaddr_in6.
453 sin6_set_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
455 /* Caller must pass in sockaddr_in6 */
456 ASSERT_SIN6IFSCOPE(sa
);
458 SIN6IFSCOPE(sa
)->sin6_scope_id
= ifscope
;
462 * Given a sockaddr_in, return the scope ID to the caller.
465 sin_get_ifscope(struct sockaddr
*sa
)
467 /* Caller must pass in sockaddr_in */
468 ASSERT_SINIFSCOPE(sa
);
470 return (SINIFSCOPE(sa
)->sin_scope_id
);
474 * Given a sockaddr_in6, return the scope ID to the caller.
477 sin6_get_ifscope(struct sockaddr
*sa
)
479 /* Caller must pass in sockaddr_in6 */
480 ASSERT_SIN6IFSCOPE(sa
);
482 return (SIN6IFSCOPE(sa
)->sin6_scope_id
);
486 sin6_set_embedded_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
488 /* Caller must pass in sockaddr_in6 */
489 ASSERT_SIN6IFSCOPE(sa
);
490 VERIFY(IN6_IS_SCOPE_EMBED(&(SIN6(sa
)->sin6_addr
)));
492 SIN6(sa
)->sin6_addr
.s6_addr16
[1] = htons(ifscope
);
495 static inline unsigned int
496 sin6_get_embedded_ifscope(struct sockaddr
*sa
)
498 /* Caller must pass in sockaddr_in6 */
499 ASSERT_SIN6IFSCOPE(sa
);
501 return (ntohs(SIN6(sa
)->sin6_addr
.s6_addr16
[1]));
505 * Copy a sockaddr_{in,in6} src to a dst storage and set scope ID into dst.
507 * To clear the scope ID, pass is a NULL pifscope. To set the scope ID, pass
508 * in a non-NULL pifscope with non-zero ifscope. Otherwise if pifscope is
509 * non-NULL and ifscope is IFSCOPE_NONE, the existing scope ID is left intact.
510 * In any case, the effective scope ID value is returned to the caller via
511 * pifscope, if it is non-NULL.
513 static struct sockaddr
*
514 sa_copy(struct sockaddr
*src
, struct sockaddr_storage
*dst
,
515 unsigned int *pifscope
)
517 int af
= src
->sa_family
;
518 unsigned int ifscope
= (pifscope
!= NULL
) ? *pifscope
: IFSCOPE_NONE
;
520 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
522 bzero(dst
, sizeof (*dst
));
525 bcopy(src
, dst
, sizeof (struct sockaddr_in
));
526 if (pifscope
== NULL
|| ifscope
!= IFSCOPE_NONE
)
527 sin_set_ifscope(SA(dst
), ifscope
);
529 bcopy(src
, dst
, sizeof (struct sockaddr_in6
));
530 if (pifscope
!= NULL
&&
531 IN6_IS_SCOPE_EMBED(&SIN6(dst
)->sin6_addr
)) {
532 unsigned int eifscope
;
534 * If the address contains the embedded scope ID,
535 * use that as the value for sin6_scope_id as long
536 * the caller doesn't insist on clearing it (by
537 * passing NULL) or setting it.
539 eifscope
= sin6_get_embedded_ifscope(SA(dst
));
540 if (eifscope
!= IFSCOPE_NONE
&& ifscope
== IFSCOPE_NONE
)
542 sin6_set_ifscope(SA(dst
), ifscope
);
544 * If sin6_scope_id is set but the address doesn't
545 * contain the equivalent embedded value, set it.
547 if (ifscope
!= IFSCOPE_NONE
&& eifscope
!= ifscope
)
548 sin6_set_embedded_ifscope(SA(dst
), ifscope
);
549 } else if (pifscope
== NULL
|| ifscope
!= IFSCOPE_NONE
) {
550 sin6_set_ifscope(SA(dst
), ifscope
);
554 if (pifscope
!= NULL
) {
555 *pifscope
= (af
== AF_INET
) ? sin_get_ifscope(SA(dst
)) :
556 sin6_get_ifscope(SA(dst
));
563 * Copy a mask from src to a dst storage and set scope ID into dst.
565 static struct sockaddr
*
566 ma_copy(int af
, struct sockaddr
*src
, struct sockaddr_storage
*dst
,
567 unsigned int ifscope
)
569 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
571 bzero(dst
, sizeof (*dst
));
572 rt_maskedcopy(src
, SA(dst
), src
);
575 * The length of the mask sockaddr would need to be adjusted
576 * to cover the additional {sin,sin6}_ifscope field; when ifscope
577 * is IFSCOPE_NONE, we'd end up clearing the scope ID field on
578 * the destination mask in addition to extending the length
579 * of the sockaddr, as a side effect. This is okay, as any
580 * trailing zeroes would be skipped by rn_addmask prior to
581 * inserting or looking up the mask in the mask tree.
584 SINIFSCOPE(dst
)->sin_scope_id
= ifscope
;
585 SINIFSCOPE(dst
)->sin_len
=
586 offsetof(struct sockaddr_inifscope
, sin_scope_id
) +
587 sizeof (SINIFSCOPE(dst
)->sin_scope_id
);
589 SIN6IFSCOPE(dst
)->sin6_scope_id
= ifscope
;
590 SIN6IFSCOPE(dst
)->sin6_len
=
591 offsetof(struct sockaddr_in6
, sin6_scope_id
) +
592 sizeof (SIN6IFSCOPE(dst
)->sin6_scope_id
);
599 * Trim trailing zeroes on a sockaddr and update its length.
601 static struct sockaddr
*
602 sa_trim(struct sockaddr
*sa
, int skip
)
604 caddr_t cp
, base
= (caddr_t
)sa
+ skip
;
606 if (sa
->sa_len
<= skip
)
609 for (cp
= base
+ (sa
->sa_len
- skip
); cp
> base
&& cp
[-1] == 0;)
612 sa
->sa_len
= (cp
- base
) + skip
;
613 if (sa
->sa_len
< skip
) {
614 /* Must not happen, and if so, panic */
615 panic("%s: broken logic (sa_len %d < skip %d )", __func__
,
618 } else if (sa
->sa_len
== skip
) {
619 /* If we end up with all zeroes, then there's no mask */
627 * Called by rtm_msg{1,2} routines to "scrub" the scope ID field away from
628 * the socket address structure, so that clients of the routing socket will
629 * not be confused by the presence of the information, or the side effect of
630 * the increased length due to that. The source sockaddr is not modified;
631 * instead, the scrubbing happens on the destination sockaddr storage that
632 * is passed in by the caller.
635 rtm_scrub_ifscope(int type
, int idx
, struct sockaddr
*hint
, struct sockaddr
*sa
,
636 struct sockaddr_storage
*ss
)
638 struct sockaddr
*ret
= sa
;
643 * If this is for an AF_INET/AF_INET6 destination address,
644 * call sa_copy() to clear the scope ID field.
646 if (sa
->sa_family
== AF_INET
&&
647 SINIFSCOPE(sa
)->sin_scope_id
!= IFSCOPE_NONE
) {
648 ret
= sa_copy(sa
, ss
, NULL
);
649 } else if (sa
->sa_family
== AF_INET6
&&
650 SIN6IFSCOPE(sa
)->sin6_scope_id
!= IFSCOPE_NONE
) {
651 ret
= sa_copy(sa
, ss
, NULL
);
658 * If this is for a mask, we can't tell whether or not there
659 * is an valid scope ID value, as the span of bytes between
660 * sa_len and the beginning of the mask (offset of sin_addr in
661 * the case of AF_INET, or sin6_addr for AF_INET6) may be
662 * filled with all-ones by rn_addmask(), and hence we cannot
663 * rely on sa_family. Because of this, we use the sa_family
664 * of the hint sockaddr (RTAX_{DST,IFA}) as indicator as to
665 * whether or not the mask is to be treated as one for AF_INET
666 * or AF_INET6. Clearing the scope ID field involves setting
667 * it to IFSCOPE_NONE followed by calling sa_trim() to trim
668 * trailing zeroes from the storage sockaddr, which reverses
669 * what was done earlier by ma_copy() on the source sockaddr.
672 ((af
= hint
->sa_family
) != AF_INET
&& af
!= AF_INET6
))
673 break; /* nothing to do */
675 skip
= (af
== AF_INET
) ?
676 offsetof(struct sockaddr_in
, sin_addr
) :
677 offsetof(struct sockaddr_in6
, sin6_addr
);
679 if (sa
->sa_len
> skip
&& sa
->sa_len
<= sizeof (*ss
)) {
680 bzero(ss
, sizeof (*ss
));
681 bcopy(sa
, ss
, sa
->sa_len
);
683 * Don't use {sin,sin6}_set_ifscope() as sa_family
684 * and sa_len for the netmask might not be set to
685 * the corresponding expected values of the hint.
687 if (hint
->sa_family
== AF_INET
)
688 SINIFSCOPE(ss
)->sin_scope_id
= IFSCOPE_NONE
;
690 SIN6IFSCOPE(ss
)->sin6_scope_id
= IFSCOPE_NONE
;
691 ret
= sa_trim(SA(ss
), skip
);
694 * For AF_INET6 mask, set sa_len appropriately unless
695 * this is requested via systl_dumpentry(), in which
696 * case we return the raw value.
698 if (hint
->sa_family
== AF_INET6
&&
699 type
!= RTM_GET
&& type
!= RTM_GET2
)
700 SA(ret
)->sa_len
= sizeof (struct sockaddr_in6
);
712 * Callback leaf-matching routine for rn_matchaddr_args used
713 * for looking up an exact match for a scoped route entry.
716 rn_match_ifscope(struct radix_node
*rn
, void *arg
)
718 struct rtentry
*rt
= (struct rtentry
*)rn
;
719 struct matchleaf_arg
*ma
= arg
;
720 int af
= rt_key(rt
)->sa_family
;
722 if (!(rt
->rt_flags
& RTF_IFSCOPE
) || (af
!= AF_INET
&& af
!= AF_INET6
))
725 return (af
== AF_INET
?
726 (SINIFSCOPE(rt_key(rt
))->sin_scope_id
== ma
->ifscope
) :
727 (SIN6IFSCOPE(rt_key(rt
))->sin6_scope_id
== ma
->ifscope
));
731 rtable_init(void **table
)
734 for (dom
= domains
; dom
; dom
= dom
->dom_next
)
735 if (dom
->dom_rtattach
)
736 dom
->dom_rtattach(&table
[dom
->dom_family
],
745 PE_parse_boot_argn("rte_debug", &rte_debug
, sizeof (rte_debug
));
747 rte_debug
|= RTD_DEBUG
;
749 rnh_lock_grp_attr
= lck_grp_attr_alloc_init();
750 rnh_lock_grp
= lck_grp_alloc_init("route", rnh_lock_grp_attr
);
751 rnh_lock_attr
= lck_attr_alloc_init();
752 if ((rnh_lock
= lck_mtx_alloc_init(rnh_lock_grp
,
753 rnh_lock_attr
)) == NULL
) {
754 printf("route_init: can't alloc rnh_lock\n");
758 rte_mtx_grp_attr
= lck_grp_attr_alloc_init();
759 rte_mtx_grp
= lck_grp_alloc_init(RTE_NAME
, rte_mtx_grp_attr
);
760 rte_mtx_attr
= lck_attr_alloc_init();
762 lck_mtx_lock(rnh_lock
);
763 rn_init(); /* initialize all zeroes, all ones, mask table */
764 lck_mtx_unlock(rnh_lock
);
765 rtable_init((void **)rt_tables
);
766 route_domain_mtx
= routedomain
.dom_mtx
;
768 if (rte_debug
& RTD_DEBUG
)
769 size
= sizeof (struct rtentry_dbg
);
771 size
= sizeof (struct rtentry
);
773 rte_zone
= zinit(size
, RTE_ZONE_MAX
* size
, 0, RTE_ZONE_NAME
);
774 if (rte_zone
== NULL
)
775 panic("route_init: failed allocating rte_zone");
777 zone_change(rte_zone
, Z_EXPAND
, TRUE
);
778 zone_change(rte_zone
, Z_CALLERACCT
, FALSE
);
779 zone_change(rte_zone
, Z_NOENCRYPT
, TRUE
);
781 TAILQ_INIT(&rttrash_head
);
785 * Atomically increment route generation counter
788 routegenid_update(void)
790 (void) atomic_add_32_ov(&route_generation
, 1);
794 * Packet routing routines.
797 rtalloc(struct route
*ro
)
803 rtalloc_scoped(struct route
*ro
, unsigned int ifscope
)
805 rtalloc_scoped_ign(ro
, 0, ifscope
);
809 rtalloc_ign_common_locked(struct route
*ro
, uint32_t ignore
,
810 unsigned int ifscope
)
814 if ((rt
= ro
->ro_rt
) != NULL
) {
816 if (rt
->rt_ifp
!= NULL
&& (rt
->rt_flags
& RTF_UP
) &&
817 rt
->generation_id
== route_generation
) {
825 ro
->ro_rt
= rtalloc1_common_locked(&ro
->ro_dst
, 1, ignore
, ifscope
);
826 if (ro
->ro_rt
!= NULL
) {
827 ro
->ro_rt
->generation_id
= route_generation
;
828 RT_LOCK_ASSERT_NOTHELD(ro
->ro_rt
);
833 rtalloc_ign(struct route
*ro
, uint32_t ignore
)
835 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
836 lck_mtx_lock(rnh_lock
);
837 rtalloc_ign_common_locked(ro
, ignore
, IFSCOPE_NONE
);
838 lck_mtx_unlock(rnh_lock
);
842 rtalloc_scoped_ign(struct route
*ro
, uint32_t ignore
, unsigned int ifscope
)
844 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
845 lck_mtx_lock(rnh_lock
);
846 rtalloc_ign_common_locked(ro
, ignore
, ifscope
);
847 lck_mtx_unlock(rnh_lock
);
850 static struct rtentry
*
851 rtalloc1_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
853 return (rtalloc1_common_locked(dst
, report
, ignflags
, IFSCOPE_NONE
));
857 rtalloc1_scoped_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
858 unsigned int ifscope
)
860 return (rtalloc1_common_locked(dst
, report
, ignflags
, ifscope
));
864 * Look up the route that matches the address given
865 * Or, at least try.. Create a cloned route if needed.
867 static struct rtentry
*
868 rtalloc1_common_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
869 unsigned int ifscope
)
871 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
872 struct rtentry
*rt
, *newrt
= NULL
;
873 struct rt_addrinfo info
;
875 int err
= 0, msgtype
= RTM_MISS
;
881 * Find the longest prefix or exact (in the scoped case) address match;
882 * callee adds a reference to entry and checks for root node as well
884 rt
= rt_lookup(FALSE
, dst
, NULL
, rnh
, ifscope
);
890 nflags
= rt
->rt_flags
& ~ignflags
;
892 if (report
&& (nflags
& (RTF_CLONING
| RTF_PRCLONING
))) {
894 * We are apparently adding (report = 0 in delete).
895 * If it requires that it be cloned, do so.
896 * (This implies it wasn't a HOST route.)
898 err
= rtrequest_locked(RTM_RESOLVE
, dst
, NULL
, NULL
, 0, &newrt
);
901 * If the cloning didn't succeed, maybe what we
902 * have from lookup above will do. Return that;
903 * no need to hold another reference since it's
911 * We cloned it; drop the original route found during lookup.
912 * The resulted cloned route (newrt) would now have an extra
913 * reference held during rtrequest.
916 if ((rt
= newrt
) && (rt
->rt_flags
& RTF_XRESOLVE
)) {
918 * If the new route specifies it be
919 * externally resolved, then go do that.
921 msgtype
= RTM_RESOLVE
;
929 * Either we hit the root or couldn't find any match,
930 * Which basically means "cant get there from here"
932 rtstat
.rts_unreach
++;
936 * If required, report the failure to the supervising
938 * For a delete, this is not an error. (report == 0)
940 bzero((caddr_t
)&info
, sizeof(info
));
941 info
.rti_info
[RTAX_DST
] = dst
;
942 rt_missmsg(msgtype
, &info
, 0, err
);
949 rtalloc1(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
951 struct rtentry
* entry
;
952 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
953 lck_mtx_lock(rnh_lock
);
954 entry
= rtalloc1_locked(dst
, report
, ignflags
);
955 lck_mtx_unlock(rnh_lock
);
960 rtalloc1_scoped(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
961 unsigned int ifscope
)
963 struct rtentry
* entry
;
964 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
965 lck_mtx_lock(rnh_lock
);
966 entry
= rtalloc1_scoped_locked(dst
, report
, ignflags
, ifscope
);
967 lck_mtx_unlock(rnh_lock
);
972 * Remove a reference count from an rtentry.
973 * If the count gets low enough, take it out of the routing table
976 rtfree_locked(struct rtentry
*rt
)
978 rtfree_common(rt
, TRUE
);
982 rtfree_common(struct rtentry
*rt
, boolean_t locked
)
984 struct radix_node_head
*rnh
;
987 * Atomically decrement the reference count and if it reaches 0,
988 * and there is a close function defined, call the close function.
991 if (rtunref(rt
) > 0) {
997 * To avoid violating lock ordering, we must drop rt_lock before
998 * trying to acquire the global rnh_lock. If we are called with
999 * rnh_lock held, then we already have exclusive access; otherwise
1000 * we do the lock dance.
1004 * Note that we check it again below after grabbing rnh_lock,
1005 * since it is possible that another thread doing a lookup wins
1006 * the race, grabs the rnh_lock first, and bumps up the reference
1007 * count in which case the route should be left alone as it is
1008 * still in use. It's also possible that another thread frees
1009 * the route after we drop rt_lock; to prevent the route from
1010 * being freed, we hold an extra reference.
1012 RT_ADDREF_LOCKED(rt
);
1014 lck_mtx_lock(rnh_lock
);
1016 RT_REMREF_LOCKED(rt
);
1017 if (rt
->rt_refcnt
> 0) {
1018 /* We've lost the race, so abort */
1025 * We may be blocked on other lock(s) as part of freeing
1026 * the entry below, so convert from spin to full mutex.
1028 RT_CONVERT_LOCK(rt
);
1030 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1032 /* Negative refcnt must never happen */
1033 if (rt
->rt_refcnt
!= 0)
1034 panic("rt %p invalid refcnt %d", rt
, rt
->rt_refcnt
);
1037 * find the tree for that address family
1038 * Note: in the case of igmp packets, there might not be an rnh
1040 rnh
= rt_tables
[rt_key(rt
)->sa_family
];
1043 * On last reference give the "close method" a chance to cleanup
1044 * private state. This also permits (for IPv4 and IPv6) a chance
1045 * to decide if the routing table entry should be purged immediately
1046 * or at a later time. When an immediate purge is to happen the
1047 * close routine typically issues RTM_DELETE which clears the RTF_UP
1048 * flag on the entry so that the code below reclaims the storage.
1050 if (rnh
!= NULL
&& rnh
->rnh_close
!= NULL
)
1051 rnh
->rnh_close((struct radix_node
*)rt
, rnh
);
1054 * If we are no longer "up" (and ref == 0) then we can free the
1055 * resources associated with the route.
1057 if (!(rt
->rt_flags
& RTF_UP
)) {
1058 struct rtentry
*rt_parent
;
1059 struct ifaddr
*rt_ifa
;
1061 if (rt
->rt_nodes
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
))
1062 panic("rt %p freed while in radix tree\n", rt
);
1064 * the rtentry must have been removed from the routing table
1065 * so it is represented in rttrash; remove that now.
1067 (void) OSDecrementAtomic(&rttrash
);
1068 if (rte_debug
& RTD_DEBUG
) {
1069 TAILQ_REMOVE(&rttrash_head
, (struct rtentry_dbg
*)rt
,
1074 * release references on items we hold them on..
1075 * e.g other routes and ifaddrs.
1077 if ((rt_parent
= rt
->rt_parent
) != NULL
)
1078 rt
->rt_parent
= NULL
;
1080 if ((rt_ifa
= rt
->rt_ifa
) != NULL
)
1084 * Now free any attached link-layer info.
1086 if (rt
->rt_llinfo
!= NULL
) {
1087 if (rt
->rt_llinfo_free
!= NULL
)
1088 (*rt
->rt_llinfo_free
)(rt
->rt_llinfo
);
1090 R_Free(rt
->rt_llinfo
);
1091 rt
->rt_llinfo
= NULL
;
1095 * Route is no longer in the tree and refcnt is 0;
1096 * we have exclusive access, so destroy it.
1100 if (rt_parent
!= NULL
)
1101 rtfree_locked(rt_parent
);
1107 * The key is separately alloc'd so free it (see rt_setgate()).
1108 * This also frees the gateway, as they are always malloc'd
1114 * Free any statistics that may have been allocated
1116 nstat_route_detach(rt
);
1119 * and the rtentry itself of course
1121 rte_lock_destroy(rt
);
1125 * The "close method" has been called, but the route is
1126 * still in the radix tree with zero refcnt, i.e. "up"
1127 * and in the cached state.
1133 lck_mtx_unlock(rnh_lock
);
1137 rtfree(struct rtentry
*rt
)
1139 rtfree_common(rt
, FALSE
);
1143 * Decrements the refcount but does not free the route when
1144 * the refcount reaches zero. Unless you have really good reason,
1145 * use rtfree not rtunref.
1148 rtunref(struct rtentry
*p
)
1150 RT_LOCK_ASSERT_HELD(p
);
1152 if (p
->rt_refcnt
== 0)
1153 panic("%s(%p) bad refcnt\n", __func__
, p
);
1157 if (rte_debug
& RTD_DEBUG
)
1158 rtunref_audit((struct rtentry_dbg
*)p
);
1160 /* Return new value */
1161 return (p
->rt_refcnt
);
1165 rtunref_audit(struct rtentry_dbg
*rte
)
1169 if (rte
->rtd_inuse
!= RTD_INUSE
)
1170 panic("rtunref: on freed rte=%p\n", rte
);
1172 idx
= atomic_add_16_ov(&rte
->rtd_refrele_cnt
, 1) % CTRACE_HIST_SIZE
;
1173 if (rte_debug
& RTD_TRACE
)
1174 ctrace_record(&rte
->rtd_refrele
[idx
]);
1178 * Add a reference count from an rtentry.
1181 rtref(struct rtentry
*p
)
1183 RT_LOCK_ASSERT_HELD(p
);
1185 if (++p
->rt_refcnt
== 0)
1186 panic("%s(%p) bad refcnt\n", __func__
, p
);
1188 if (rte_debug
& RTD_DEBUG
)
1189 rtref_audit((struct rtentry_dbg
*)p
);
1193 rtref_audit(struct rtentry_dbg
*rte
)
1197 if (rte
->rtd_inuse
!= RTD_INUSE
)
1198 panic("rtref_audit: on freed rte=%p\n", rte
);
1200 idx
= atomic_add_16_ov(&rte
->rtd_refhold_cnt
, 1) % CTRACE_HIST_SIZE
;
1201 if (rte_debug
& RTD_TRACE
)
1202 ctrace_record(&rte
->rtd_refhold
[idx
]);
1206 rtsetifa(struct rtentry
*rt
, struct ifaddr
* ifa
)
1208 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1210 RT_LOCK_ASSERT_HELD(rt
);
1212 if (rt
->rt_ifa
== ifa
)
1215 /* Become a regular mutex, just in case */
1216 RT_CONVERT_LOCK(rt
);
1218 /* Release the old ifa */
1220 IFA_REMREF(rt
->rt_ifa
);
1225 /* Take a reference to the ifa */
1227 IFA_ADDREF(rt
->rt_ifa
);
1231 * Force a routing table entry to the specified
1232 * destination to go through the given gateway.
1233 * Normally called as a result of a routing redirect
1234 * message from the network layer.
1237 rtredirect(struct ifnet
*ifp
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1238 struct sockaddr
*netmask
, int flags
, struct sockaddr
*src
,
1239 struct rtentry
**rtp
)
1241 struct rtentry
*rt
= NULL
;
1244 struct rt_addrinfo info
;
1245 struct ifaddr
*ifa
= NULL
;
1246 unsigned int ifscope
= (ifp
!= NULL
) ? ifp
->if_index
: IFSCOPE_NONE
;
1247 struct sockaddr_storage ss
;
1249 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1250 lck_mtx_lock(rnh_lock
);
1253 * Transform src into the internal routing table form for
1254 * comparison against rt_gateway below.
1257 if ((src
->sa_family
== AF_INET
&& ip_doscopedroute
) ||
1258 (src
->sa_family
== AF_INET6
&& ip6_doscopedroute
))
1260 if (src
->sa_family
== AF_INET
&& ip_doscopedroute
)
1262 src
= sa_copy(src
, &ss
, &ifscope
);
1265 * Verify the gateway is directly reachable; if scoped routing
1266 * is enabled, verify that it is reachable from the interface
1267 * where the ICMP redirect arrived on.
1269 if ((ifa
= ifa_ifwithnet_scoped(gateway
, ifscope
)) == NULL
) {
1270 error
= ENETUNREACH
;
1274 /* Lookup route to the destination (from the original IP header) */
1275 rt
= rtalloc1_scoped_locked(dst
, 0, RTF_CLONING
|RTF_PRCLONING
, ifscope
);
1280 * If the redirect isn't from our current router for this dst,
1281 * it's either old or wrong. If it redirects us to ourselves,
1282 * we have a routing loop, perhaps as a result of an interface
1283 * going down recently. Holding rnh_lock here prevents the
1284 * possibility of rt_ifa/ifa's ifa_addr from changing (e.g.
1285 * in_ifinit), so okay to access ifa_addr without locking.
1287 if (!(flags
& RTF_DONE
) && rt
!= NULL
&&
1288 (!equal(src
, rt
->rt_gateway
) || !equal(rt
->rt_ifa
->ifa_addr
,
1293 if ((ifa
= ifa_ifwithaddr(gateway
))) {
1296 error
= EHOSTUNREACH
;
1312 * Create a new entry if we just got back a wildcard entry
1313 * or the the lookup failed. This is necessary for hosts
1314 * which use routing redirects generated by smart gateways
1315 * to dynamically build the routing tables.
1317 if ((rt
== NULL
) || (rt_mask(rt
) != NULL
&& rt_mask(rt
)->sa_len
< 2))
1320 * Don't listen to the redirect if it's
1321 * for a route to an interface.
1323 RT_LOCK_ASSERT_HELD(rt
);
1324 if (rt
->rt_flags
& RTF_GATEWAY
) {
1325 if (((rt
->rt_flags
& RTF_HOST
) == 0) && (flags
& RTF_HOST
)) {
1327 * Changing from route to net => route to host.
1328 * Create new route, rather than smashing route
1329 * to net; similar to cloned routes, the newly
1330 * created host route is scoped as well.
1335 flags
|= RTF_GATEWAY
| RTF_DYNAMIC
;
1336 error
= rtrequest_scoped_locked(RTM_ADD
, dst
,
1337 gateway
, netmask
, flags
, NULL
, ifscope
);
1338 stat
= &rtstat
.rts_dynamic
;
1341 * Smash the current notion of the gateway to
1342 * this destination. Should check about netmask!!!
1344 rt
->rt_flags
|= RTF_MODIFIED
;
1345 flags
|= RTF_MODIFIED
;
1346 stat
= &rtstat
.rts_newgateway
;
1348 * add the key and gateway (in one malloc'd chunk).
1350 error
= rt_setgate(rt
, rt_key(rt
), gateway
);
1355 error
= EHOSTUNREACH
;
1359 RT_LOCK_ASSERT_NOTHELD(rt
);
1367 rtstat
.rts_badredirect
++;
1372 routegenid_update();
1374 lck_mtx_unlock(rnh_lock
);
1375 bzero((caddr_t
)&info
, sizeof(info
));
1376 info
.rti_info
[RTAX_DST
] = dst
;
1377 info
.rti_info
[RTAX_GATEWAY
] = gateway
;
1378 info
.rti_info
[RTAX_NETMASK
] = netmask
;
1379 info
.rti_info
[RTAX_AUTHOR
] = src
;
1380 rt_missmsg(RTM_REDIRECT
, &info
, flags
, error
);
1384 * Routing table ioctl interface.
1387 rtioctl(unsigned long req
, caddr_t data
, struct proc
*p
)
1390 #if INET && MROUTING
1391 return mrt_ioctl(req
, data
);
1394 #pragma unused(data)
1402 const struct sockaddr
*dst
,
1403 const struct sockaddr
*gateway
)
1407 lck_mtx_lock(rnh_lock
);
1408 ifa
= ifa_ifwithroute_locked(flags
, dst
, gateway
);
1409 lck_mtx_unlock(rnh_lock
);
1415 ifa_ifwithroute_locked(int flags
, const struct sockaddr
*dst
,
1416 const struct sockaddr
*gateway
)
1418 return (ifa_ifwithroute_common_locked((flags
& ~RTF_IFSCOPE
), dst
,
1419 gateway
, IFSCOPE_NONE
));
1423 ifa_ifwithroute_scoped_locked(int flags
, const struct sockaddr
*dst
,
1424 const struct sockaddr
*gateway
, unsigned int ifscope
)
1426 if (ifscope
!= IFSCOPE_NONE
)
1427 flags
|= RTF_IFSCOPE
;
1429 flags
&= ~RTF_IFSCOPE
;
1431 return (ifa_ifwithroute_common_locked(flags
, dst
, gateway
, ifscope
));
1434 static struct ifaddr
*
1435 ifa_ifwithroute_common_locked(int flags
, const struct sockaddr
*dst
,
1436 const struct sockaddr
*gw
, unsigned int ifscope
)
1438 struct ifaddr
*ifa
= NULL
;
1439 struct rtentry
*rt
= NULL
;
1440 struct sockaddr_storage dst_ss
, gw_ss
;
1442 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1445 * Just in case the sockaddr passed in by the caller
1446 * contains a scope ID, make sure to clear it since
1447 * interface addresses aren't scoped.
1451 ((dst
->sa_family
== AF_INET
&& ip_doscopedroute
) ||
1452 (dst
->sa_family
== AF_INET6
&& ip6_doscopedroute
)))
1454 if (dst
!= NULL
&& dst
->sa_family
== AF_INET
&& ip_doscopedroute
)
1456 dst
= sa_copy(SA(dst
), &dst_ss
, NULL
);
1460 ((gw
->sa_family
== AF_INET
&& ip_doscopedroute
) ||
1461 (gw
->sa_family
== AF_INET6
&& ip6_doscopedroute
)))
1463 if (gw
!= NULL
&& gw
->sa_family
== AF_INET
&& ip_doscopedroute
)
1465 gw
= sa_copy(SA(gw
), &gw_ss
, NULL
);
1467 if (!(flags
& RTF_GATEWAY
)) {
1469 * If we are adding a route to an interface,
1470 * and the interface is a pt to pt link
1471 * we should search for the destination
1472 * as our clue to the interface. Otherwise
1473 * we can use the local address.
1475 if (flags
& RTF_HOST
) {
1476 ifa
= ifa_ifwithdstaddr(dst
);
1479 ifa
= ifa_ifwithaddr_scoped(gw
, ifscope
);
1482 * If we are adding a route to a remote net
1483 * or host, the gateway may still be on the
1484 * other end of a pt to pt link.
1486 ifa
= ifa_ifwithdstaddr(gw
);
1489 ifa
= ifa_ifwithnet_scoped(gw
, ifscope
);
1491 /* Workaround to avoid gcc warning regarding const variable */
1492 rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)dst
,
1498 /* Become a regular mutex */
1499 RT_CONVERT_LOCK(rt
);
1502 RT_REMREF_LOCKED(rt
);
1508 * Holding rnh_lock here prevents the possibility of ifa from
1509 * changing (e.g. in_ifinit), so it is safe to access its
1510 * ifa_addr (here and down below) without locking.
1512 if (ifa
!= NULL
&& ifa
->ifa_addr
->sa_family
!= dst
->sa_family
) {
1513 struct ifaddr
*newifa
;
1514 /* Callee adds reference to newifa upon success */
1515 newifa
= ifaof_ifpforaddr(dst
, ifa
->ifa_ifp
);
1516 if (newifa
!= NULL
) {
1522 * If we are adding a gateway, it is quite possible that the
1523 * routing table has a static entry in place for the gateway,
1524 * that may not agree with info garnered from the interfaces.
1525 * The routing table should carry more precedence than the
1526 * interfaces in this matter. Must be careful not to stomp
1527 * on new entries from rtinit, hence (ifa->ifa_addr != gw).
1530 !equal(ifa
->ifa_addr
, (struct sockaddr
*)(size_t)gw
)) &&
1531 (rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)gw
,
1532 0, 0, ifscope
)) != NULL
) {
1538 /* Become a regular mutex */
1539 RT_CONVERT_LOCK(rt
);
1542 RT_REMREF_LOCKED(rt
);
1546 * If an interface scope was specified, the interface index of
1547 * the found ifaddr must be equivalent to that of the scope;
1548 * otherwise there is no match.
1550 if ((flags
& RTF_IFSCOPE
) &&
1551 ifa
!= NULL
&& ifa
->ifa_ifp
->if_index
!= ifscope
) {
1559 static int rt_fixdelete(struct radix_node
*, void *);
1560 static int rt_fixchange(struct radix_node
*, void *);
1563 struct rtentry
*rt0
;
1564 struct radix_node_head
*rnh
;
1568 rtrequest_locked(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1569 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
)
1571 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1572 (flags
& ~RTF_IFSCOPE
), ret_nrt
, IFSCOPE_NONE
));
1576 rtrequest_scoped_locked(int req
, struct sockaddr
*dst
,
1577 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1578 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1580 if (ifscope
!= IFSCOPE_NONE
)
1581 flags
|= RTF_IFSCOPE
;
1583 flags
&= ~RTF_IFSCOPE
;
1585 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1586 flags
, ret_nrt
, ifscope
));
1590 * Do appropriate manipulations of a routing tree given all the bits of
1593 * Storing the scope ID in the radix key is an internal job that should be
1594 * left to routines in this module. Callers should specify the scope value
1595 * to the "scoped" variants of route routines instead of manipulating the
1596 * key itself. This is typically done when creating a scoped route, e.g.
1597 * rtrequest(RTM_ADD). Once such a route is created and marked with the
1598 * RTF_IFSCOPE flag, callers can simply use its rt_key(rt) to clone it
1599 * (RTM_RESOLVE) or to remove it (RTM_DELETE). An exception to this is
1600 * during certain routing socket operations where the search key might be
1601 * derived from the routing message itself, in which case the caller must
1602 * specify the destination address and scope value for RTM_ADD/RTM_DELETE.
1605 rtrequest_common_locked(int req
, struct sockaddr
*dst0
,
1606 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1607 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1611 struct radix_node
*rn
;
1612 struct radix_node_head
*rnh
;
1613 struct ifaddr
*ifa
= NULL
;
1614 struct sockaddr
*ndst
, *dst
= dst0
;
1615 struct sockaddr_storage ss
, mask
;
1616 struct timeval curr_calendartime
;
1617 int af
= dst
->sa_family
;
1618 void (*ifa_rtrequest
)(int, struct rtentry
*, struct sockaddr
*);
1620 #define senderr(x) { error = x ; goto bad; }
1622 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1624 * Find the correct routing tree to use for this Address Family
1626 if ((rnh
= rt_tables
[af
]) == NULL
)
1629 * If we are adding a host route then we don't want to put
1630 * a netmask in the tree
1632 if (flags
& RTF_HOST
)
1636 * If Scoped Routing is enabled, use a local copy of the destination
1637 * address to store the scope ID into. This logic is repeated below
1638 * in the RTM_RESOLVE handler since the caller does not normally
1639 * specify such a flag during a resolve, as well as for the handling
1640 * of IPv4 link-local address; instead, it passes in the route used for
1641 * cloning for which the scope info is derived from. Note also that
1642 * in the case of RTM_DELETE, the address passed in by the caller
1643 * might already contain the scope ID info when it is the key itself,
1644 * thus making RTF_IFSCOPE unnecessary; one instance where it is
1645 * explicitly set is inside route_output() as part of handling a
1646 * routing socket request.
1649 if (req
!= RTM_RESOLVE
&&
1650 ((af
== AF_INET
&& ip_doscopedroute
) ||
1651 (af
== AF_INET6
&& ip6_doscopedroute
))) {
1653 if (req
!= RTM_RESOLVE
&& af
== AF_INET
&& ip_doscopedroute
) {
1655 /* Transform dst into the internal routing table form */
1656 dst
= sa_copy(dst
, &ss
, &ifscope
);
1658 /* Transform netmask into the internal routing table form */
1659 if (netmask
!= NULL
)
1660 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
1662 if (ifscope
!= IFSCOPE_NONE
)
1663 flags
|= RTF_IFSCOPE
;
1665 if ((flags
& RTF_IFSCOPE
) && (af
!= AF_INET
&& af
!= AF_INET6
))
1669 if ((af
== AF_INET
&& !ip_doscopedroute
) ||
1670 (af
== AF_INET6
&& !ip6_doscopedroute
))
1672 if (af
== AF_INET
&& !ip_doscopedroute
)
1674 ifscope
= IFSCOPE_NONE
;
1677 if (ifscope
== IFSCOPE_NONE
)
1678 flags
&= ~RTF_IFSCOPE
;
1682 struct rtentry
*gwrt
= NULL
;
1684 * Remove the item from the tree and return it.
1685 * Complain if it is not there and do no more processing.
1687 if ((rn
= rnh
->rnh_deladdr(dst
, netmask
, rnh
)) == NULL
)
1689 if (rn
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
))
1690 panic ("rtrequest delete");
1691 rt
= (struct rtentry
*)rn
;
1694 * Take an extra reference to handle the deletion of a route
1695 * entry whose reference count is already 0; e.g. an expiring
1696 * cloned route entry or an entry that was added to the table
1697 * with 0 reference. If the caller is interested in this route,
1698 * we will return it with the reference intact. Otherwise we
1699 * will decrement the reference via rtfree_locked() and then
1700 * possibly deallocate it.
1703 RT_ADDREF_LOCKED(rt
);
1704 rt
->rt_flags
&= ~RTF_UP
;
1707 * For consistency, in case the caller didn't set the flag.
1709 rt
->rt_flags
|= RTF_CONDEMNED
;
1712 * Now search what's left of the subtree for any cloned
1713 * routes which might have been formed from this node.
1715 if ((rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) &&
1718 rnh
->rnh_walktree_from(rnh
, dst
, rt_mask(rt
),
1724 * Remove any external references we may have.
1726 if ((gwrt
= rt
->rt_gwroute
) != NULL
)
1727 rt
->rt_gwroute
= NULL
;
1730 * give the protocol a chance to keep things in sync.
1732 if ((ifa
= rt
->rt_ifa
) != NULL
) {
1734 ifa_rtrequest
= ifa
->ifa_rtrequest
;
1736 if (ifa_rtrequest
!= NULL
)
1737 ifa_rtrequest(RTM_DELETE
, rt
, NULL
);
1738 /* keep reference on rt_ifa */
1743 * one more rtentry floating around that is not
1744 * linked to the routing table.
1746 (void) OSIncrementAtomic(&rttrash
);
1747 if (rte_debug
& RTD_DEBUG
) {
1748 TAILQ_INSERT_TAIL(&rttrash_head
,
1749 (struct rtentry_dbg
*)rt
, rtd_trash_link
);
1753 * If this is the (non-scoped) default route, clear
1754 * the interface index used for the primary ifscope.
1756 if (rt_primary_default(rt
, rt_key(rt
))) {
1757 set_primary_ifscope(rt_key(rt
)->sa_family
,
1760 rt_clear_idleref(rt
);
1765 * This might result in another rtentry being freed if
1766 * we held its last reference. Do this after the rtentry
1767 * lock is dropped above, as it could lead to the same
1768 * lock being acquired if gwrt is a clone of rt.
1771 rtfree_locked(gwrt
);
1774 * If the caller wants it, then it can have it,
1775 * but it's up to it to free the rtentry as we won't be
1778 if (ret_nrt
!= NULL
) {
1779 /* Return the route to caller with reference intact */
1782 /* Dereference or deallocate the route */
1788 if (ret_nrt
== NULL
|| (rt
= *ret_nrt
) == NULL
)
1791 * If cloning, we have the parent route given by the caller
1792 * and will use its rt_gateway, rt_rmx as part of the cloning
1793 * process below. Since rnh_lock is held at this point, the
1794 * parent's rt_ifa and rt_gateway will not change, and its
1795 * relevant rt_flags will not change as well. The only thing
1796 * that could change are the metrics, and thus we hold the
1797 * parent route's rt_lock later on during the actual copying
1802 flags
= rt
->rt_flags
&
1803 ~(RTF_CLONING
| RTF_PRCLONING
| RTF_STATIC
);
1804 flags
|= RTF_WASCLONED
;
1805 gateway
= rt
->rt_gateway
;
1806 if ((netmask
= rt
->rt_genmask
) == NULL
)
1810 if ((af
!= AF_INET
&& af
!= AF_INET6
) ||
1811 (af
== AF_INET
&& !ip_doscopedroute
) ||
1812 (af
== AF_INET6
&& !ip6_doscopedroute
))
1814 if (af
!= AF_INET
|| !ip_doscopedroute
)
1819 * When scoped routing is enabled, cloned entries are
1820 * always scoped according to the interface portion of
1821 * the parent route. The exception to this are IPv4
1822 * link local addresses.
1824 if (af
== AF_INET
&&
1825 IN_LINKLOCAL(ntohl(SIN(dst
)->sin_addr
.s_addr
))) {
1826 ifscope
= IFSCOPE_NONE
;
1827 flags
&= ~RTF_IFSCOPE
;
1829 if (flags
& RTF_IFSCOPE
) {
1830 ifscope
= (af
== AF_INET
) ?
1831 sin_get_ifscope(rt_key(rt
)) :
1832 sin6_get_ifscope(rt_key(rt
));
1834 ifscope
= rt
->rt_ifp
->if_index
;
1835 flags
|= RTF_IFSCOPE
;
1837 VERIFY(ifscope
!= IFSCOPE_NONE
);
1841 * Transform dst into the internal routing table form,
1842 * clearing out the scope ID field if ifscope isn't set.
1844 dst
= sa_copy(dst
, &ss
, (ifscope
== IFSCOPE_NONE
) ?
1847 /* Transform netmask into the internal routing table form */
1848 if (netmask
!= NULL
)
1849 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
1854 if ((flags
& RTF_GATEWAY
) && !gateway
)
1855 panic("rtrequest: RTF_GATEWAY but no gateway");
1857 if (flags
& RTF_IFSCOPE
) {
1858 ifa
= ifa_ifwithroute_scoped_locked(flags
, dst0
,
1861 ifa
= ifa_ifwithroute_locked(flags
, dst0
, gateway
);
1864 senderr(ENETUNREACH
);
1866 getmicrotime(&curr_calendartime
);
1867 if ((rt
= rte_alloc()) == NULL
)
1869 Bzero(rt
, sizeof(*rt
));
1871 rt
->base_calendartime
= curr_calendartime
.tv_sec
;
1872 rt
->base_uptime
= net_uptime();
1874 rt
->rt_flags
= RTF_UP
| flags
;
1877 * Add the gateway. Possibly re-malloc-ing the storage for it
1878 * also add the rt_gwroute if possible.
1880 if ((error
= rt_setgate(rt
, dst
, gateway
)) != 0) {
1882 nstat_route_detach(rt
);
1883 rte_lock_destroy(rt
);
1889 * point to the (possibly newly malloc'd) dest address.
1894 * make sure it contains the value we want (masked if needed).
1897 rt_maskedcopy(dst
, ndst
, netmask
);
1899 Bcopy(dst
, ndst
, dst
->sa_len
);
1902 * Note that we now have a reference to the ifa.
1903 * This moved from below so that rnh->rnh_addaddr() can
1904 * examine the ifa and ifa->ifa_ifp if it so desires.
1907 rt
->rt_ifp
= rt
->rt_ifa
->ifa_ifp
;
1909 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1911 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
, (caddr_t
)netmask
,
1914 struct rtentry
*rt2
;
1916 * Uh-oh, we already have one of these in the tree.
1917 * We do a special hack: if the route that's already
1918 * there was generated by the protocol-cloning
1919 * mechanism, then we just blow it away and retry
1920 * the insertion of the new one.
1922 if (flags
& RTF_IFSCOPE
) {
1923 rt2
= rtalloc1_scoped_locked(dst0
, 0,
1924 RTF_CLONING
| RTF_PRCLONING
, ifscope
);
1926 rt2
= rtalloc1_locked(dst
, 0,
1927 RTF_CLONING
| RTF_PRCLONING
);
1929 if (rt2
&& rt2
->rt_parent
) {
1931 * rnh_lock is held here, so rt_key and
1932 * rt_gateway of rt2 will not change.
1934 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt2
),
1935 rt2
->rt_gateway
, rt_mask(rt2
),
1938 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
,
1942 /* undo the extra ref we got */
1948 * If it still failed to go into the tree,
1949 * then un-make it (this should be a function)
1952 if (rt
->rt_gwroute
) {
1953 rtfree_locked(rt
->rt_gwroute
);
1954 rt
->rt_gwroute
= NULL
;
1957 IFA_REMREF(rt
->rt_ifa
);
1962 nstat_route_detach(rt
);
1963 rte_lock_destroy(rt
);
1968 rt
->rt_parent
= NULL
;
1971 * If we got here from RESOLVE, then we are cloning so clone
1972 * the rest, and note that we are a clone (and increment the
1973 * parent's references). rnh_lock is still held, which prevents
1974 * a lookup from returning the newly-created route. Hence
1975 * holding and releasing the parent's rt_lock while still
1976 * holding the route's rt_lock is safe since the new route
1977 * is not yet externally visible.
1979 if (req
== RTM_RESOLVE
) {
1980 RT_LOCK_SPIN(*ret_nrt
);
1981 VERIFY((*ret_nrt
)->rt_expire
== 0 || (*ret_nrt
)->rt_rmx
.rmx_expire
!= 0);
1982 VERIFY((*ret_nrt
)->rt_expire
!= 0 || (*ret_nrt
)->rt_rmx
.rmx_expire
== 0);
1983 rt
->rt_rmx
= (*ret_nrt
)->rt_rmx
;
1984 rt_setexpire(rt
, (*ret_nrt
)->rt_expire
);
1985 if ((*ret_nrt
)->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) {
1986 rt
->rt_parent
= (*ret_nrt
);
1987 RT_ADDREF_LOCKED(*ret_nrt
);
1989 RT_UNLOCK(*ret_nrt
);
1992 * Enable interface reference counting for unicast
1993 * cloned routes and bump up the reference count.
1995 if (rt
->rt_parent
!= NULL
&&
1996 !(rt
->rt_flags
& (RTF_BROADCAST
| RTF_MULTICAST
))) {
2002 * if this protocol has something to add to this then
2003 * allow it to do that as well.
2006 ifa_rtrequest
= ifa
->ifa_rtrequest
;
2008 if (ifa_rtrequest
!= NULL
)
2009 ifa_rtrequest(req
, rt
, SA(ret_nrt
? *ret_nrt
: NULL
));
2014 * If this is the (non-scoped) default route, record
2015 * the interface index used for the primary ifscope.
2017 if (rt_primary_default(rt
, rt_key(rt
))) {
2018 set_primary_ifscope(rt_key(rt
)->sa_family
,
2019 rt
->rt_ifp
->if_index
);
2023 * actually return a resultant rtentry and
2024 * give the caller a single reference.
2028 RT_ADDREF_LOCKED(rt
);
2032 * We repeat the same procedure from rt_setgate() here because
2033 * it doesn't fire when we call it there because the node
2034 * hasn't been added to the tree yet.
2036 if (req
== RTM_ADD
&&
2037 !(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != NULL
) {
2038 struct rtfc_arg arg
;
2042 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
2043 rt_fixchange
, &arg
);
2048 nstat_route_new_entry(rt
);
2058 rtrequest(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
2059 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
)
2062 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2063 lck_mtx_lock(rnh_lock
);
2064 error
= rtrequest_locked(req
, dst
, gateway
, netmask
, flags
, ret_nrt
);
2065 lck_mtx_unlock(rnh_lock
);
2070 rtrequest_scoped(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
2071 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
,
2072 unsigned int ifscope
)
2075 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2076 lck_mtx_lock(rnh_lock
);
2077 error
= rtrequest_scoped_locked(req
, dst
, gateway
, netmask
, flags
,
2079 lck_mtx_unlock(rnh_lock
);
2084 * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
2085 * (i.e., the routes related to it by the operation of cloning). This
2086 * routine is iterated over all potential former-child-routes by way of
2087 * rnh->rnh_walktree_from() above, and those that actually are children of
2088 * the late parent (passed in as VP here) are themselves deleted.
2091 rt_fixdelete(struct radix_node
*rn
, void *vp
)
2093 struct rtentry
*rt
= (struct rtentry
*)rn
;
2094 struct rtentry
*rt0
= vp
;
2096 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2099 if (rt
->rt_parent
== rt0
&&
2100 !(rt
->rt_flags
& (RTF_PINNED
| RTF_CLONING
| RTF_PRCLONING
))) {
2102 * Safe to drop rt_lock and use rt_key, since holding
2103 * rnh_lock here prevents another thread from calling
2104 * rt_setgate() on this route.
2107 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
2108 rt_mask(rt
), rt
->rt_flags
, NULL
));
2115 * This routine is called from rt_setgate() to do the analogous thing for
2116 * adds and changes. There is the added complication in this case of a
2117 * middle insert; i.e., insertion of a new network route between an older
2118 * network route and (cloned) host routes. For this reason, a simple check
2119 * of rt->rt_parent is insufficient; each candidate route must be tested
2120 * against the (mask, value) of the new route (passed as before in vp)
2121 * to see if the new route matches it.
2123 * XXX - it may be possible to do fixdelete() for changes and reserve this
2124 * routine just for adds. I'm not sure why I thought it was necessary to do
2128 rt_fixchange(struct radix_node
*rn
, void *vp
)
2130 struct rtentry
*rt
= (struct rtentry
*)rn
;
2131 struct rtfc_arg
*ap
= vp
;
2132 struct rtentry
*rt0
= ap
->rt0
;
2133 struct radix_node_head
*rnh
= ap
->rnh
;
2134 u_char
*xk1
, *xm1
, *xk2
, *xmp
;
2137 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2141 if (!rt
->rt_parent
||
2142 (rt
->rt_flags
& (RTF_PINNED
| RTF_CLONING
| RTF_PRCLONING
))) {
2147 if (rt
->rt_parent
== rt0
)
2151 * There probably is a function somewhere which does this...
2152 * if not, there should be.
2154 len
= imin(rt_key(rt0
)->sa_len
, rt_key(rt
)->sa_len
);
2156 xk1
= (u_char
*)rt_key(rt0
);
2157 xm1
= (u_char
*)rt_mask(rt0
);
2158 xk2
= (u_char
*)rt_key(rt
);
2161 * Avoid applying a less specific route; do this only if the parent
2162 * route (rt->rt_parent) is a network route, since otherwise its mask
2163 * will be NULL if it is a cloning host route.
2165 if ((xmp
= (u_char
*)rt_mask(rt
->rt_parent
)) != NULL
) {
2166 int mlen
= rt_mask(rt
->rt_parent
)->sa_len
;
2167 if (mlen
> rt_mask(rt0
)->sa_len
) {
2172 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< mlen
; i
++) {
2173 if ((xmp
[i
] & ~(xmp
[i
] ^ xm1
[i
])) != xmp
[i
]) {
2180 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< len
; i
++) {
2181 if ((xk2
[i
] & xm1
[i
]) != xk1
[i
]) {
2188 * OK, this node is a clone, and matches the node currently being
2189 * changed/added under the node's mask. So, get rid of it.
2193 * Safe to drop rt_lock and use rt_key, since holding rnh_lock here
2194 * prevents another thread from calling rt_setgate() on this route.
2197 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
2198 rt_mask(rt
), rt
->rt_flags
, NULL
));
2202 * Round up sockaddr len to multiples of 32-bytes. This will reduce
2203 * or even eliminate the need to re-allocate the chunk of memory used
2204 * for rt_key and rt_gateway in the event the gateway portion changes.
2205 * Certain code paths (e.g. IPSec) are notorious for caching the address
2206 * of rt_gateway; this rounding-up would help ensure that the gateway
2207 * portion never gets deallocated (though it may change contents) and
2208 * thus greatly simplifies things.
2210 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
2213 * Sets the gateway and/or gateway route portion of a route; may be
2214 * called on an existing route to modify the gateway portion. Both
2215 * rt_key and rt_gateway are allocated out of the same memory chunk.
2216 * Route entry lock must be held by caller; this routine will return
2217 * with the lock held.
2220 rt_setgate(struct rtentry
*rt
, struct sockaddr
*dst
, struct sockaddr
*gate
)
2222 int dlen
= SA_SIZE(dst
->sa_len
), glen
= SA_SIZE(gate
->sa_len
);
2223 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
2225 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2226 RT_LOCK_ASSERT_HELD(rt
);
2229 * If this is for a route that is on its way of being removed,
2230 * or is temporarily frozen, reject the modification request.
2232 if (rt
->rt_flags
& RTF_CONDEMNED
)
2235 /* Add an extra ref for ourselves */
2236 RT_ADDREF_LOCKED(rt
);
2239 * A host route with the destination equal to the gateway
2240 * will interfere with keeping LLINFO in the routing
2241 * table, so disallow it.
2243 if (((rt
->rt_flags
& (RTF_HOST
|RTF_GATEWAY
|RTF_LLINFO
)) ==
2244 (RTF_HOST
|RTF_GATEWAY
)) && (dst
->sa_len
== gate
->sa_len
) &&
2245 (bcmp(dst
, gate
, dst
->sa_len
) == 0)) {
2247 * The route might already exist if this is an RTM_CHANGE
2248 * or a routing redirect, so try to delete it.
2250 if (rt_key(rt
) != NULL
) {
2252 * Safe to drop rt_lock and use rt_key, rt_gateway,
2253 * since holding rnh_lock here prevents another thread
2254 * from calling rt_setgate() on this route.
2257 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt
),
2258 rt
->rt_gateway
, rt_mask(rt
), rt
->rt_flags
, NULL
);
2261 /* Release extra ref */
2262 RT_REMREF_LOCKED(rt
);
2263 return (EADDRNOTAVAIL
);
2267 * The destination is not directly reachable. Get a route
2268 * to the next-hop gateway and store it in rt_gwroute.
2270 if (rt
->rt_flags
& RTF_GATEWAY
) {
2271 struct rtentry
*gwrt
;
2272 unsigned int ifscope
;
2274 if (dst
->sa_family
== AF_INET
)
2275 ifscope
= sin_get_ifscope(dst
);
2276 else if (dst
->sa_family
== AF_INET6
)
2277 ifscope
= sin6_get_ifscope(dst
);
2279 ifscope
= IFSCOPE_NONE
;
2282 gwrt
= rtalloc1_scoped_locked(gate
, 1,
2283 RTF_CLONING
| RTF_PRCLONING
, ifscope
);
2285 RT_LOCK_ASSERT_NOTHELD(gwrt
);
2289 * Cloning loop avoidance:
2291 * In the presence of protocol-cloning and bad configuration,
2292 * it is possible to get stuck in bottomless mutual recursion
2293 * (rtrequest rt_setgate rtalloc1). We avoid this by not
2294 * allowing protocol-cloning to operate for gateways (which
2295 * is probably the correct choice anyway), and avoid the
2296 * resulting reference loops by disallowing any route to run
2297 * through itself as a gateway. This is obviously mandatory
2298 * when we get rt->rt_output(). It implies that a route to
2299 * the gateway must already be present in the system in order
2300 * for the gateway to be referred to by another route.
2303 RT_REMREF_LOCKED(gwrt
);
2304 /* Release extra ref */
2305 RT_REMREF_LOCKED(rt
);
2306 return (EADDRINUSE
); /* failure */
2310 * If scoped, the gateway route must use the same interface;
2311 * we're holding rnh_lock now, so rt_gateway and rt_ifp of gwrt
2312 * should not change and are freely accessible.
2314 if (ifscope
!= IFSCOPE_NONE
&& (rt
->rt_flags
& RTF_IFSCOPE
) &&
2315 gwrt
!= NULL
&& gwrt
->rt_ifp
!= NULL
&&
2316 gwrt
->rt_ifp
->if_index
!= ifscope
) {
2317 rtfree_locked(gwrt
); /* rt != gwrt, no deadlock */
2318 /* Release extra ref */
2319 RT_REMREF_LOCKED(rt
);
2320 return ((rt
->rt_flags
& RTF_HOST
) ?
2321 EHOSTUNREACH
: ENETUNREACH
);
2324 /* Check again since we dropped the lock above */
2325 if (rt
->rt_flags
& RTF_CONDEMNED
) {
2327 rtfree_locked(gwrt
);
2328 /* Release extra ref */
2329 RT_REMREF_LOCKED(rt
);
2333 if (rt
->rt_gwroute
!= NULL
)
2334 rtfree_locked(rt
->rt_gwroute
);
2335 rt
->rt_gwroute
= gwrt
;
2338 * In case the (non-scoped) default route gets modified via
2339 * an ICMP redirect, record the interface index used for the
2340 * primary ifscope. Also done in rt_setif() to take care
2341 * of the non-redirect cases.
2343 if (rt_primary_default(rt
, dst
) && rt
->rt_ifp
!= NULL
) {
2344 set_primary_ifscope(dst
->sa_family
,
2345 rt
->rt_ifp
->if_index
);
2349 * Tell the kernel debugger about the new default gateway
2350 * if the gateway route uses the primary interface, or
2351 * if we are in a transient state before the non-scoped
2352 * default gateway is installed (similar to how the system
2353 * was behaving in the past). In future, it would be good
2354 * to do all this only when KDP is enabled.
2356 if ((dst
->sa_family
== AF_INET
) &&
2357 gwrt
!= NULL
&& gwrt
->rt_gateway
->sa_family
== AF_LINK
&&
2358 (gwrt
->rt_ifp
->if_index
== get_primary_ifscope(AF_INET
) ||
2359 get_primary_ifscope(AF_INET
) == IFSCOPE_NONE
))
2360 kdp_set_gateway_mac(SDL(gwrt
->rt_gateway
)->sdl_data
);
2364 * Prepare to store the gateway in rt_gateway. Both dst and gateway
2365 * are stored one after the other in the same malloc'd chunk. If we
2366 * have room, reuse the old buffer since rt_gateway already points
2367 * to the right place. Otherwise, malloc a new block and update
2368 * the 'dst' address and point rt_gateway to the right place.
2370 if (rt
->rt_gateway
== NULL
|| glen
> SA_SIZE(rt
->rt_gateway
->sa_len
)) {
2373 /* The underlying allocation is done with M_WAITOK set */
2374 R_Malloc(new, caddr_t
, dlen
+ glen
);
2376 if (rt
->rt_gwroute
!= NULL
)
2377 rtfree_locked(rt
->rt_gwroute
);
2378 rt
->rt_gwroute
= NULL
;
2379 /* Release extra ref */
2380 RT_REMREF_LOCKED(rt
);
2385 * Copy from 'dst' and not rt_key(rt) because we can get
2386 * here to initialize a newly allocated route entry, in
2387 * which case rt_key(rt) is NULL (and so does rt_gateway).
2389 bzero(new, dlen
+ glen
);
2390 Bcopy(dst
, new, dst
->sa_len
);
2391 R_Free(rt_key(rt
)); /* free old block; NULL is okay */
2392 rt
->rt_nodes
->rn_key
= new;
2393 rt
->rt_gateway
= (struct sockaddr
*)(new + dlen
);
2397 * Copy the new gateway value into the memory chunk.
2399 Bcopy(gate
, rt
->rt_gateway
, gate
->sa_len
);
2402 * For consistency between rt_gateway and rt_key(gwrt).
2404 if ((rt
->rt_flags
& RTF_GATEWAY
) && rt
->rt_gwroute
!= NULL
&&
2405 (rt
->rt_gwroute
->rt_flags
& RTF_IFSCOPE
)) {
2406 if (rt
->rt_gateway
->sa_family
== AF_INET
&&
2407 rt_key(rt
->rt_gwroute
)->sa_family
== AF_INET
) {
2408 sin_set_ifscope(rt
->rt_gateway
,
2409 sin_get_ifscope(rt_key(rt
->rt_gwroute
)));
2410 } else if (rt
->rt_gateway
->sa_family
== AF_INET6
&&
2411 rt_key(rt
->rt_gwroute
)->sa_family
== AF_INET6
) {
2412 sin6_set_ifscope(rt
->rt_gateway
,
2413 sin6_get_ifscope(rt_key(rt
->rt_gwroute
)));
2418 * This isn't going to do anything useful for host routes, so
2419 * don't bother. Also make sure we have a reasonable mask
2420 * (we don't yet have one during adds).
2422 if (!(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != 0) {
2423 struct rtfc_arg arg
;
2427 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
2428 rt_fixchange
, &arg
);
2432 /* Release extra ref */
2433 RT_REMREF_LOCKED(rt
);
2440 rt_maskedcopy(struct sockaddr
*src
, struct sockaddr
*dst
,
2441 struct sockaddr
*netmask
)
2443 u_char
*cp1
= (u_char
*)src
;
2444 u_char
*cp2
= (u_char
*)dst
;
2445 u_char
*cp3
= (u_char
*)netmask
;
2446 u_char
*cplim
= cp2
+ *cp3
;
2447 u_char
*cplim2
= cp2
+ *cp1
;
2449 *cp2
++ = *cp1
++; *cp2
++ = *cp1
++; /* copies sa_len & sa_family */
2454 *cp2
++ = *cp1
++ & *cp3
++;
2456 bzero((caddr_t
)cp2
, (unsigned)(cplim2
- cp2
));
2460 * Lookup an AF_INET/AF_INET6 scoped or non-scoped route depending on the
2461 * ifscope value passed in by the caller (IFSCOPE_NONE implies non-scoped).
2463 static struct radix_node
*
2464 node_lookup(struct sockaddr
*dst
, struct sockaddr
*netmask
,
2465 unsigned int ifscope
)
2467 struct radix_node_head
*rnh
;
2468 struct radix_node
*rn
;
2469 struct sockaddr_storage ss
, mask
;
2470 int af
= dst
->sa_family
;
2471 struct matchleaf_arg ma
= { ifscope
};
2472 rn_matchf_t
*f
= rn_match_ifscope
;
2475 if (af
!= AF_INET
&& af
!= AF_INET6
)
2478 rnh
= rt_tables
[af
];
2481 * Transform dst into the internal routing table form,
2482 * clearing out the scope ID field if ifscope isn't set.
2484 dst
= sa_copy(dst
, &ss
, (ifscope
== IFSCOPE_NONE
) ? NULL
: &ifscope
);
2486 /* Transform netmask into the internal routing table form */
2487 if (netmask
!= NULL
)
2488 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
2490 if (ifscope
== IFSCOPE_NONE
)
2493 rn
= rnh
->rnh_lookup_args(dst
, netmask
, rnh
, f
, w
);
2494 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2501 * Lookup the AF_INET/AF_INET6 non-scoped default route.
2503 static struct radix_node
*
2504 node_lookup_default(int af
)
2506 struct radix_node_head
*rnh
;
2508 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
2509 rnh
= rt_tables
[af
];
2511 return (af
== AF_INET
? rnh
->rnh_lookup(&sin_def
, NULL
, rnh
) :
2512 rnh
->rnh_lookup(&sin6_def
, NULL
, rnh
));
2516 * Common routine to lookup/match a route. It invokes the lookup/matchaddr
2517 * callback which could be address family-specific. The main difference
2518 * between the two (at least for AF_INET/AF_INET6) is that a lookup does
2519 * not alter the expiring state of a route, whereas a match would unexpire
2520 * or revalidate the route.
2522 * The optional scope or interface index property of a route allows for a
2523 * per-interface route instance. This permits multiple route entries having
2524 * the same destination (but not necessarily the same gateway) to exist in
2525 * the routing table; each of these entries is specific to the corresponding
2526 * interface. This is made possible by storing the scope ID value into the
2527 * radix key, thus making each route entry unique. These scoped entries
2528 * exist along with the regular, non-scoped entries in the same radix tree
2529 * for a given address family (AF_INET/AF_INET6); the scope logically
2530 * partitions it into multiple per-interface sub-trees.
2532 * When a scoped route lookup is performed, the routing table is searched for
2533 * the best match that would result in a route using the same interface as the
2534 * one associated with the scope (the exception to this are routes that point
2535 * to the loopback interface). The search rule follows the longest matching
2536 * prefix with the additional interface constraint.
2539 rt_lookup(boolean_t lookup_only
, struct sockaddr
*dst
, struct sockaddr
*netmask
,
2540 struct radix_node_head
*rnh
, unsigned int ifscope
)
2542 struct radix_node
*rn0
, *rn
;
2544 int af
= dst
->sa_family
;
2545 struct sockaddr_storage dst_ss
, mask_ss
;
2547 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2553 * Non-scoped route lookup.
2556 if ((af
!= AF_INET
&& af
!= AF_INET6
) ||
2557 (af
== AF_INET
&& !ip_doscopedroute
) ||
2558 (af
== AF_INET6
&& !ip6_doscopedroute
)) {
2560 if (af
!= AF_INET
|| !ip_doscopedroute
) {
2562 rn
= rnh
->rnh_matchaddr(dst
, rnh
);
2565 * Don't return a root node; also, rnh_matchaddr callback
2566 * would have done the necessary work to clear RTPRF_OURS
2567 * for certain protocol families.
2569 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2572 RT_LOCK_SPIN(RT(rn
));
2573 if (!(RT(rn
)->rt_flags
& RTF_CONDEMNED
)) {
2574 RT_ADDREF_LOCKED(RT(rn
));
2584 /* Transform dst/netmask into the internal routing table form */
2585 dst
= sa_copy(dst
, &dst_ss
, &ifscope
);
2586 if (netmask
!= NULL
)
2587 netmask
= ma_copy(af
, netmask
, &mask_ss
, ifscope
);
2588 dontcare
= (ifscope
== IFSCOPE_NONE
);
2591 * Scoped route lookup:
2593 * We first perform a non-scoped lookup for the original result.
2594 * Afterwards, depending on whether or not the caller has specified
2595 * a scope, we perform a more specific scoped search and fallback
2596 * to this original result upon failure.
2598 rn0
= rn
= node_lookup(dst
, netmask
, IFSCOPE_NONE
);
2601 * If the caller did not specify a scope, use the primary scope
2602 * derived from the system's non-scoped default route. If, for
2603 * any reason, there is no primary interface, ifscope will be
2604 * set to IFSCOPE_NONE; if the above lookup resulted in a route,
2605 * we'll do a more-specific search below, scoped to the interface
2609 ifscope
= get_primary_ifscope(af
);
2612 * Keep the original result if either of the following is true:
2614 * 1) The interface portion of the route has the same interface
2615 * index as the scope value and it is marked with RTF_IFSCOPE.
2616 * 2) The route uses the loopback interface, in which case the
2617 * destination (host/net) is local/loopback.
2619 * Otherwise, do a more specified search using the scope;
2620 * we're holding rnh_lock now, so rt_ifp should not change.
2623 struct rtentry
*rt
= RT(rn
);
2624 if (rt
->rt_ifp
!= lo_ifp
) {
2625 if (rt
->rt_ifp
->if_index
!= ifscope
) {
2627 * Wrong interface; keep the original result
2628 * only if the caller did not specify a scope,
2629 * and do a more specific scoped search using
2630 * the scope of the found route. Otherwise,
2631 * start again from scratch.
2635 ifscope
= rt
->rt_ifp
->if_index
;
2638 } else if (!(rt
->rt_flags
& RTF_IFSCOPE
)) {
2640 * Right interface, except that this route
2641 * isn't marked with RTF_IFSCOPE. Do a more
2642 * specific scoped search. Keep the original
2643 * result and return it it in case the scoped
2652 * Scoped search. Find the most specific entry having the same
2653 * interface scope as the one requested. The following will result
2654 * in searching for the longest prefix scoped match.
2657 rn
= node_lookup(dst
, netmask
, ifscope
);
2660 * Use the original result if either of the following is true:
2662 * 1) The scoped search did not yield any result.
2663 * 2) The result from the scoped search is a scoped default route,
2664 * and the original (non-scoped) result is not a default route,
2665 * i.e. the original result is a more specific host/net route.
2666 * 3) The scoped search yielded a net route but the original
2667 * result is a host route, i.e. the original result is treated
2668 * as a more specific route.
2670 if (rn
== NULL
|| (rn0
!= NULL
&&
2671 ((SA_DEFAULT(rt_key(RT(rn
))) && !SA_DEFAULT(rt_key(RT(rn0
)))) ||
2672 (!RT_HOST(rn
) && RT_HOST(rn0
)))))
2676 * If we still don't have a route, use the non-scoped default
2677 * route as long as the interface portion satistifes the scope.
2679 if (rn
== NULL
&& (rn
= node_lookup_default(af
)) != NULL
&&
2680 RT(rn
)->rt_ifp
->if_index
!= ifscope
)
2685 * Manually clear RTPRF_OURS using rt_validate() and
2686 * bump up the reference count after, and not before;
2687 * we only get here for AF_INET/AF_INET6. node_lookup()
2688 * has done the check against RNF_ROOT, so we can be sure
2689 * that we're not returning a root node here.
2691 RT_LOCK_SPIN(RT(rn
));
2692 if (rt_validate(RT(rn
))) {
2693 RT_ADDREF_LOCKED(RT(rn
));
2705 rt_validate(struct rtentry
*rt
)
2707 RT_LOCK_ASSERT_HELD(rt
);
2709 if (!(rt
->rt_flags
& RTF_CONDEMNED
)) {
2710 int af
= rt_key(rt
)->sa_family
;
2713 (void) in_validate(RN(rt
));
2714 else if (af
== AF_INET6
)
2715 (void) in6_validate(RN(rt
));
2720 return (rt
!= NULL
);
2724 * Set up a routing table entry, normally
2728 rtinit(struct ifaddr
*ifa
, int cmd
, int flags
)
2731 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2732 lck_mtx_lock(rnh_lock
);
2733 error
= rtinit_locked(ifa
, cmd
, flags
);
2734 lck_mtx_unlock(rnh_lock
);
2739 rtinit_locked(struct ifaddr
*ifa
, int cmd
, int flags
)
2742 struct sockaddr
*dst
;
2743 struct sockaddr
*deldst
;
2745 struct rtentry
*nrt
= 0;
2746 u_int32_t ifa_flags
;
2750 * Holding rnh_lock here prevents the possibility of ifa from
2751 * changing (e.g. in_ifinit), so it is safe to access its
2752 * ifa_{dst}addr (here and down below) without locking.
2754 dst
= flags
& RTF_HOST
? ifa
->ifa_dstaddr
: ifa
->ifa_addr
;
2756 * If it's a delete, check that if it exists, it's on the correct
2757 * interface or we might scrub a route to another ifa which would
2758 * be confusing at best and possibly worse.
2760 if (cmd
== RTM_DELETE
) {
2762 * It's a delete, so it should already exist..
2763 * If it's a net, mask off the host bits
2764 * (Assuming we have a mask)
2766 if ((flags
& RTF_HOST
) == 0 && ifa
->ifa_netmask
) {
2767 m
= m_get(M_DONTWAIT
, MT_SONAME
);
2771 deldst
= mtod(m
, struct sockaddr
*);
2772 rt_maskedcopy(dst
, deldst
, ifa
->ifa_netmask
);
2776 * Get an rtentry that is in the routing tree and
2777 * contains the correct info. (if this fails, can't get there).
2778 * We set "report" to FALSE so that if it doesn't exist,
2779 * it doesn't report an error or clone a route, etc. etc.
2781 rt
= rtalloc1_locked(dst
, 0, 0);
2784 * Ok so we found the rtentry. it has an extra reference
2785 * for us at this stage. we won't need that so
2789 if (rt
->rt_ifa
!= ifa
) {
2790 RT_REMREF_LOCKED(rt
);
2793 * If the interface in the rtentry doesn't match
2794 * the interface we are using, then we don't
2795 * want to delete it, so return an error.
2796 * This seems to be the only point of
2797 * this whole RTM_DELETE clause.
2801 return (flags
& RTF_HOST
? EHOSTUNREACH
2804 RT_REMREF_LOCKED(rt
);
2812 * One would think that as we are deleting, and we know
2813 * it doesn't exist, we could just return at this point
2814 * with an "ELSE" clause, but apparently not..
2816 lck_mtx_unlock(rnh_lock
);
2817 return (flags
& RTF_HOST
? EHOSTUNREACH
2823 * Do the actual request
2826 ifa_flags
= ifa
->ifa_flags
;
2828 error
= rtrequest_locked(cmd
, dst
, ifa
->ifa_addr
, ifa
->ifa_netmask
,
2829 flags
| ifa_flags
, &nrt
);
2833 * If we are deleting, and we found an entry, then
2834 * it's been removed from the tree.. now throw it away.
2836 if (cmd
== RTM_DELETE
&& error
== 0 && (rt
= nrt
)) {
2838 * notify any listening routing agents of the change
2841 rt_newaddrmsg(cmd
, ifa
, error
, nrt
);
2843 routegenid_update();
2849 * We are adding, and we have a returned routing entry.
2850 * We need to sanity check the result.
2852 if (cmd
== RTM_ADD
&& error
== 0 && (rt
= nrt
)) {
2855 * If it came back with an unexpected interface, then it must
2856 * have already existed or something. (XXX)
2858 if (rt
->rt_ifa
!= ifa
) {
2859 void (*ifa_rtrequest
)
2860 (int, struct rtentry
*, struct sockaddr
*);
2862 if (!(rt
->rt_ifa
->ifa_ifp
->if_flags
&
2863 (IFF_POINTOPOINT
|IFF_LOOPBACK
)))
2864 printf("rtinit: wrong ifa (%p) was (%p)\n",
2867 * Ask that the protocol in question
2868 * remove anything it has associated with
2869 * this route and ifaddr.
2871 IFA_LOCK_SPIN(rt
->rt_ifa
);
2872 ifa_rtrequest
= rt
->rt_ifa
->ifa_rtrequest
;
2873 IFA_UNLOCK(rt
->rt_ifa
);
2874 if (ifa_rtrequest
!= NULL
)
2875 ifa_rtrequest(RTM_DELETE
, rt
, SA(0));
2877 * Set the route's ifa.
2881 if (rt
->rt_ifp
!= ifa
->ifa_ifp
) {
2883 * Purge any link-layer info caching.
2885 if (rt
->rt_llinfo_purge
!= NULL
)
2886 rt
->rt_llinfo_purge(rt
);
2888 * Adjust route ref count for the interfaces.
2890 if (rt
->rt_if_ref_fn
!= NULL
) {
2891 rt
->rt_if_ref_fn(ifa
->ifa_ifp
, 1);
2892 rt
->rt_if_ref_fn(rt
->rt_ifp
, -1);
2897 * And substitute in references to the ifaddr
2900 rt
->rt_ifp
= ifa
->ifa_ifp
;
2901 rt
->rt_rmx
.rmx_mtu
= ifa
->ifa_ifp
->if_mtu
; /*XXX*/
2903 * Now ask the protocol to check if it needs
2904 * any special processing in its new form.
2907 ifa_rtrequest
= ifa
->ifa_rtrequest
;
2909 if (ifa_rtrequest
!= NULL
)
2910 ifa_rtrequest(RTM_ADD
, rt
, SA(0));
2913 * notify any listenning routing agents of the change
2915 rt_newaddrmsg(cmd
, ifa
, error
, nrt
);
2917 routegenid_update();
2919 * We just wanted to add it; we don't actually need a
2920 * reference. This will result in a route that's added
2921 * to the routing table without a reference count. The
2922 * RTM_DELETE code will do the necessary step to adjust
2923 * the reference count at deletion time.
2925 RT_REMREF_LOCKED(rt
);
2932 rt_expiry(struct rtentry
*rt
, u_int64_t base
, u_int32_t delta
)
2937 * If the interface of the route doesn't demand aggressive draining,
2938 * return the expiration time based on the caller-supplied delta.
2939 * Otherwise use the more aggressive route expiration delta (or
2940 * the caller-supplied delta, whichever is less.)
2942 if (rt
->rt_ifp
== NULL
|| rt
->rt_ifp
->if_want_aggressive_drain
== 0)
2943 retval
= base
+ delta
;
2945 retval
= base
+ MIN(rt_if_idle_expire_timeout
, delta
);
2951 rt_set_idleref(struct rtentry
*rt
)
2953 RT_LOCK_ASSERT_HELD(rt
);
2955 rt_clear_idleref(rt
);
2956 rt
->rt_if_ref_fn
= rte_if_ref
;
2957 rt
->rt_if_ref_fn(rt
->rt_ifp
, 1);
2958 rt
->rt_flags
|= RTF_IFREF
;
2962 rt_clear_idleref(struct rtentry
*rt
)
2964 RT_LOCK_ASSERT_HELD(rt
);
2966 if (rt
->rt_if_ref_fn
!= NULL
) {
2967 rt
->rt_if_ref_fn(rt
->rt_ifp
, -1);
2968 rt
->rt_flags
&= ~RTF_IFREF
;
2969 rt
->rt_if_ref_fn
= NULL
;
2974 rte_lock_init(struct rtentry
*rt
)
2976 lck_mtx_init(&rt
->rt_lock
, rte_mtx_grp
, rte_mtx_attr
);
2980 rte_lock_destroy(struct rtentry
*rt
)
2982 RT_LOCK_ASSERT_NOTHELD(rt
);
2983 lck_mtx_destroy(&rt
->rt_lock
, rte_mtx_grp
);
2987 rt_lock(struct rtentry
*rt
, boolean_t spin
)
2989 RT_LOCK_ASSERT_NOTHELD(rt
);
2991 lck_mtx_lock_spin(&rt
->rt_lock
);
2993 lck_mtx_lock(&rt
->rt_lock
);
2994 if (rte_debug
& RTD_DEBUG
)
2995 rte_lock_debug((struct rtentry_dbg
*)rt
);
2999 rt_unlock(struct rtentry
*rt
)
3001 RT_LOCK_ASSERT_HELD(rt
);
3002 if (rte_debug
& RTD_DEBUG
)
3003 rte_unlock_debug((struct rtentry_dbg
*)rt
);
3004 lck_mtx_unlock(&rt
->rt_lock
);
3009 rte_lock_debug(struct rtentry_dbg
*rte
)
3013 idx
= atomic_add_32_ov(&rte
->rtd_lock_cnt
, 1) % CTRACE_HIST_SIZE
;
3014 if (rte_debug
& RTD_TRACE
)
3015 ctrace_record(&rte
->rtd_lock
[idx
]);
3019 rte_unlock_debug(struct rtentry_dbg
*rte
)
3023 idx
= atomic_add_32_ov(&rte
->rtd_unlock_cnt
, 1) % CTRACE_HIST_SIZE
;
3024 if (rte_debug
& RTD_TRACE
)
3025 ctrace_record(&rte
->rtd_unlock
[idx
]);
3028 static struct rtentry
*
3031 if (rte_debug
& RTD_DEBUG
)
3032 return (rte_alloc_debug());
3034 return ((struct rtentry
*)zalloc(rte_zone
));
3038 rte_free(struct rtentry
*p
)
3040 if (rte_debug
& RTD_DEBUG
) {
3045 if (p
->rt_refcnt
!= 0)
3046 panic("rte_free: rte=%p refcnt=%d non-zero\n", p
, p
->rt_refcnt
);
3052 rte_if_ref(struct ifnet
*ifp
, int cnt
)
3054 struct kev_msg ev_msg
;
3055 struct net_event_data ev_data
;
3058 /* Force cnt to 1 increment/decrement */
3059 if (cnt
< -1 || cnt
> 1)
3060 panic("%s: invalid count argument (%d)", __func__
, cnt
);
3062 old
= atomic_add_32_ov(&ifp
->if_route_refcnt
, cnt
);
3063 if (cnt
< 0 && old
== 0)
3064 panic("%s: ifp=%p negative route refcnt!", __func__
, ifp
);
3067 * The following is done without first holding the ifnet lock,
3068 * for performance reasons. The relevant ifnet fields, with
3069 * the exception of the if_idle_flags, are never changed
3070 * during the lifetime of the ifnet. The if_idle_flags
3071 * may possibly be modified, so in the event that the value
3072 * is stale because IFRF_IDLE_NOTIFY was cleared, we'd end up
3073 * sending the event anyway. This is harmless as it is just
3074 * a notification to the monitoring agent in user space, and
3075 * it is expected to check via SIOCGIFGETRTREFCNT again anyway.
3077 if ((ifp
->if_idle_flags
& IFRF_IDLE_NOTIFY
) && cnt
< 0 && old
== 1) {
3078 bzero(&ev_msg
, sizeof (ev_msg
));
3079 bzero(&ev_data
, sizeof (ev_data
));
3081 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
3082 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
3083 ev_msg
.kev_subclass
= KEV_DL_SUBCLASS
;
3084 ev_msg
.event_code
= KEV_DL_IF_IDLE_ROUTE_REFCNT
;
3086 strlcpy(&ev_data
.if_name
[0], ifp
->if_name
, IFNAMSIZ
);
3088 ev_data
.if_family
= ifp
->if_family
;
3089 ev_data
.if_unit
= ifp
->if_unit
;
3090 ev_msg
.dv
[0].data_length
= sizeof (struct net_event_data
);
3091 ev_msg
.dv
[0].data_ptr
= &ev_data
;
3093 kev_post_msg(&ev_msg
);
3097 static inline struct rtentry
*
3098 rte_alloc_debug(void)
3100 struct rtentry_dbg
*rte
;
3102 rte
= ((struct rtentry_dbg
*)zalloc(rte_zone
));
3104 bzero(rte
, sizeof (*rte
));
3105 if (rte_debug
& RTD_TRACE
)
3106 ctrace_record(&rte
->rtd_alloc
);
3107 rte
->rtd_inuse
= RTD_INUSE
;
3109 return ((struct rtentry
*)rte
);
3113 rte_free_debug(struct rtentry
*p
)
3115 struct rtentry_dbg
*rte
= (struct rtentry_dbg
*)p
;
3117 if (p
->rt_refcnt
!= 0)
3118 panic("rte_free: rte=%p refcnt=%d\n", p
, p
->rt_refcnt
);
3120 if (rte
->rtd_inuse
== RTD_FREED
)
3121 panic("rte_free: double free rte=%p\n", rte
);
3122 else if (rte
->rtd_inuse
!= RTD_INUSE
)
3123 panic("rte_free: corrupted rte=%p\n", rte
);
3125 bcopy((caddr_t
)p
, (caddr_t
)&rte
->rtd_entry_saved
, sizeof (*p
));
3126 /* Preserve rt_lock to help catch use-after-free cases */
3127 bzero((caddr_t
)p
, offsetof(struct rtentry
, rt_lock
));
3129 rte
->rtd_inuse
= RTD_FREED
;
3131 if (rte_debug
& RTD_TRACE
)
3132 ctrace_record(&rte
->rtd_free
);
3134 if (!(rte_debug
& RTD_NO_FREE
))
3139 ctrace_record(ctrace_t
*tr
)
3141 tr
->th
= current_thread();
3142 bzero(tr
->pc
, sizeof (tr
->pc
));
3143 (void) OSBacktrace(tr
->pc
, CTRACE_STACK_SIZE
);
3146 __private_extern__
void
3149 const struct route
*src
,
3152 /* Copy everything (rt, dst, flags) from ifnet */
3153 bcopy(src
, dst
, length
);
3155 /* Hold one reference for the local copy of struct route */
3156 if (dst
->ro_rt
!= NULL
)
3157 RT_ADDREF(dst
->ro_rt
);
3160 __private_extern__
void
3166 /* No cached route in the ifnet? */
3167 if (dst
->ro_rt
== NULL
) {
3169 * Copy everything (rt, dst, flags) from ip_forward();
3170 * the reference to the route was held at the time
3171 * it was allocated and is kept intact.
3173 bcopy(src
, dst
, length
);
3174 } else if (src
->ro_rt
!= NULL
) {
3176 * If the same, update just the ro_flags and ditch the one
3177 * in the local copy. Else ditch the one that is currently
3178 * cached, and cache the new route.
3180 if (dst
->ro_rt
== src
->ro_rt
) {
3181 dst
->ro_flags
= src
->ro_flags
;
3185 bcopy(src
, dst
, length
);
3189 /* This function consumes the reference */