2 * Copyright (c) 2000-2012 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 decl_lck_mtx_data(,rnh_lock_data
); /* global routing tables mutex */
208 lck_mtx_t
*rnh_lock
= &rnh_lock_data
;
209 static lck_attr_t
*rnh_lock_attr
;
210 static lck_grp_t
*rnh_lock_grp
;
211 static lck_grp_attr_t
*rnh_lock_grp_attr
;
213 /* Lock group and attribute for routing entry locks */
214 static lck_attr_t
*rte_mtx_attr
;
215 static lck_grp_t
*rte_mtx_grp
;
216 static lck_grp_attr_t
*rte_mtx_grp_attr
;
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 SINIFSCOPE(sa) ((struct sockaddr_inifscope *)(size_t)(sa))
341 #define SIN6IFSCOPE(sa) SIN6(sa)
343 #define ASSERT_SINIFSCOPE(sa) { \
344 if ((sa)->sa_family != AF_INET || \
345 (sa)->sa_len < sizeof (struct sockaddr_in)) \
346 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
349 #define ASSERT_SIN6IFSCOPE(sa) { \
350 if ((sa)->sa_family != AF_INET6 || \
351 (sa)->sa_len < sizeof (struct sockaddr_in6)) \
352 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
356 * Argument to leaf-matching routine; at present it is scoped routing
357 * specific but can be expanded in future to include other search filters.
359 struct matchleaf_arg
{
360 unsigned int ifscope
; /* interface scope */
364 * For looking up the non-scoped default route (sockaddr instead
365 * of sockaddr_in for convenience).
367 static struct sockaddr sin_def
= {
368 sizeof (struct sockaddr_in
), AF_INET
, { 0, }
371 static struct sockaddr_in6 sin6_def
= {
372 sizeof (struct sockaddr_in6
), AF_INET6
, 0, 0, IN6ADDR_ANY_INIT
, 0
376 * Interface index (scope) of the primary interface; determined at
377 * the time when the default, non-scoped route gets added, changed
378 * or deleted. Protected by rnh_lock.
380 static unsigned int primary_ifscope
= IFSCOPE_NONE
;
381 static unsigned int primary6_ifscope
= IFSCOPE_NONE
;
383 #define INET_DEFAULT(sa) \
384 ((sa)->sa_family == AF_INET && SIN(sa)->sin_addr.s_addr == 0)
386 #define INET6_DEFAULT(sa) \
387 ((sa)->sa_family == AF_INET6 && \
388 IN6_IS_ADDR_UNSPECIFIED(&SIN6(sa)->sin6_addr))
390 #define SA_DEFAULT(sa) (INET_DEFAULT(sa) || INET6_DEFAULT(sa))
391 #define RT(r) ((struct rtentry *)r)
392 #define RN(r) ((struct radix_node *)r)
393 #define RT_HOST(r) (RT(r)->rt_flags & RTF_HOST)
395 SYSCTL_DECL(_net_idle_route
);
397 static int rt_if_idle_expire_timeout
= RT_IF_IDLE_EXPIRE_TIMEOUT
;
398 SYSCTL_INT(_net_idle_route
, OID_AUTO
, expire_timeout
, CTLFLAG_RW
|CTLFLAG_LOCKED
,
399 &rt_if_idle_expire_timeout
, 0, "Default expiration time on routes for "
400 "interface idle reference counting");
403 * Given a route, determine whether or not it is the non-scoped default
404 * route; dst typically comes from rt_key(rt) but may be coming from
405 * a separate place when rt is in the process of being created.
408 rt_primary_default(struct rtentry
*rt
, struct sockaddr
*dst
)
410 return (SA_DEFAULT(dst
) && !(rt
->rt_flags
& RTF_IFSCOPE
));
414 * Set the ifscope of the primary interface; caller holds rnh_lock.
417 set_primary_ifscope(int af
, unsigned int ifscope
)
420 primary_ifscope
= ifscope
;
422 primary6_ifscope
= ifscope
;
426 * Return the ifscope of the primary interface; caller holds rnh_lock.
429 get_primary_ifscope(int af
)
431 return (af
== AF_INET
? primary_ifscope
: primary6_ifscope
);
435 * Set the scope ID of a given a sockaddr_in.
438 sin_set_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
440 /* Caller must pass in sockaddr_in */
441 ASSERT_SINIFSCOPE(sa
);
443 SINIFSCOPE(sa
)->sin_scope_id
= ifscope
;
447 * Set the scope ID of given a sockaddr_in6.
450 sin6_set_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
452 /* Caller must pass in sockaddr_in6 */
453 ASSERT_SIN6IFSCOPE(sa
);
455 SIN6IFSCOPE(sa
)->sin6_scope_id
= ifscope
;
459 * Given a sockaddr_in, return the scope ID to the caller.
462 sin_get_ifscope(struct sockaddr
*sa
)
464 /* Caller must pass in sockaddr_in */
465 ASSERT_SINIFSCOPE(sa
);
467 return (SINIFSCOPE(sa
)->sin_scope_id
);
471 * Given a sockaddr_in6, return the scope ID to the caller.
474 sin6_get_ifscope(struct sockaddr
*sa
)
476 /* Caller must pass in sockaddr_in6 */
477 ASSERT_SIN6IFSCOPE(sa
);
479 return (SIN6IFSCOPE(sa
)->sin6_scope_id
);
483 sin6_set_embedded_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
485 /* Caller must pass in sockaddr_in6 */
486 ASSERT_SIN6IFSCOPE(sa
);
487 VERIFY(IN6_IS_SCOPE_EMBED(&(SIN6(sa
)->sin6_addr
)));
489 SIN6(sa
)->sin6_addr
.s6_addr16
[1] = htons(ifscope
);
492 static inline unsigned int
493 sin6_get_embedded_ifscope(struct sockaddr
*sa
)
495 /* Caller must pass in sockaddr_in6 */
496 ASSERT_SIN6IFSCOPE(sa
);
498 return (ntohs(SIN6(sa
)->sin6_addr
.s6_addr16
[1]));
502 * Copy a sockaddr_{in,in6} src to a dst storage and set scope ID into dst.
504 * To clear the scope ID, pass is a NULL pifscope. To set the scope ID, pass
505 * in a non-NULL pifscope with non-zero ifscope. Otherwise if pifscope is
506 * non-NULL and ifscope is IFSCOPE_NONE, the existing scope ID is left intact.
507 * In any case, the effective scope ID value is returned to the caller via
508 * pifscope, if it is non-NULL.
510 static struct sockaddr
*
511 sa_copy(struct sockaddr
*src
, struct sockaddr_storage
*dst
,
512 unsigned int *pifscope
)
514 int af
= src
->sa_family
;
515 unsigned int ifscope
= (pifscope
!= NULL
) ? *pifscope
: IFSCOPE_NONE
;
517 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
519 bzero(dst
, sizeof (*dst
));
522 bcopy(src
, dst
, sizeof (struct sockaddr_in
));
523 if (pifscope
== NULL
|| ifscope
!= IFSCOPE_NONE
)
524 sin_set_ifscope(SA(dst
), ifscope
);
526 bcopy(src
, dst
, sizeof (struct sockaddr_in6
));
527 if (pifscope
!= NULL
&&
528 IN6_IS_SCOPE_EMBED(&SIN6(dst
)->sin6_addr
)) {
529 unsigned int eifscope
;
531 * If the address contains the embedded scope ID,
532 * use that as the value for sin6_scope_id as long
533 * the caller doesn't insist on clearing it (by
534 * passing NULL) or setting it.
536 eifscope
= sin6_get_embedded_ifscope(SA(dst
));
537 if (eifscope
!= IFSCOPE_NONE
&& ifscope
== IFSCOPE_NONE
)
539 sin6_set_ifscope(SA(dst
), ifscope
);
541 * If sin6_scope_id is set but the address doesn't
542 * contain the equivalent embedded value, set it.
544 if (ifscope
!= IFSCOPE_NONE
&& eifscope
!= ifscope
)
545 sin6_set_embedded_ifscope(SA(dst
), ifscope
);
546 } else if (pifscope
== NULL
|| ifscope
!= IFSCOPE_NONE
) {
547 sin6_set_ifscope(SA(dst
), ifscope
);
551 if (pifscope
!= NULL
) {
552 *pifscope
= (af
== AF_INET
) ? sin_get_ifscope(SA(dst
)) :
553 sin6_get_ifscope(SA(dst
));
560 * Copy a mask from src to a dst storage and set scope ID into dst.
562 static struct sockaddr
*
563 ma_copy(int af
, struct sockaddr
*src
, struct sockaddr_storage
*dst
,
564 unsigned int ifscope
)
566 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
568 bzero(dst
, sizeof (*dst
));
569 rt_maskedcopy(src
, SA(dst
), src
);
572 * The length of the mask sockaddr would need to be adjusted
573 * to cover the additional {sin,sin6}_ifscope field; when ifscope
574 * is IFSCOPE_NONE, we'd end up clearing the scope ID field on
575 * the destination mask in addition to extending the length
576 * of the sockaddr, as a side effect. This is okay, as any
577 * trailing zeroes would be skipped by rn_addmask prior to
578 * inserting or looking up the mask in the mask tree.
581 SINIFSCOPE(dst
)->sin_scope_id
= ifscope
;
582 SINIFSCOPE(dst
)->sin_len
=
583 offsetof(struct sockaddr_inifscope
, sin_scope_id
) +
584 sizeof (SINIFSCOPE(dst
)->sin_scope_id
);
586 SIN6IFSCOPE(dst
)->sin6_scope_id
= ifscope
;
587 SIN6IFSCOPE(dst
)->sin6_len
=
588 offsetof(struct sockaddr_in6
, sin6_scope_id
) +
589 sizeof (SIN6IFSCOPE(dst
)->sin6_scope_id
);
596 * Trim trailing zeroes on a sockaddr and update its length.
598 static struct sockaddr
*
599 sa_trim(struct sockaddr
*sa
, int skip
)
601 caddr_t cp
, base
= (caddr_t
)sa
+ skip
;
603 if (sa
->sa_len
<= skip
)
606 for (cp
= base
+ (sa
->sa_len
- skip
); cp
> base
&& cp
[-1] == 0;)
609 sa
->sa_len
= (cp
- base
) + skip
;
610 if (sa
->sa_len
< skip
) {
611 /* Must not happen, and if so, panic */
612 panic("%s: broken logic (sa_len %d < skip %d )", __func__
,
615 } else if (sa
->sa_len
== skip
) {
616 /* If we end up with all zeroes, then there's no mask */
624 * Called by rtm_msg{1,2} routines to "scrub" the scope ID field away from
625 * the socket address structure, so that clients of the routing socket will
626 * not be confused by the presence of the information, or the side effect of
627 * the increased length due to that. The source sockaddr is not modified;
628 * instead, the scrubbing happens on the destination sockaddr storage that
629 * is passed in by the caller.
632 rtm_scrub_ifscope(int type
, int idx
, struct sockaddr
*hint
, struct sockaddr
*sa
,
633 struct sockaddr_storage
*ss
)
635 struct sockaddr
*ret
= sa
;
640 * If this is for an AF_INET/AF_INET6 destination address,
641 * call sa_copy() to clear the scope ID field.
643 if (sa
->sa_family
== AF_INET
&&
644 SINIFSCOPE(sa
)->sin_scope_id
!= IFSCOPE_NONE
) {
645 ret
= sa_copy(sa
, ss
, NULL
);
646 } else if (sa
->sa_family
== AF_INET6
&&
647 SIN6IFSCOPE(sa
)->sin6_scope_id
!= IFSCOPE_NONE
) {
648 ret
= sa_copy(sa
, ss
, NULL
);
655 * If this is for a mask, we can't tell whether or not there
656 * is an valid scope ID value, as the span of bytes between
657 * sa_len and the beginning of the mask (offset of sin_addr in
658 * the case of AF_INET, or sin6_addr for AF_INET6) may be
659 * filled with all-ones by rn_addmask(), and hence we cannot
660 * rely on sa_family. Because of this, we use the sa_family
661 * of the hint sockaddr (RTAX_{DST,IFA}) as indicator as to
662 * whether or not the mask is to be treated as one for AF_INET
663 * or AF_INET6. Clearing the scope ID field involves setting
664 * it to IFSCOPE_NONE followed by calling sa_trim() to trim
665 * trailing zeroes from the storage sockaddr, which reverses
666 * what was done earlier by ma_copy() on the source sockaddr.
669 ((af
= hint
->sa_family
) != AF_INET
&& af
!= AF_INET6
))
670 break; /* nothing to do */
672 skip
= (af
== AF_INET
) ?
673 offsetof(struct sockaddr_in
, sin_addr
) :
674 offsetof(struct sockaddr_in6
, sin6_addr
);
676 if (sa
->sa_len
> skip
&& sa
->sa_len
<= sizeof (*ss
)) {
677 bzero(ss
, sizeof (*ss
));
678 bcopy(sa
, ss
, sa
->sa_len
);
680 * Don't use {sin,sin6}_set_ifscope() as sa_family
681 * and sa_len for the netmask might not be set to
682 * the corresponding expected values of the hint.
684 if (hint
->sa_family
== AF_INET
)
685 SINIFSCOPE(ss
)->sin_scope_id
= IFSCOPE_NONE
;
687 SIN6IFSCOPE(ss
)->sin6_scope_id
= IFSCOPE_NONE
;
688 ret
= sa_trim(SA(ss
), skip
);
691 * For AF_INET6 mask, set sa_len appropriately unless
692 * this is requested via systl_dumpentry(), in which
693 * case we return the raw value.
695 if (hint
->sa_family
== AF_INET6
&&
696 type
!= RTM_GET
&& type
!= RTM_GET2
)
697 SA(ret
)->sa_len
= sizeof (struct sockaddr_in6
);
709 * Callback leaf-matching routine for rn_matchaddr_args used
710 * for looking up an exact match for a scoped route entry.
713 rn_match_ifscope(struct radix_node
*rn
, void *arg
)
715 struct rtentry
*rt
= (struct rtentry
*)rn
;
716 struct matchleaf_arg
*ma
= arg
;
717 int af
= rt_key(rt
)->sa_family
;
719 if (!(rt
->rt_flags
& RTF_IFSCOPE
) || (af
!= AF_INET
&& af
!= AF_INET6
))
722 return (af
== AF_INET
?
723 (SINIFSCOPE(rt_key(rt
))->sin_scope_id
== ma
->ifscope
) :
724 (SIN6IFSCOPE(rt_key(rt
))->sin6_scope_id
== ma
->ifscope
));
728 rtable_init(void **table
)
731 for (dom
= domains
; dom
; dom
= dom
->dom_next
)
732 if (dom
->dom_rtattach
)
733 dom
->dom_rtattach(&table
[dom
->dom_family
],
742 PE_parse_boot_argn("rte_debug", &rte_debug
, sizeof (rte_debug
));
744 rte_debug
|= RTD_DEBUG
;
746 rnh_lock_grp_attr
= lck_grp_attr_alloc_init();
747 rnh_lock_grp
= lck_grp_alloc_init("route", rnh_lock_grp_attr
);
748 rnh_lock_attr
= lck_attr_alloc_init();
749 lck_mtx_init(rnh_lock
, rnh_lock_grp
, rnh_lock_attr
);
751 rte_mtx_grp_attr
= lck_grp_attr_alloc_init();
752 rte_mtx_grp
= lck_grp_alloc_init(RTE_NAME
, rte_mtx_grp_attr
);
753 rte_mtx_attr
= lck_attr_alloc_init();
755 lck_mtx_lock(rnh_lock
);
756 rn_init(); /* initialize all zeroes, all ones, mask table */
757 lck_mtx_unlock(rnh_lock
);
758 rtable_init((void **)rt_tables
);
760 if (rte_debug
& RTD_DEBUG
)
761 size
= sizeof (struct rtentry_dbg
);
763 size
= sizeof (struct rtentry
);
765 rte_zone
= zinit(size
, RTE_ZONE_MAX
* size
, 0, RTE_ZONE_NAME
);
766 if (rte_zone
== NULL
)
767 panic("route_init: failed allocating rte_zone");
769 zone_change(rte_zone
, Z_EXPAND
, TRUE
);
770 zone_change(rte_zone
, Z_CALLERACCT
, FALSE
);
771 zone_change(rte_zone
, Z_NOENCRYPT
, TRUE
);
773 TAILQ_INIT(&rttrash_head
);
777 * Atomically increment route generation counter
780 routegenid_update(void)
782 (void) atomic_add_32_ov(&route_generation
, 1);
786 * Packet routing routines.
789 rtalloc(struct route
*ro
)
795 rtalloc_scoped(struct route
*ro
, unsigned int ifscope
)
797 rtalloc_scoped_ign(ro
, 0, ifscope
);
801 rtalloc_ign_common_locked(struct route
*ro
, uint32_t ignore
,
802 unsigned int ifscope
)
806 if ((rt
= ro
->ro_rt
) != NULL
) {
808 if (rt
->rt_ifp
!= NULL
&& (rt
->rt_flags
& RTF_UP
) &&
809 rt
->generation_id
== route_generation
) {
817 ro
->ro_rt
= rtalloc1_common_locked(&ro
->ro_dst
, 1, ignore
, ifscope
);
818 if (ro
->ro_rt
!= NULL
) {
819 ro
->ro_rt
->generation_id
= route_generation
;
820 RT_LOCK_ASSERT_NOTHELD(ro
->ro_rt
);
825 rtalloc_ign(struct route
*ro
, uint32_t ignore
)
827 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
828 lck_mtx_lock(rnh_lock
);
829 rtalloc_ign_common_locked(ro
, ignore
, IFSCOPE_NONE
);
830 lck_mtx_unlock(rnh_lock
);
834 rtalloc_scoped_ign(struct route
*ro
, uint32_t ignore
, unsigned int ifscope
)
836 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
837 lck_mtx_lock(rnh_lock
);
838 rtalloc_ign_common_locked(ro
, ignore
, ifscope
);
839 lck_mtx_unlock(rnh_lock
);
842 static struct rtentry
*
843 rtalloc1_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
845 return (rtalloc1_common_locked(dst
, report
, ignflags
, IFSCOPE_NONE
));
849 rtalloc1_scoped_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
850 unsigned int ifscope
)
852 return (rtalloc1_common_locked(dst
, report
, ignflags
, ifscope
));
856 * Look up the route that matches the address given
857 * Or, at least try.. Create a cloned route if needed.
859 static struct rtentry
*
860 rtalloc1_common_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
861 unsigned int ifscope
)
863 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
864 struct rtentry
*rt
, *newrt
= NULL
;
865 struct rt_addrinfo info
;
867 int err
= 0, msgtype
= RTM_MISS
;
873 * Find the longest prefix or exact (in the scoped case) address match;
874 * callee adds a reference to entry and checks for root node as well
876 rt
= rt_lookup(FALSE
, dst
, NULL
, rnh
, ifscope
);
882 nflags
= rt
->rt_flags
& ~ignflags
;
884 if (report
&& (nflags
& (RTF_CLONING
| RTF_PRCLONING
))) {
886 * We are apparently adding (report = 0 in delete).
887 * If it requires that it be cloned, do so.
888 * (This implies it wasn't a HOST route.)
890 err
= rtrequest_locked(RTM_RESOLVE
, dst
, NULL
, NULL
, 0, &newrt
);
893 * If the cloning didn't succeed, maybe what we
894 * have from lookup above will do. Return that;
895 * no need to hold another reference since it's
903 * We cloned it; drop the original route found during lookup.
904 * The resulted cloned route (newrt) would now have an extra
905 * reference held during rtrequest.
908 if ((rt
= newrt
) && (rt
->rt_flags
& RTF_XRESOLVE
)) {
910 * If the new route specifies it be
911 * externally resolved, then go do that.
913 msgtype
= RTM_RESOLVE
;
921 * Either we hit the root or couldn't find any match,
922 * Which basically means "cant get there from here"
924 rtstat
.rts_unreach
++;
928 * If required, report the failure to the supervising
930 * For a delete, this is not an error. (report == 0)
932 bzero((caddr_t
)&info
, sizeof(info
));
933 info
.rti_info
[RTAX_DST
] = dst
;
934 rt_missmsg(msgtype
, &info
, 0, err
);
941 rtalloc1(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
943 struct rtentry
* entry
;
944 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
945 lck_mtx_lock(rnh_lock
);
946 entry
= rtalloc1_locked(dst
, report
, ignflags
);
947 lck_mtx_unlock(rnh_lock
);
952 rtalloc1_scoped(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
953 unsigned int ifscope
)
955 struct rtentry
* entry
;
956 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
957 lck_mtx_lock(rnh_lock
);
958 entry
= rtalloc1_scoped_locked(dst
, report
, ignflags
, ifscope
);
959 lck_mtx_unlock(rnh_lock
);
964 * Remove a reference count from an rtentry.
965 * If the count gets low enough, take it out of the routing table
968 rtfree_locked(struct rtentry
*rt
)
970 rtfree_common(rt
, TRUE
);
974 rtfree_common(struct rtentry
*rt
, boolean_t locked
)
976 struct radix_node_head
*rnh
;
979 * Atomically decrement the reference count and if it reaches 0,
980 * and there is a close function defined, call the close function.
983 if (rtunref(rt
) > 0) {
989 * To avoid violating lock ordering, we must drop rt_lock before
990 * trying to acquire the global rnh_lock. If we are called with
991 * rnh_lock held, then we already have exclusive access; otherwise
992 * we do the lock dance.
996 * Note that we check it again below after grabbing rnh_lock,
997 * since it is possible that another thread doing a lookup wins
998 * the race, grabs the rnh_lock first, and bumps up the reference
999 * count in which case the route should be left alone as it is
1000 * still in use. It's also possible that another thread frees
1001 * the route after we drop rt_lock; to prevent the route from
1002 * being freed, we hold an extra reference.
1004 RT_ADDREF_LOCKED(rt
);
1006 lck_mtx_lock(rnh_lock
);
1008 RT_REMREF_LOCKED(rt
);
1009 if (rt
->rt_refcnt
> 0) {
1010 /* We've lost the race, so abort */
1017 * We may be blocked on other lock(s) as part of freeing
1018 * the entry below, so convert from spin to full mutex.
1020 RT_CONVERT_LOCK(rt
);
1022 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1024 /* Negative refcnt must never happen */
1025 if (rt
->rt_refcnt
!= 0)
1026 panic("rt %p invalid refcnt %d", rt
, rt
->rt_refcnt
);
1029 * find the tree for that address family
1030 * Note: in the case of igmp packets, there might not be an rnh
1032 rnh
= rt_tables
[rt_key(rt
)->sa_family
];
1035 * On last reference give the "close method" a chance to cleanup
1036 * private state. This also permits (for IPv4 and IPv6) a chance
1037 * to decide if the routing table entry should be purged immediately
1038 * or at a later time. When an immediate purge is to happen the
1039 * close routine typically issues RTM_DELETE which clears the RTF_UP
1040 * flag on the entry so that the code below reclaims the storage.
1042 if (rnh
!= NULL
&& rnh
->rnh_close
!= NULL
)
1043 rnh
->rnh_close((struct radix_node
*)rt
, rnh
);
1046 * If we are no longer "up" (and ref == 0) then we can free the
1047 * resources associated with the route.
1049 if (!(rt
->rt_flags
& RTF_UP
)) {
1050 struct rtentry
*rt_parent
;
1051 struct ifaddr
*rt_ifa
;
1053 if (rt
->rt_nodes
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
))
1054 panic("rt %p freed while in radix tree\n", rt
);
1056 * the rtentry must have been removed from the routing table
1057 * so it is represented in rttrash; remove that now.
1059 (void) OSDecrementAtomic(&rttrash
);
1060 if (rte_debug
& RTD_DEBUG
) {
1061 TAILQ_REMOVE(&rttrash_head
, (struct rtentry_dbg
*)rt
,
1066 * release references on items we hold them on..
1067 * e.g other routes and ifaddrs.
1069 if ((rt_parent
= rt
->rt_parent
) != NULL
)
1070 rt
->rt_parent
= NULL
;
1072 if ((rt_ifa
= rt
->rt_ifa
) != NULL
)
1076 * Now free any attached link-layer info.
1078 if (rt
->rt_llinfo
!= NULL
) {
1079 if (rt
->rt_llinfo_free
!= NULL
)
1080 (*rt
->rt_llinfo_free
)(rt
->rt_llinfo
);
1082 R_Free(rt
->rt_llinfo
);
1083 rt
->rt_llinfo
= NULL
;
1087 * Route is no longer in the tree and refcnt is 0;
1088 * we have exclusive access, so destroy it.
1092 if (rt_parent
!= NULL
)
1093 rtfree_locked(rt_parent
);
1099 * The key is separately alloc'd so free it (see rt_setgate()).
1100 * This also frees the gateway, as they are always malloc'd
1106 * Free any statistics that may have been allocated
1108 nstat_route_detach(rt
);
1111 * and the rtentry itself of course
1113 rte_lock_destroy(rt
);
1117 * The "close method" has been called, but the route is
1118 * still in the radix tree with zero refcnt, i.e. "up"
1119 * and in the cached state.
1125 lck_mtx_unlock(rnh_lock
);
1129 rtfree(struct rtentry
*rt
)
1131 rtfree_common(rt
, FALSE
);
1135 * Decrements the refcount but does not free the route when
1136 * the refcount reaches zero. Unless you have really good reason,
1137 * use rtfree not rtunref.
1140 rtunref(struct rtentry
*p
)
1142 RT_LOCK_ASSERT_HELD(p
);
1144 if (p
->rt_refcnt
== 0)
1145 panic("%s(%p) bad refcnt\n", __func__
, p
);
1149 if (rte_debug
& RTD_DEBUG
)
1150 rtunref_audit((struct rtentry_dbg
*)p
);
1152 /* Return new value */
1153 return (p
->rt_refcnt
);
1157 rtunref_audit(struct rtentry_dbg
*rte
)
1161 if (rte
->rtd_inuse
!= RTD_INUSE
)
1162 panic("rtunref: on freed rte=%p\n", rte
);
1164 idx
= atomic_add_16_ov(&rte
->rtd_refrele_cnt
, 1) % CTRACE_HIST_SIZE
;
1165 if (rte_debug
& RTD_TRACE
)
1166 ctrace_record(&rte
->rtd_refrele
[idx
]);
1170 * Add a reference count from an rtentry.
1173 rtref(struct rtentry
*p
)
1175 RT_LOCK_ASSERT_HELD(p
);
1177 if (++p
->rt_refcnt
== 0)
1178 panic("%s(%p) bad refcnt\n", __func__
, p
);
1180 if (rte_debug
& RTD_DEBUG
)
1181 rtref_audit((struct rtentry_dbg
*)p
);
1185 rtref_audit(struct rtentry_dbg
*rte
)
1189 if (rte
->rtd_inuse
!= RTD_INUSE
)
1190 panic("rtref_audit: on freed rte=%p\n", rte
);
1192 idx
= atomic_add_16_ov(&rte
->rtd_refhold_cnt
, 1) % CTRACE_HIST_SIZE
;
1193 if (rte_debug
& RTD_TRACE
)
1194 ctrace_record(&rte
->rtd_refhold
[idx
]);
1198 rtsetifa(struct rtentry
*rt
, struct ifaddr
* ifa
)
1200 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1202 RT_LOCK_ASSERT_HELD(rt
);
1204 if (rt
->rt_ifa
== ifa
)
1207 /* Become a regular mutex, just in case */
1208 RT_CONVERT_LOCK(rt
);
1210 /* Release the old ifa */
1212 IFA_REMREF(rt
->rt_ifa
);
1217 /* Take a reference to the ifa */
1219 IFA_ADDREF(rt
->rt_ifa
);
1223 * Force a routing table entry to the specified
1224 * destination to go through the given gateway.
1225 * Normally called as a result of a routing redirect
1226 * message from the network layer.
1229 rtredirect(struct ifnet
*ifp
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1230 struct sockaddr
*netmask
, int flags
, struct sockaddr
*src
,
1231 struct rtentry
**rtp
)
1233 struct rtentry
*rt
= NULL
;
1236 struct rt_addrinfo info
;
1237 struct ifaddr
*ifa
= NULL
;
1238 unsigned int ifscope
= (ifp
!= NULL
) ? ifp
->if_index
: IFSCOPE_NONE
;
1239 struct sockaddr_storage ss
;
1241 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1242 lck_mtx_lock(rnh_lock
);
1245 * Transform src into the internal routing table form for
1246 * comparison against rt_gateway below.
1249 if ((src
->sa_family
== AF_INET
&& ip_doscopedroute
) ||
1250 (src
->sa_family
== AF_INET6
&& ip6_doscopedroute
))
1252 if (src
->sa_family
== AF_INET
&& ip_doscopedroute
)
1254 src
= sa_copy(src
, &ss
, &ifscope
);
1257 * Verify the gateway is directly reachable; if scoped routing
1258 * is enabled, verify that it is reachable from the interface
1259 * where the ICMP redirect arrived on.
1261 if ((ifa
= ifa_ifwithnet_scoped(gateway
, ifscope
)) == NULL
) {
1262 error
= ENETUNREACH
;
1266 /* Lookup route to the destination (from the original IP header) */
1267 rt
= rtalloc1_scoped_locked(dst
, 0, RTF_CLONING
|RTF_PRCLONING
, ifscope
);
1272 * If the redirect isn't from our current router for this dst,
1273 * it's either old or wrong. If it redirects us to ourselves,
1274 * we have a routing loop, perhaps as a result of an interface
1275 * going down recently. Holding rnh_lock here prevents the
1276 * possibility of rt_ifa/ifa's ifa_addr from changing (e.g.
1277 * in_ifinit), so okay to access ifa_addr without locking.
1279 if (!(flags
& RTF_DONE
) && rt
!= NULL
&&
1280 (!equal(src
, rt
->rt_gateway
) || !equal(rt
->rt_ifa
->ifa_addr
,
1285 if ((ifa
= ifa_ifwithaddr(gateway
))) {
1288 error
= EHOSTUNREACH
;
1304 * Create a new entry if we just got back a wildcard entry
1305 * or the the lookup failed. This is necessary for hosts
1306 * which use routing redirects generated by smart gateways
1307 * to dynamically build the routing tables.
1309 if ((rt
== NULL
) || (rt_mask(rt
) != NULL
&& rt_mask(rt
)->sa_len
< 2))
1312 * Don't listen to the redirect if it's
1313 * for a route to an interface.
1315 RT_LOCK_ASSERT_HELD(rt
);
1316 if (rt
->rt_flags
& RTF_GATEWAY
) {
1317 if (((rt
->rt_flags
& RTF_HOST
) == 0) && (flags
& RTF_HOST
)) {
1319 * Changing from route to net => route to host.
1320 * Create new route, rather than smashing route
1321 * to net; similar to cloned routes, the newly
1322 * created host route is scoped as well.
1327 flags
|= RTF_GATEWAY
| RTF_DYNAMIC
;
1328 error
= rtrequest_scoped_locked(RTM_ADD
, dst
,
1329 gateway
, netmask
, flags
, NULL
, ifscope
);
1330 stat
= &rtstat
.rts_dynamic
;
1333 * Smash the current notion of the gateway to
1334 * this destination. Should check about netmask!!!
1336 rt
->rt_flags
|= RTF_MODIFIED
;
1337 flags
|= RTF_MODIFIED
;
1338 stat
= &rtstat
.rts_newgateway
;
1340 * add the key and gateway (in one malloc'd chunk).
1342 error
= rt_setgate(rt
, rt_key(rt
), gateway
);
1347 error
= EHOSTUNREACH
;
1351 RT_LOCK_ASSERT_NOTHELD(rt
);
1359 rtstat
.rts_badredirect
++;
1364 routegenid_update();
1366 lck_mtx_unlock(rnh_lock
);
1367 bzero((caddr_t
)&info
, sizeof(info
));
1368 info
.rti_info
[RTAX_DST
] = dst
;
1369 info
.rti_info
[RTAX_GATEWAY
] = gateway
;
1370 info
.rti_info
[RTAX_NETMASK
] = netmask
;
1371 info
.rti_info
[RTAX_AUTHOR
] = src
;
1372 rt_missmsg(RTM_REDIRECT
, &info
, flags
, error
);
1376 * Routing table ioctl interface.
1379 rtioctl(unsigned long req
, caddr_t data
, struct proc
*p
)
1382 #if INET && MROUTING
1383 return mrt_ioctl(req
, data
);
1386 #pragma unused(data)
1394 const struct sockaddr
*dst
,
1395 const struct sockaddr
*gateway
)
1399 lck_mtx_lock(rnh_lock
);
1400 ifa
= ifa_ifwithroute_locked(flags
, dst
, gateway
);
1401 lck_mtx_unlock(rnh_lock
);
1407 ifa_ifwithroute_locked(int flags
, const struct sockaddr
*dst
,
1408 const struct sockaddr
*gateway
)
1410 return (ifa_ifwithroute_common_locked((flags
& ~RTF_IFSCOPE
), dst
,
1411 gateway
, IFSCOPE_NONE
));
1415 ifa_ifwithroute_scoped_locked(int flags
, const struct sockaddr
*dst
,
1416 const struct sockaddr
*gateway
, unsigned int ifscope
)
1418 if (ifscope
!= IFSCOPE_NONE
)
1419 flags
|= RTF_IFSCOPE
;
1421 flags
&= ~RTF_IFSCOPE
;
1423 return (ifa_ifwithroute_common_locked(flags
, dst
, gateway
, ifscope
));
1426 static struct ifaddr
*
1427 ifa_ifwithroute_common_locked(int flags
, const struct sockaddr
*dst
,
1428 const struct sockaddr
*gw
, unsigned int ifscope
)
1430 struct ifaddr
*ifa
= NULL
;
1431 struct rtentry
*rt
= NULL
;
1432 struct sockaddr_storage dst_ss
, gw_ss
;
1434 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1437 * Just in case the sockaddr passed in by the caller
1438 * contains a scope ID, make sure to clear it since
1439 * interface addresses aren't scoped.
1443 ((dst
->sa_family
== AF_INET
&& ip_doscopedroute
) ||
1444 (dst
->sa_family
== AF_INET6
&& ip6_doscopedroute
)))
1446 if (dst
!= NULL
&& dst
->sa_family
== AF_INET
&& ip_doscopedroute
)
1448 dst
= sa_copy(SA((uintptr_t)dst
), &dst_ss
, NULL
);
1452 ((gw
->sa_family
== AF_INET
&& ip_doscopedroute
) ||
1453 (gw
->sa_family
== AF_INET6
&& ip6_doscopedroute
)))
1455 if (gw
!= NULL
&& gw
->sa_family
== AF_INET
&& ip_doscopedroute
)
1457 gw
= sa_copy(SA((uintptr_t)gw
), &gw_ss
, NULL
);
1459 if (!(flags
& RTF_GATEWAY
)) {
1461 * If we are adding a route to an interface,
1462 * and the interface is a pt to pt link
1463 * we should search for the destination
1464 * as our clue to the interface. Otherwise
1465 * we can use the local address.
1467 if (flags
& RTF_HOST
) {
1468 ifa
= ifa_ifwithdstaddr(dst
);
1471 ifa
= ifa_ifwithaddr_scoped(gw
, ifscope
);
1474 * If we are adding a route to a remote net
1475 * or host, the gateway may still be on the
1476 * other end of a pt to pt link.
1478 ifa
= ifa_ifwithdstaddr(gw
);
1481 ifa
= ifa_ifwithnet_scoped(gw
, ifscope
);
1483 /* Workaround to avoid gcc warning regarding const variable */
1484 rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)dst
,
1490 /* Become a regular mutex */
1491 RT_CONVERT_LOCK(rt
);
1494 RT_REMREF_LOCKED(rt
);
1500 * Holding rnh_lock here prevents the possibility of ifa from
1501 * changing (e.g. in_ifinit), so it is safe to access its
1502 * ifa_addr (here and down below) without locking.
1504 if (ifa
!= NULL
&& ifa
->ifa_addr
->sa_family
!= dst
->sa_family
) {
1505 struct ifaddr
*newifa
;
1506 /* Callee adds reference to newifa upon success */
1507 newifa
= ifaof_ifpforaddr(dst
, ifa
->ifa_ifp
);
1508 if (newifa
!= NULL
) {
1514 * If we are adding a gateway, it is quite possible that the
1515 * routing table has a static entry in place for the gateway,
1516 * that may not agree with info garnered from the interfaces.
1517 * The routing table should carry more precedence than the
1518 * interfaces in this matter. Must be careful not to stomp
1519 * on new entries from rtinit, hence (ifa->ifa_addr != gw).
1522 !equal(ifa
->ifa_addr
, (struct sockaddr
*)(size_t)gw
)) &&
1523 (rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)gw
,
1524 0, 0, ifscope
)) != NULL
) {
1530 /* Become a regular mutex */
1531 RT_CONVERT_LOCK(rt
);
1534 RT_REMREF_LOCKED(rt
);
1538 * If an interface scope was specified, the interface index of
1539 * the found ifaddr must be equivalent to that of the scope;
1540 * otherwise there is no match.
1542 if ((flags
& RTF_IFSCOPE
) &&
1543 ifa
!= NULL
&& ifa
->ifa_ifp
->if_index
!= ifscope
) {
1551 static int rt_fixdelete(struct radix_node
*, void *);
1552 static int rt_fixchange(struct radix_node
*, void *);
1555 struct rtentry
*rt0
;
1556 struct radix_node_head
*rnh
;
1560 rtrequest_locked(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1561 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
)
1563 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1564 (flags
& ~RTF_IFSCOPE
), ret_nrt
, IFSCOPE_NONE
));
1568 rtrequest_scoped_locked(int req
, struct sockaddr
*dst
,
1569 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1570 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1572 if (ifscope
!= IFSCOPE_NONE
)
1573 flags
|= RTF_IFSCOPE
;
1575 flags
&= ~RTF_IFSCOPE
;
1577 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1578 flags
, ret_nrt
, ifscope
));
1582 * Do appropriate manipulations of a routing tree given all the bits of
1585 * Storing the scope ID in the radix key is an internal job that should be
1586 * left to routines in this module. Callers should specify the scope value
1587 * to the "scoped" variants of route routines instead of manipulating the
1588 * key itself. This is typically done when creating a scoped route, e.g.
1589 * rtrequest(RTM_ADD). Once such a route is created and marked with the
1590 * RTF_IFSCOPE flag, callers can simply use its rt_key(rt) to clone it
1591 * (RTM_RESOLVE) or to remove it (RTM_DELETE). An exception to this is
1592 * during certain routing socket operations where the search key might be
1593 * derived from the routing message itself, in which case the caller must
1594 * specify the destination address and scope value for RTM_ADD/RTM_DELETE.
1597 rtrequest_common_locked(int req
, struct sockaddr
*dst0
,
1598 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1599 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1603 struct radix_node
*rn
;
1604 struct radix_node_head
*rnh
;
1605 struct ifaddr
*ifa
= NULL
;
1606 struct sockaddr
*ndst
, *dst
= dst0
;
1607 struct sockaddr_storage ss
, mask
;
1608 struct timeval curr_calendartime
;
1609 int af
= dst
->sa_family
;
1610 void (*ifa_rtrequest
)(int, struct rtentry
*, struct sockaddr
*);
1612 #define senderr(x) { error = x ; goto bad; }
1614 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1616 * Find the correct routing tree to use for this Address Family
1618 if ((rnh
= rt_tables
[af
]) == NULL
)
1621 * If we are adding a host route then we don't want to put
1622 * a netmask in the tree
1624 if (flags
& RTF_HOST
)
1628 * If Scoped Routing is enabled, use a local copy of the destination
1629 * address to store the scope ID into. This logic is repeated below
1630 * in the RTM_RESOLVE handler since the caller does not normally
1631 * specify such a flag during a resolve, as well as for the handling
1632 * of IPv4 link-local address; instead, it passes in the route used for
1633 * cloning for which the scope info is derived from. Note also that
1634 * in the case of RTM_DELETE, the address passed in by the caller
1635 * might already contain the scope ID info when it is the key itself,
1636 * thus making RTF_IFSCOPE unnecessary; one instance where it is
1637 * explicitly set is inside route_output() as part of handling a
1638 * routing socket request.
1641 if (req
!= RTM_RESOLVE
&&
1642 ((af
== AF_INET
&& ip_doscopedroute
) ||
1643 (af
== AF_INET6
&& ip6_doscopedroute
))) {
1645 if (req
!= RTM_RESOLVE
&& af
== AF_INET
&& ip_doscopedroute
) {
1647 /* Transform dst into the internal routing table form */
1648 dst
= sa_copy(dst
, &ss
, &ifscope
);
1650 /* Transform netmask into the internal routing table form */
1651 if (netmask
!= NULL
)
1652 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
1654 if (ifscope
!= IFSCOPE_NONE
)
1655 flags
|= RTF_IFSCOPE
;
1657 if ((flags
& RTF_IFSCOPE
) && (af
!= AF_INET
&& af
!= AF_INET6
))
1661 if ((af
== AF_INET
&& !ip_doscopedroute
) ||
1662 (af
== AF_INET6
&& !ip6_doscopedroute
))
1664 if (af
== AF_INET
&& !ip_doscopedroute
)
1666 ifscope
= IFSCOPE_NONE
;
1669 if (ifscope
== IFSCOPE_NONE
)
1670 flags
&= ~RTF_IFSCOPE
;
1674 struct rtentry
*gwrt
= NULL
;
1676 * Remove the item from the tree and return it.
1677 * Complain if it is not there and do no more processing.
1679 if ((rn
= rnh
->rnh_deladdr(dst
, netmask
, rnh
)) == NULL
)
1681 if (rn
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
))
1682 panic ("rtrequest delete");
1683 rt
= (struct rtentry
*)rn
;
1686 * Take an extra reference to handle the deletion of a route
1687 * entry whose reference count is already 0; e.g. an expiring
1688 * cloned route entry or an entry that was added to the table
1689 * with 0 reference. If the caller is interested in this route,
1690 * we will return it with the reference intact. Otherwise we
1691 * will decrement the reference via rtfree_locked() and then
1692 * possibly deallocate it.
1695 RT_ADDREF_LOCKED(rt
);
1696 rt
->rt_flags
&= ~RTF_UP
;
1699 * For consistency, in case the caller didn't set the flag.
1701 rt
->rt_flags
|= RTF_CONDEMNED
;
1704 * Clear RTF_ROUTER if it's set.
1706 if (rt
->rt_flags
& RTF_ROUTER
) {
1707 VERIFY(rt
->rt_flags
& RTF_HOST
);
1708 rt
->rt_flags
&= ~RTF_ROUTER
;
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, or those routes that are cloned
1823 * from a RTF_PROXY route. For the latter, the clone
1824 * gets to keep the RTF_PROXY flag.
1826 if ((af
== AF_INET
&&
1827 IN_LINKLOCAL(ntohl(SIN(dst
)->sin_addr
.s_addr
))) ||
1828 (rt
->rt_flags
& RTF_PROXY
)) {
1829 ifscope
= IFSCOPE_NONE
;
1830 flags
&= ~RTF_IFSCOPE
;
1832 if (flags
& RTF_IFSCOPE
) {
1833 ifscope
= (af
== AF_INET
) ?
1834 sin_get_ifscope(rt_key(rt
)) :
1835 sin6_get_ifscope(rt_key(rt
));
1837 ifscope
= rt
->rt_ifp
->if_index
;
1838 flags
|= RTF_IFSCOPE
;
1840 VERIFY(ifscope
!= IFSCOPE_NONE
);
1844 * Transform dst into the internal routing table form,
1845 * clearing out the scope ID field if ifscope isn't set.
1847 dst
= sa_copy(dst
, &ss
, (ifscope
== IFSCOPE_NONE
) ?
1850 /* Transform netmask into the internal routing table form */
1851 if (netmask
!= NULL
)
1852 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
1857 if ((flags
& RTF_GATEWAY
) && !gateway
)
1858 panic("rtrequest: RTF_GATEWAY but no gateway");
1860 if (flags
& RTF_IFSCOPE
) {
1861 ifa
= ifa_ifwithroute_scoped_locked(flags
, dst0
,
1864 ifa
= ifa_ifwithroute_locked(flags
, dst0
, gateway
);
1867 senderr(ENETUNREACH
);
1869 getmicrotime(&curr_calendartime
);
1870 if ((rt
= rte_alloc()) == NULL
)
1872 Bzero(rt
, sizeof(*rt
));
1874 rt
->base_calendartime
= curr_calendartime
.tv_sec
;
1875 rt
->base_uptime
= net_uptime();
1877 rt
->rt_flags
= RTF_UP
| flags
;
1880 * Add the gateway. Possibly re-malloc-ing the storage for it
1881 * also add the rt_gwroute if possible.
1883 if ((error
= rt_setgate(rt
, dst
, gateway
)) != 0) {
1886 nstat_route_detach(rt
);
1887 rte_lock_destroy(rt
);
1893 * point to the (possibly newly malloc'd) dest address.
1898 * make sure it contains the value we want (masked if needed).
1901 rt_maskedcopy(dst
, ndst
, netmask
);
1903 Bcopy(dst
, ndst
, dst
->sa_len
);
1906 * Note that we now have a reference to the ifa.
1907 * This moved from below so that rnh->rnh_addaddr() can
1908 * examine the ifa and ifa->ifa_ifp if it so desires.
1911 rt
->rt_ifp
= rt
->rt_ifa
->ifa_ifp
;
1913 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1915 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
, (caddr_t
)netmask
,
1918 struct rtentry
*rt2
;
1920 * Uh-oh, we already have one of these in the tree.
1921 * We do a special hack: if the route that's already
1922 * there was generated by the protocol-cloning
1923 * mechanism, then we just blow it away and retry
1924 * the insertion of the new one.
1926 if (flags
& RTF_IFSCOPE
) {
1927 rt2
= rtalloc1_scoped_locked(dst0
, 0,
1928 RTF_CLONING
| RTF_PRCLONING
, ifscope
);
1930 rt2
= rtalloc1_locked(dst
, 0,
1931 RTF_CLONING
| RTF_PRCLONING
);
1933 if (rt2
&& rt2
->rt_parent
) {
1935 * rnh_lock is held here, so rt_key and
1936 * rt_gateway of rt2 will not change.
1938 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt2
),
1939 rt2
->rt_gateway
, rt_mask(rt2
),
1942 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
,
1946 /* undo the extra ref we got */
1952 * If it still failed to go into the tree,
1953 * then un-make it (this should be a function)
1956 /* Clear gateway route */
1957 rt_set_gwroute(rt
, rt_key(rt
), NULL
);
1959 IFA_REMREF(rt
->rt_ifa
);
1964 nstat_route_detach(rt
);
1965 rte_lock_destroy(rt
);
1970 rt
->rt_parent
= NULL
;
1973 * If we got here from RESOLVE, then we are cloning so clone
1974 * the rest, and note that we are a clone (and increment the
1975 * parent's references). rnh_lock is still held, which prevents
1976 * a lookup from returning the newly-created route. Hence
1977 * holding and releasing the parent's rt_lock while still
1978 * holding the route's rt_lock is safe since the new route
1979 * is not yet externally visible.
1981 if (req
== RTM_RESOLVE
) {
1982 RT_LOCK_SPIN(*ret_nrt
);
1983 VERIFY((*ret_nrt
)->rt_expire
== 0 ||
1984 (*ret_nrt
)->rt_rmx
.rmx_expire
!= 0);
1985 VERIFY((*ret_nrt
)->rt_expire
!= 0 ||
1986 (*ret_nrt
)->rt_rmx
.rmx_expire
== 0);
1987 rt
->rt_rmx
= (*ret_nrt
)->rt_rmx
;
1988 rt_setexpire(rt
, (*ret_nrt
)->rt_expire
);
1989 if ((*ret_nrt
)->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) {
1990 rt
->rt_parent
= (*ret_nrt
);
1991 RT_ADDREF_LOCKED(*ret_nrt
);
1993 RT_UNLOCK(*ret_nrt
);
1996 * Enable interface reference counting for unicast
1997 * cloned routes and bump up the reference count.
1999 if (rt
->rt_parent
!= NULL
&&
2000 !(rt
->rt_flags
& (RTF_BROADCAST
| RTF_MULTICAST
))) {
2006 * if this protocol has something to add to this then
2007 * allow it to do that as well.
2010 ifa_rtrequest
= ifa
->ifa_rtrequest
;
2012 if (ifa_rtrequest
!= NULL
)
2013 ifa_rtrequest(req
, rt
, SA(ret_nrt
? *ret_nrt
: NULL
));
2018 * If this is the (non-scoped) default route, record
2019 * the interface index used for the primary ifscope.
2021 if (rt_primary_default(rt
, rt_key(rt
))) {
2022 set_primary_ifscope(rt_key(rt
)->sa_family
,
2023 rt
->rt_ifp
->if_index
);
2027 * actually return a resultant rtentry and
2028 * give the caller a single reference.
2032 RT_ADDREF_LOCKED(rt
);
2036 * We repeat the same procedures from rt_setgate() here
2037 * because they weren't completed when we called it earlier,
2038 * since the node was embryonic.
2040 if ((rt
->rt_flags
& RTF_GATEWAY
) && rt
->rt_gwroute
!= NULL
)
2041 rt_set_gwroute(rt
, rt_key(rt
), rt
->rt_gwroute
);
2043 if (req
== RTM_ADD
&&
2044 !(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != NULL
) {
2045 struct rtfc_arg arg
;
2049 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
2050 rt_fixchange
, &arg
);
2055 nstat_route_new_entry(rt
);
2066 rtrequest(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
2067 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
)
2070 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2071 lck_mtx_lock(rnh_lock
);
2072 error
= rtrequest_locked(req
, dst
, gateway
, netmask
, flags
, ret_nrt
);
2073 lck_mtx_unlock(rnh_lock
);
2078 rtrequest_scoped(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
2079 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
,
2080 unsigned int ifscope
)
2083 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2084 lck_mtx_lock(rnh_lock
);
2085 error
= rtrequest_scoped_locked(req
, dst
, gateway
, netmask
, flags
,
2087 lck_mtx_unlock(rnh_lock
);
2092 * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
2093 * (i.e., the routes related to it by the operation of cloning). This
2094 * routine is iterated over all potential former-child-routes by way of
2095 * rnh->rnh_walktree_from() above, and those that actually are children of
2096 * the late parent (passed in as VP here) are themselves deleted.
2099 rt_fixdelete(struct radix_node
*rn
, void *vp
)
2101 struct rtentry
*rt
= (struct rtentry
*)rn
;
2102 struct rtentry
*rt0
= vp
;
2104 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2107 if (rt
->rt_parent
== rt0
&&
2108 !(rt
->rt_flags
& (RTF_PINNED
| RTF_CLONING
| RTF_PRCLONING
))) {
2110 * Safe to drop rt_lock and use rt_key, since holding
2111 * rnh_lock here prevents another thread from calling
2112 * rt_setgate() on this route.
2115 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
2116 rt_mask(rt
), rt
->rt_flags
, NULL
));
2123 * This routine is called from rt_setgate() to do the analogous thing for
2124 * adds and changes. There is the added complication in this case of a
2125 * middle insert; i.e., insertion of a new network route between an older
2126 * network route and (cloned) host routes. For this reason, a simple check
2127 * of rt->rt_parent is insufficient; each candidate route must be tested
2128 * against the (mask, value) of the new route (passed as before in vp)
2129 * to see if the new route matches it.
2131 * XXX - it may be possible to do fixdelete() for changes and reserve this
2132 * routine just for adds. I'm not sure why I thought it was necessary to do
2136 rt_fixchange(struct radix_node
*rn
, void *vp
)
2138 struct rtentry
*rt
= (struct rtentry
*)rn
;
2139 struct rtfc_arg
*ap
= vp
;
2140 struct rtentry
*rt0
= ap
->rt0
;
2141 struct radix_node_head
*rnh
= ap
->rnh
;
2142 u_char
*xk1
, *xm1
, *xk2
, *xmp
;
2145 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2149 if (!rt
->rt_parent
||
2150 (rt
->rt_flags
& (RTF_PINNED
| RTF_CLONING
| RTF_PRCLONING
))) {
2155 if (rt
->rt_parent
== rt0
)
2159 * There probably is a function somewhere which does this...
2160 * if not, there should be.
2162 len
= imin(rt_key(rt0
)->sa_len
, rt_key(rt
)->sa_len
);
2164 xk1
= (u_char
*)rt_key(rt0
);
2165 xm1
= (u_char
*)rt_mask(rt0
);
2166 xk2
= (u_char
*)rt_key(rt
);
2169 * Avoid applying a less specific route; do this only if the parent
2170 * route (rt->rt_parent) is a network route, since otherwise its mask
2171 * will be NULL if it is a cloning host route.
2173 if ((xmp
= (u_char
*)rt_mask(rt
->rt_parent
)) != NULL
) {
2174 int mlen
= rt_mask(rt
->rt_parent
)->sa_len
;
2175 if (mlen
> rt_mask(rt0
)->sa_len
) {
2180 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< mlen
; i
++) {
2181 if ((xmp
[i
] & ~(xmp
[i
] ^ xm1
[i
])) != xmp
[i
]) {
2188 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< len
; i
++) {
2189 if ((xk2
[i
] & xm1
[i
]) != xk1
[i
]) {
2196 * OK, this node is a clone, and matches the node currently being
2197 * changed/added under the node's mask. So, get rid of it.
2201 * Safe to drop rt_lock and use rt_key, since holding rnh_lock here
2202 * prevents another thread from calling rt_setgate() on this route.
2205 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
2206 rt_mask(rt
), rt
->rt_flags
, NULL
));
2210 * Round up sockaddr len to multiples of 32-bytes. This will reduce
2211 * or even eliminate the need to re-allocate the chunk of memory used
2212 * for rt_key and rt_gateway in the event the gateway portion changes.
2213 * Certain code paths (e.g. IPSec) are notorious for caching the address
2214 * of rt_gateway; this rounding-up would help ensure that the gateway
2215 * portion never gets deallocated (though it may change contents) and
2216 * thus greatly simplifies things.
2218 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
2221 * Sets the gateway and/or gateway route portion of a route; may be
2222 * called on an existing route to modify the gateway portion. Both
2223 * rt_key and rt_gateway are allocated out of the same memory chunk.
2224 * Route entry lock must be held by caller; this routine will return
2225 * with the lock held.
2228 rt_setgate(struct rtentry
*rt
, struct sockaddr
*dst
, struct sockaddr
*gate
)
2230 int dlen
= SA_SIZE(dst
->sa_len
), glen
= SA_SIZE(gate
->sa_len
);
2231 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
2232 boolean_t loop
= FALSE
;
2234 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2235 RT_LOCK_ASSERT_HELD(rt
);
2238 * If this is for a route that is on its way of being removed,
2239 * or is temporarily frozen, reject the modification request.
2241 if (rt
->rt_flags
& RTF_CONDEMNED
)
2244 /* Add an extra ref for ourselves */
2245 RT_ADDREF_LOCKED(rt
);
2247 if (rt
->rt_flags
& RTF_GATEWAY
) {
2248 if ((dst
->sa_len
== gate
->sa_len
) &&
2249 (dst
->sa_family
== AF_INET
|| dst
->sa_family
== AF_INET6
)) {
2250 struct sockaddr_storage dst_ss
, gate_ss
;
2252 (void) sa_copy(dst
, &dst_ss
, NULL
);
2253 (void) sa_copy(gate
, &gate_ss
, NULL
);
2255 loop
= equal(SA(&dst_ss
), SA(&gate_ss
));
2257 loop
= (dst
->sa_len
== gate
->sa_len
&&
2263 * A (cloning) network route with the destination equal to the gateway
2264 * will create an endless loop (see notes below), so disallow it.
2266 if (((rt
->rt_flags
& (RTF_HOST
|RTF_GATEWAY
|RTF_LLINFO
)) ==
2267 RTF_GATEWAY
) && loop
) {
2268 /* Release extra ref */
2269 RT_REMREF_LOCKED(rt
);
2270 return (EADDRNOTAVAIL
);
2274 * A host route with the destination equal to the gateway
2275 * will interfere with keeping LLINFO in the routing
2276 * table, so disallow it.
2278 if (((rt
->rt_flags
& (RTF_HOST
|RTF_GATEWAY
|RTF_LLINFO
)) ==
2279 (RTF_HOST
|RTF_GATEWAY
)) && loop
) {
2281 * The route might already exist if this is an RTM_CHANGE
2282 * or a routing redirect, so try to delete it.
2284 if (rt_key(rt
) != NULL
) {
2286 * Safe to drop rt_lock and use rt_key, rt_gateway,
2287 * since holding rnh_lock here prevents another thread
2288 * from calling rt_setgate() on this route.
2291 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt
),
2292 rt
->rt_gateway
, rt_mask(rt
), rt
->rt_flags
, NULL
);
2295 /* Release extra ref */
2296 RT_REMREF_LOCKED(rt
);
2297 return (EADDRNOTAVAIL
);
2301 * The destination is not directly reachable. Get a route
2302 * to the next-hop gateway and store it in rt_gwroute.
2304 if (rt
->rt_flags
& RTF_GATEWAY
) {
2305 struct rtentry
*gwrt
;
2306 unsigned int ifscope
;
2308 if (dst
->sa_family
== AF_INET
)
2309 ifscope
= sin_get_ifscope(dst
);
2310 else if (dst
->sa_family
== AF_INET6
)
2311 ifscope
= sin6_get_ifscope(dst
);
2313 ifscope
= IFSCOPE_NONE
;
2317 * Don't ignore RTF_CLONING, since we prefer that rt_gwroute
2318 * points to a clone rather than a cloning route; see above
2319 * check for cloning loop avoidance (dst == gate).
2321 gwrt
= rtalloc1_scoped_locked(gate
, 1, RTF_PRCLONING
, ifscope
);
2323 RT_LOCK_ASSERT_NOTHELD(gwrt
);
2327 * Cloning loop avoidance:
2329 * In the presence of protocol-cloning and bad configuration,
2330 * it is possible to get stuck in bottomless mutual recursion
2331 * (rtrequest rt_setgate rtalloc1). We avoid this by not
2332 * allowing protocol-cloning to operate for gateways (which
2333 * is probably the correct choice anyway), and avoid the
2334 * resulting reference loops by disallowing any route to run
2335 * through itself as a gateway. This is obviously mandatory
2336 * when we get rt->rt_output(). It implies that a route to
2337 * the gateway must already be present in the system in order
2338 * for the gateway to be referred to by another route.
2341 RT_REMREF_LOCKED(gwrt
);
2342 /* Release extra ref */
2343 RT_REMREF_LOCKED(rt
);
2344 return (EADDRINUSE
); /* failure */
2348 * If scoped, the gateway route must use the same interface;
2349 * we're holding rnh_lock now, so rt_gateway and rt_ifp of gwrt
2350 * should not change and are freely accessible.
2352 if (ifscope
!= IFSCOPE_NONE
&& (rt
->rt_flags
& RTF_IFSCOPE
) &&
2353 gwrt
!= NULL
&& gwrt
->rt_ifp
!= NULL
&&
2354 gwrt
->rt_ifp
->if_index
!= ifscope
) {
2355 rtfree_locked(gwrt
); /* rt != gwrt, no deadlock */
2356 /* Release extra ref */
2357 RT_REMREF_LOCKED(rt
);
2358 return ((rt
->rt_flags
& RTF_HOST
) ?
2359 EHOSTUNREACH
: ENETUNREACH
);
2362 /* Check again since we dropped the lock above */
2363 if (rt
->rt_flags
& RTF_CONDEMNED
) {
2365 rtfree_locked(gwrt
);
2366 /* Release extra ref */
2367 RT_REMREF_LOCKED(rt
);
2371 /* Set gateway route; callee adds ref to gwrt if non-NULL */
2372 rt_set_gwroute(rt
, dst
, gwrt
);
2375 * In case the (non-scoped) default route gets modified via
2376 * an ICMP redirect, record the interface index used for the
2377 * primary ifscope. Also done in rt_setif() to take care
2378 * of the non-redirect cases.
2380 if (rt_primary_default(rt
, dst
) && rt
->rt_ifp
!= NULL
) {
2381 set_primary_ifscope(dst
->sa_family
,
2382 rt
->rt_ifp
->if_index
);
2386 * Tell the kernel debugger about the new default gateway
2387 * if the gateway route uses the primary interface, or
2388 * if we are in a transient state before the non-scoped
2389 * default gateway is installed (similar to how the system
2390 * was behaving in the past). In future, it would be good
2391 * to do all this only when KDP is enabled.
2393 if ((dst
->sa_family
== AF_INET
) &&
2394 gwrt
!= NULL
&& gwrt
->rt_gateway
->sa_family
== AF_LINK
&&
2395 (gwrt
->rt_ifp
->if_index
== get_primary_ifscope(AF_INET
) ||
2396 get_primary_ifscope(AF_INET
) == IFSCOPE_NONE
)) {
2397 kdp_set_gateway_mac(SDL((void *)gwrt
->rt_gateway
)->
2401 /* Release extra ref from rtalloc1() */
2407 * Prepare to store the gateway in rt_gateway. Both dst and gateway
2408 * are stored one after the other in the same malloc'd chunk. If we
2409 * have room, reuse the old buffer since rt_gateway already points
2410 * to the right place. Otherwise, malloc a new block and update
2411 * the 'dst' address and point rt_gateway to the right place.
2413 if (rt
->rt_gateway
== NULL
|| glen
> SA_SIZE(rt
->rt_gateway
->sa_len
)) {
2416 /* The underlying allocation is done with M_WAITOK set */
2417 R_Malloc(new, caddr_t
, dlen
+ glen
);
2419 /* Clear gateway route */
2420 rt_set_gwroute(rt
, dst
, NULL
);
2421 /* Release extra ref */
2422 RT_REMREF_LOCKED(rt
);
2427 * Copy from 'dst' and not rt_key(rt) because we can get
2428 * here to initialize a newly allocated route entry, in
2429 * which case rt_key(rt) is NULL (and so does rt_gateway).
2431 bzero(new, dlen
+ glen
);
2432 Bcopy(dst
, new, dst
->sa_len
);
2433 R_Free(rt_key(rt
)); /* free old block; NULL is okay */
2434 rt
->rt_nodes
->rn_key
= new;
2435 rt
->rt_gateway
= (struct sockaddr
*)(new + dlen
);
2439 * Copy the new gateway value into the memory chunk.
2441 Bcopy(gate
, rt
->rt_gateway
, gate
->sa_len
);
2444 * For consistency between rt_gateway and rt_key(gwrt).
2446 if ((rt
->rt_flags
& RTF_GATEWAY
) && rt
->rt_gwroute
!= NULL
&&
2447 (rt
->rt_gwroute
->rt_flags
& RTF_IFSCOPE
)) {
2448 if (rt
->rt_gateway
->sa_family
== AF_INET
&&
2449 rt_key(rt
->rt_gwroute
)->sa_family
== AF_INET
) {
2450 sin_set_ifscope(rt
->rt_gateway
,
2451 sin_get_ifscope(rt_key(rt
->rt_gwroute
)));
2452 } else if (rt
->rt_gateway
->sa_family
== AF_INET6
&&
2453 rt_key(rt
->rt_gwroute
)->sa_family
== AF_INET6
) {
2454 sin6_set_ifscope(rt
->rt_gateway
,
2455 sin6_get_ifscope(rt_key(rt
->rt_gwroute
)));
2460 * This isn't going to do anything useful for host routes, so
2461 * don't bother. Also make sure we have a reasonable mask
2462 * (we don't yet have one during adds).
2464 if (!(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != 0) {
2465 struct rtfc_arg arg
;
2469 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
2470 rt_fixchange
, &arg
);
2474 /* Release extra ref */
2475 RT_REMREF_LOCKED(rt
);
2482 rt_set_gwroute(struct rtentry
*rt
, struct sockaddr
*dst
, struct rtentry
*gwrt
)
2484 boolean_t gwrt_isrouter
;
2486 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2487 RT_LOCK_ASSERT_HELD(rt
);
2490 RT_ADDREF(gwrt
); /* for this routine */
2493 * Get rid of existing gateway route; if rt_gwroute is already
2494 * set to gwrt, this is slightly redundant (though safe since
2495 * we held an extra ref above) but makes the code simpler.
2497 if (rt
->rt_gwroute
!= NULL
) {
2498 struct rtentry
*ogwrt
= rt
->rt_gwroute
;
2500 VERIFY(rt
!= ogwrt
); /* sanity check */
2501 rt
->rt_gwroute
= NULL
;
2503 rtfree_locked(ogwrt
);
2505 VERIFY(rt
->rt_gwroute
== NULL
);
2509 * And associate the new gateway route.
2511 if ((rt
->rt_gwroute
= gwrt
) != NULL
) {
2512 RT_ADDREF(gwrt
); /* for rt */
2514 if (rt
->rt_flags
& RTF_WASCLONED
) {
2515 /* rt_parent might be NULL if rt is embryonic */
2516 gwrt_isrouter
= (rt
->rt_parent
!= NULL
&&
2517 SA_DEFAULT(rt_key(rt
->rt_parent
)) &&
2518 !RT_HOST(rt
->rt_parent
));
2520 gwrt_isrouter
= (SA_DEFAULT(dst
) && !RT_HOST(rt
));
2523 /* If gwrt points to a default router, mark it accordingly */
2524 if (gwrt_isrouter
&& RT_HOST(gwrt
) &&
2525 !(gwrt
->rt_flags
& RTF_ROUTER
)) {
2527 gwrt
->rt_flags
|= RTF_ROUTER
;
2531 RT_REMREF(gwrt
); /* for this routine */
2536 rt_maskedcopy(struct sockaddr
*src
, struct sockaddr
*dst
,
2537 struct sockaddr
*netmask
)
2539 u_char
*cp1
= (u_char
*)src
;
2540 u_char
*cp2
= (u_char
*)dst
;
2541 u_char
*cp3
= (u_char
*)netmask
;
2542 u_char
*cplim
= cp2
+ *cp3
;
2543 u_char
*cplim2
= cp2
+ *cp1
;
2545 *cp2
++ = *cp1
++; *cp2
++ = *cp1
++; /* copies sa_len & sa_family */
2550 *cp2
++ = *cp1
++ & *cp3
++;
2552 bzero((caddr_t
)cp2
, (unsigned)(cplim2
- cp2
));
2556 * Lookup an AF_INET/AF_INET6 scoped or non-scoped route depending on the
2557 * ifscope value passed in by the caller (IFSCOPE_NONE implies non-scoped).
2559 static struct radix_node
*
2560 node_lookup(struct sockaddr
*dst
, struct sockaddr
*netmask
,
2561 unsigned int ifscope
)
2563 struct radix_node_head
*rnh
;
2564 struct radix_node
*rn
;
2565 struct sockaddr_storage ss
, mask
;
2566 int af
= dst
->sa_family
;
2567 struct matchleaf_arg ma
= { ifscope
};
2568 rn_matchf_t
*f
= rn_match_ifscope
;
2571 if (af
!= AF_INET
&& af
!= AF_INET6
)
2574 rnh
= rt_tables
[af
];
2577 * Transform dst into the internal routing table form,
2578 * clearing out the scope ID field if ifscope isn't set.
2580 dst
= sa_copy(dst
, &ss
, (ifscope
== IFSCOPE_NONE
) ? NULL
: &ifscope
);
2582 /* Transform netmask into the internal routing table form */
2583 if (netmask
!= NULL
)
2584 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
2586 if (ifscope
== IFSCOPE_NONE
)
2589 rn
= rnh
->rnh_lookup_args(dst
, netmask
, rnh
, f
, w
);
2590 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2597 * Lookup the AF_INET/AF_INET6 non-scoped default route.
2599 static struct radix_node
*
2600 node_lookup_default(int af
)
2602 struct radix_node_head
*rnh
;
2604 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
2605 rnh
= rt_tables
[af
];
2607 return (af
== AF_INET
? rnh
->rnh_lookup(&sin_def
, NULL
, rnh
) :
2608 rnh
->rnh_lookup(&sin6_def
, NULL
, rnh
));
2612 * Common routine to lookup/match a route. It invokes the lookup/matchaddr
2613 * callback which could be address family-specific. The main difference
2614 * between the two (at least for AF_INET/AF_INET6) is that a lookup does
2615 * not alter the expiring state of a route, whereas a match would unexpire
2616 * or revalidate the route.
2618 * The optional scope or interface index property of a route allows for a
2619 * per-interface route instance. This permits multiple route entries having
2620 * the same destination (but not necessarily the same gateway) to exist in
2621 * the routing table; each of these entries is specific to the corresponding
2622 * interface. This is made possible by storing the scope ID value into the
2623 * radix key, thus making each route entry unique. These scoped entries
2624 * exist along with the regular, non-scoped entries in the same radix tree
2625 * for a given address family (AF_INET/AF_INET6); the scope logically
2626 * partitions it into multiple per-interface sub-trees.
2628 * When a scoped route lookup is performed, the routing table is searched for
2629 * the best match that would result in a route using the same interface as the
2630 * one associated with the scope (the exception to this are routes that point
2631 * to the loopback interface). The search rule follows the longest matching
2632 * prefix with the additional interface constraint.
2635 rt_lookup(boolean_t lookup_only
, struct sockaddr
*dst
, struct sockaddr
*netmask
,
2636 struct radix_node_head
*rnh
, unsigned int ifscope
)
2638 struct radix_node
*rn0
, *rn
;
2640 int af
= dst
->sa_family
;
2641 struct sockaddr_storage dst_ss
, mask_ss
;
2643 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2649 * Non-scoped route lookup.
2652 if ((af
!= AF_INET
&& af
!= AF_INET6
) ||
2653 (af
== AF_INET
&& !ip_doscopedroute
) ||
2654 (af
== AF_INET6
&& !ip6_doscopedroute
)) {
2656 if (af
!= AF_INET
|| !ip_doscopedroute
) {
2658 rn
= rnh
->rnh_matchaddr(dst
, rnh
);
2661 * Don't return a root node; also, rnh_matchaddr callback
2662 * would have done the necessary work to clear RTPRF_OURS
2663 * for certain protocol families.
2665 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2668 RT_LOCK_SPIN(RT(rn
));
2669 if (!(RT(rn
)->rt_flags
& RTF_CONDEMNED
)) {
2670 RT_ADDREF_LOCKED(RT(rn
));
2680 /* Transform dst/netmask into the internal routing table form */
2681 dst
= sa_copy(dst
, &dst_ss
, &ifscope
);
2682 if (netmask
!= NULL
)
2683 netmask
= ma_copy(af
, netmask
, &mask_ss
, ifscope
);
2684 dontcare
= (ifscope
== IFSCOPE_NONE
);
2687 * Scoped route lookup:
2689 * We first perform a non-scoped lookup for the original result.
2690 * Afterwards, depending on whether or not the caller has specified
2691 * a scope, we perform a more specific scoped search and fallback
2692 * to this original result upon failure.
2694 rn0
= rn
= node_lookup(dst
, netmask
, IFSCOPE_NONE
);
2697 * If the caller did not specify a scope, use the primary scope
2698 * derived from the system's non-scoped default route. If, for
2699 * any reason, there is no primary interface, ifscope will be
2700 * set to IFSCOPE_NONE; if the above lookup resulted in a route,
2701 * we'll do a more-specific search below, scoped to the interface
2705 ifscope
= get_primary_ifscope(af
);
2708 * Keep the original result if either of the following is true:
2710 * 1) The interface portion of the route has the same interface
2711 * index as the scope value and it is marked with RTF_IFSCOPE.
2712 * 2) The route uses the loopback interface, in which case the
2713 * destination (host/net) is local/loopback.
2715 * Otherwise, do a more specified search using the scope;
2716 * we're holding rnh_lock now, so rt_ifp should not change.
2719 struct rtentry
*rt
= RT(rn
);
2720 if (rt
->rt_ifp
!= lo_ifp
) {
2721 if (rt
->rt_ifp
->if_index
!= ifscope
) {
2723 * Wrong interface; keep the original result
2724 * only if the caller did not specify a scope,
2725 * and do a more specific scoped search using
2726 * the scope of the found route. Otherwise,
2727 * start again from scratch.
2731 ifscope
= rt
->rt_ifp
->if_index
;
2734 } else if (!(rt
->rt_flags
& RTF_IFSCOPE
)) {
2736 * Right interface, except that this route
2737 * isn't marked with RTF_IFSCOPE. Do a more
2738 * specific scoped search. Keep the original
2739 * result and return it it in case the scoped
2748 * Scoped search. Find the most specific entry having the same
2749 * interface scope as the one requested. The following will result
2750 * in searching for the longest prefix scoped match.
2753 rn
= node_lookup(dst
, netmask
, ifscope
);
2756 * Use the original result if either of the following is true:
2758 * 1) The scoped search did not yield any result.
2759 * 2) The result from the scoped search is a scoped default route,
2760 * and the original (non-scoped) result is not a default route,
2761 * i.e. the original result is a more specific host/net route.
2762 * 3) The scoped search yielded a net route but the original
2763 * result is a host route, i.e. the original result is treated
2764 * as a more specific route.
2766 if (rn
== NULL
|| (rn0
!= NULL
&&
2767 ((SA_DEFAULT(rt_key(RT(rn
))) && !SA_DEFAULT(rt_key(RT(rn0
)))) ||
2768 (!RT_HOST(rn
) && RT_HOST(rn0
)))))
2772 * If we still don't have a route, use the non-scoped default
2773 * route as long as the interface portion satistifes the scope.
2775 if (rn
== NULL
&& (rn
= node_lookup_default(af
)) != NULL
&&
2776 RT(rn
)->rt_ifp
->if_index
!= ifscope
)
2781 * Manually clear RTPRF_OURS using rt_validate() and
2782 * bump up the reference count after, and not before;
2783 * we only get here for AF_INET/AF_INET6. node_lookup()
2784 * has done the check against RNF_ROOT, so we can be sure
2785 * that we're not returning a root node here.
2787 RT_LOCK_SPIN(RT(rn
));
2788 if (rt_validate(RT(rn
))) {
2789 RT_ADDREF_LOCKED(RT(rn
));
2801 rt_validate(struct rtentry
*rt
)
2803 RT_LOCK_ASSERT_HELD(rt
);
2805 if ((rt
->rt_flags
& (RTF_UP
| RTF_CONDEMNED
)) == RTF_UP
) {
2806 int af
= rt_key(rt
)->sa_family
;
2809 (void) in_validate(RN(rt
));
2810 else if (af
== AF_INET6
)
2811 (void) in6_validate(RN(rt
));
2816 return (rt
!= NULL
);
2820 * Set up a routing table entry, normally
2824 rtinit(struct ifaddr
*ifa
, int cmd
, int flags
)
2827 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2828 lck_mtx_lock(rnh_lock
);
2829 error
= rtinit_locked(ifa
, cmd
, flags
);
2830 lck_mtx_unlock(rnh_lock
);
2835 rtinit_locked(struct ifaddr
*ifa
, int cmd
, int flags
)
2838 struct sockaddr
*dst
;
2839 struct sockaddr
*deldst
;
2841 struct rtentry
*nrt
= 0;
2842 u_int32_t ifa_flags
;
2846 * Holding rnh_lock here prevents the possibility of ifa from
2847 * changing (e.g. in_ifinit), so it is safe to access its
2848 * ifa_{dst}addr (here and down below) without locking.
2850 dst
= flags
& RTF_HOST
? ifa
->ifa_dstaddr
: ifa
->ifa_addr
;
2852 * If it's a delete, check that if it exists, it's on the correct
2853 * interface or we might scrub a route to another ifa which would
2854 * be confusing at best and possibly worse.
2856 if (cmd
== RTM_DELETE
) {
2858 * It's a delete, so it should already exist..
2859 * If it's a net, mask off the host bits
2860 * (Assuming we have a mask)
2862 if ((flags
& RTF_HOST
) == 0 && ifa
->ifa_netmask
) {
2863 m
= m_get(M_DONTWAIT
, MT_SONAME
);
2867 deldst
= mtod(m
, struct sockaddr
*);
2868 rt_maskedcopy(dst
, deldst
, ifa
->ifa_netmask
);
2872 * Get an rtentry that is in the routing tree and
2873 * contains the correct info. (if this fails, can't get there).
2874 * We set "report" to FALSE so that if it doesn't exist,
2875 * it doesn't report an error or clone a route, etc. etc.
2877 rt
= rtalloc1_locked(dst
, 0, 0);
2880 * Ok so we found the rtentry. it has an extra reference
2881 * for us at this stage. we won't need that so
2885 if (rt
->rt_ifa
!= ifa
) {
2886 RT_REMREF_LOCKED(rt
);
2889 * If the interface in the rtentry doesn't match
2890 * the interface we are using, then we don't
2891 * want to delete it, so return an error.
2892 * This seems to be the only point of
2893 * this whole RTM_DELETE clause.
2897 return (flags
& RTF_HOST
? EHOSTUNREACH
2900 RT_REMREF_LOCKED(rt
);
2908 * One would think that as we are deleting, and we know
2909 * it doesn't exist, we could just return at this point
2910 * with an "ELSE" clause, but apparently not..
2912 lck_mtx_unlock(rnh_lock
);
2913 return (flags
& RTF_HOST
? EHOSTUNREACH
2919 * Do the actual request
2922 ifa_flags
= ifa
->ifa_flags
;
2924 error
= rtrequest_locked(cmd
, dst
, ifa
->ifa_addr
, ifa
->ifa_netmask
,
2925 flags
| ifa_flags
, &nrt
);
2929 * If we are deleting, and we found an entry, then
2930 * it's been removed from the tree.. now throw it away.
2932 if (cmd
== RTM_DELETE
&& error
== 0 && (rt
= nrt
)) {
2934 * notify any listening routing agents of the change
2937 rt_newaddrmsg(cmd
, ifa
, error
, nrt
);
2939 routegenid_update();
2945 * We are adding, and we have a returned routing entry.
2946 * We need to sanity check the result.
2948 if (cmd
== RTM_ADD
&& error
== 0 && (rt
= nrt
)) {
2951 * If it came back with an unexpected interface, then it must
2952 * have already existed or something. (XXX)
2954 if (rt
->rt_ifa
!= ifa
) {
2955 void (*ifa_rtrequest
)
2956 (int, struct rtentry
*, struct sockaddr
*);
2958 if (!(rt
->rt_ifa
->ifa_ifp
->if_flags
&
2959 (IFF_POINTOPOINT
|IFF_LOOPBACK
)))
2960 printf("rtinit: wrong ifa (%p) was (%p)\n",
2963 * Ask that the protocol in question
2964 * remove anything it has associated with
2965 * this route and ifaddr.
2967 IFA_LOCK_SPIN(rt
->rt_ifa
);
2968 ifa_rtrequest
= rt
->rt_ifa
->ifa_rtrequest
;
2969 IFA_UNLOCK(rt
->rt_ifa
);
2970 if (ifa_rtrequest
!= NULL
)
2971 ifa_rtrequest(RTM_DELETE
, rt
, SA(0));
2973 * Set the route's ifa.
2977 if (rt
->rt_ifp
!= ifa
->ifa_ifp
) {
2979 * Purge any link-layer info caching.
2981 if (rt
->rt_llinfo_purge
!= NULL
)
2982 rt
->rt_llinfo_purge(rt
);
2984 * Adjust route ref count for the interfaces.
2986 if (rt
->rt_if_ref_fn
!= NULL
) {
2987 rt
->rt_if_ref_fn(ifa
->ifa_ifp
, 1);
2988 rt
->rt_if_ref_fn(rt
->rt_ifp
, -1);
2993 * And substitute in references to the ifaddr
2996 rt
->rt_ifp
= ifa
->ifa_ifp
;
2997 rt
->rt_rmx
.rmx_mtu
= ifa
->ifa_ifp
->if_mtu
; /*XXX*/
2999 * Now ask the protocol to check if it needs
3000 * any special processing in its new form.
3003 ifa_rtrequest
= ifa
->ifa_rtrequest
;
3005 if (ifa_rtrequest
!= NULL
)
3006 ifa_rtrequest(RTM_ADD
, rt
, SA(0));
3009 * notify any listenning routing agents of the change
3011 rt_newaddrmsg(cmd
, ifa
, error
, nrt
);
3013 routegenid_update();
3015 * We just wanted to add it; we don't actually need a
3016 * reference. This will result in a route that's added
3017 * to the routing table without a reference count. The
3018 * RTM_DELETE code will do the necessary step to adjust
3019 * the reference count at deletion time.
3021 RT_REMREF_LOCKED(rt
);
3028 rt_expiry(struct rtentry
*rt
, u_int64_t base
, u_int32_t delta
)
3033 * If the interface of the route doesn't demand aggressive draining,
3034 * return the expiration time based on the caller-supplied delta.
3035 * Otherwise use the more aggressive route expiration delta (or
3036 * the caller-supplied delta, whichever is less.)
3038 if (rt
->rt_ifp
== NULL
|| rt
->rt_ifp
->if_want_aggressive_drain
== 0)
3039 retval
= base
+ delta
;
3041 retval
= base
+ MIN(rt_if_idle_expire_timeout
, delta
);
3047 rt_set_idleref(struct rtentry
*rt
)
3049 RT_LOCK_ASSERT_HELD(rt
);
3051 rt_clear_idleref(rt
);
3052 rt
->rt_if_ref_fn
= rte_if_ref
;
3053 rt
->rt_if_ref_fn(rt
->rt_ifp
, 1);
3054 rt
->rt_flags
|= RTF_IFREF
;
3058 rt_clear_idleref(struct rtentry
*rt
)
3060 RT_LOCK_ASSERT_HELD(rt
);
3062 if (rt
->rt_if_ref_fn
!= NULL
) {
3063 rt
->rt_if_ref_fn(rt
->rt_ifp
, -1);
3064 rt
->rt_flags
&= ~RTF_IFREF
;
3065 rt
->rt_if_ref_fn
= NULL
;
3070 rt_set_proxy(struct rtentry
*rt
, boolean_t set
)
3072 lck_mtx_lock(rnh_lock
);
3075 * Search for any cloned routes which might have
3076 * been formed from this node, and delete them.
3078 if (rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) {
3079 struct radix_node_head
*rnh
= rt_tables
[rt_key(rt
)->sa_family
];
3082 rt
->rt_flags
|= RTF_PROXY
;
3084 rt
->rt_flags
&= ~RTF_PROXY
;
3087 if (rnh
!= NULL
&& rt_mask(rt
)) {
3088 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
3094 lck_mtx_unlock(rnh_lock
);
3098 rte_lock_init(struct rtentry
*rt
)
3100 lck_mtx_init(&rt
->rt_lock
, rte_mtx_grp
, rte_mtx_attr
);
3104 rte_lock_destroy(struct rtentry
*rt
)
3106 RT_LOCK_ASSERT_NOTHELD(rt
);
3107 lck_mtx_destroy(&rt
->rt_lock
, rte_mtx_grp
);
3111 rt_lock(struct rtentry
*rt
, boolean_t spin
)
3113 RT_LOCK_ASSERT_NOTHELD(rt
);
3115 lck_mtx_lock_spin(&rt
->rt_lock
);
3117 lck_mtx_lock(&rt
->rt_lock
);
3118 if (rte_debug
& RTD_DEBUG
)
3119 rte_lock_debug((struct rtentry_dbg
*)rt
);
3123 rt_unlock(struct rtentry
*rt
)
3125 RT_LOCK_ASSERT_HELD(rt
);
3126 if (rte_debug
& RTD_DEBUG
)
3127 rte_unlock_debug((struct rtentry_dbg
*)rt
);
3128 lck_mtx_unlock(&rt
->rt_lock
);
3133 rte_lock_debug(struct rtentry_dbg
*rte
)
3137 idx
= atomic_add_32_ov(&rte
->rtd_lock_cnt
, 1) % CTRACE_HIST_SIZE
;
3138 if (rte_debug
& RTD_TRACE
)
3139 ctrace_record(&rte
->rtd_lock
[idx
]);
3143 rte_unlock_debug(struct rtentry_dbg
*rte
)
3147 idx
= atomic_add_32_ov(&rte
->rtd_unlock_cnt
, 1) % CTRACE_HIST_SIZE
;
3148 if (rte_debug
& RTD_TRACE
)
3149 ctrace_record(&rte
->rtd_unlock
[idx
]);
3152 static struct rtentry
*
3155 if (rte_debug
& RTD_DEBUG
)
3156 return (rte_alloc_debug());
3158 return ((struct rtentry
*)zalloc(rte_zone
));
3162 rte_free(struct rtentry
*p
)
3164 if (rte_debug
& RTD_DEBUG
) {
3169 if (p
->rt_refcnt
!= 0)
3170 panic("rte_free: rte=%p refcnt=%d non-zero\n", p
, p
->rt_refcnt
);
3176 rte_if_ref(struct ifnet
*ifp
, int cnt
)
3178 struct kev_msg ev_msg
;
3179 struct net_event_data ev_data
;
3182 /* Force cnt to 1 increment/decrement */
3183 if (cnt
< -1 || cnt
> 1)
3184 panic("%s: invalid count argument (%d)", __func__
, cnt
);
3186 old
= atomic_add_32_ov(&ifp
->if_route_refcnt
, cnt
);
3187 if (cnt
< 0 && old
== 0)
3188 panic("%s: ifp=%p negative route refcnt!", __func__
, ifp
);
3191 * The following is done without first holding the ifnet lock,
3192 * for performance reasons. The relevant ifnet fields, with
3193 * the exception of the if_idle_flags, are never changed
3194 * during the lifetime of the ifnet. The if_idle_flags
3195 * may possibly be modified, so in the event that the value
3196 * is stale because IFRF_IDLE_NOTIFY was cleared, we'd end up
3197 * sending the event anyway. This is harmless as it is just
3198 * a notification to the monitoring agent in user space, and
3199 * it is expected to check via SIOCGIFGETRTREFCNT again anyway.
3201 if ((ifp
->if_idle_flags
& IFRF_IDLE_NOTIFY
) && cnt
< 0 && old
== 1) {
3202 bzero(&ev_msg
, sizeof (ev_msg
));
3203 bzero(&ev_data
, sizeof (ev_data
));
3205 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
3206 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
3207 ev_msg
.kev_subclass
= KEV_DL_SUBCLASS
;
3208 ev_msg
.event_code
= KEV_DL_IF_IDLE_ROUTE_REFCNT
;
3210 strlcpy(&ev_data
.if_name
[0], ifp
->if_name
, IFNAMSIZ
);
3212 ev_data
.if_family
= ifp
->if_family
;
3213 ev_data
.if_unit
= ifp
->if_unit
;
3214 ev_msg
.dv
[0].data_length
= sizeof (struct net_event_data
);
3215 ev_msg
.dv
[0].data_ptr
= &ev_data
;
3217 kev_post_msg(&ev_msg
);
3221 static inline struct rtentry
*
3222 rte_alloc_debug(void)
3224 struct rtentry_dbg
*rte
;
3226 rte
= ((struct rtentry_dbg
*)zalloc(rte_zone
));
3228 bzero(rte
, sizeof (*rte
));
3229 if (rte_debug
& RTD_TRACE
)
3230 ctrace_record(&rte
->rtd_alloc
);
3231 rte
->rtd_inuse
= RTD_INUSE
;
3233 return ((struct rtentry
*)rte
);
3237 rte_free_debug(struct rtentry
*p
)
3239 struct rtentry_dbg
*rte
= (struct rtentry_dbg
*)p
;
3241 if (p
->rt_refcnt
!= 0)
3242 panic("rte_free: rte=%p refcnt=%d\n", p
, p
->rt_refcnt
);
3244 if (rte
->rtd_inuse
== RTD_FREED
)
3245 panic("rte_free: double free rte=%p\n", rte
);
3246 else if (rte
->rtd_inuse
!= RTD_INUSE
)
3247 panic("rte_free: corrupted rte=%p\n", rte
);
3249 bcopy((caddr_t
)p
, (caddr_t
)&rte
->rtd_entry_saved
, sizeof (*p
));
3250 /* Preserve rt_lock to help catch use-after-free cases */
3251 bzero((caddr_t
)p
, offsetof(struct rtentry
, rt_lock
));
3253 rte
->rtd_inuse
= RTD_FREED
;
3255 if (rte_debug
& RTD_TRACE
)
3256 ctrace_record(&rte
->rtd_free
);
3258 if (!(rte_debug
& RTD_NO_FREE
))
3263 ctrace_record(ctrace_t
*tr
)
3265 tr
->th
= current_thread();
3266 bzero(tr
->pc
, sizeof (tr
->pc
));
3267 (void) OSBacktrace(tr
->pc
, CTRACE_STACK_SIZE
);
3270 __private_extern__
void
3273 const struct route
*src
,
3276 /* Copy everything (rt, dst, flags) from ifnet */
3277 bcopy(src
, dst
, length
);
3279 /* Hold one reference for the local copy of struct route */
3280 if (dst
->ro_rt
!= NULL
)
3281 RT_ADDREF(dst
->ro_rt
);
3284 __private_extern__
void
3290 /* No cached route in the ifnet? */
3291 if (dst
->ro_rt
== NULL
) {
3293 * Copy everything (rt, dst, flags) from ip_forward();
3294 * the reference to the route was held at the time
3295 * it was allocated and is kept intact.
3297 bcopy(src
, dst
, length
);
3298 } else if (src
->ro_rt
!= NULL
) {
3300 * If the same, update just the ro_flags and ditch the one
3301 * in the local copy. Else ditch the one that is currently
3302 * cached, and cache the new route.
3304 if (dst
->ro_rt
== src
->ro_rt
) {
3305 dst
->ro_flags
= src
->ro_flags
;
3309 bcopy(src
, dst
, length
);
3313 /* This function consumes the reference */
3318 * route_to_gwroute will find the gateway route for a given route.
3320 * If the route is down, look the route up again.
3321 * If the route goes through a gateway, get the route to the gateway.
3322 * If the gateway route is down, look it up again.
3323 * If the route is set to reject, verify it hasn't expired.
3325 * If the returned route is non-NULL, the caller is responsible for
3326 * releasing the reference and unlocking the route.
3328 #define senderr(e) { error = (e); goto bad; }
3330 route_to_gwroute(const struct sockaddr
*net_dest
, struct rtentry
*hint0
,
3331 struct rtentry
**out_route
)
3334 struct rtentry
*rt
= hint0
, *hint
= hint0
;
3336 unsigned int ifindex
;
3345 * Next hop determination. Because we may involve the gateway route
3346 * in addition to the original route, locking is rather complicated.
3347 * The general concept is that regardless of whether the route points
3348 * to the original route or to the gateway route, this routine takes
3349 * an extra reference on such a route. This extra reference will be
3350 * released at the end.
3352 * Care must be taken to ensure that the "hint0" route never gets freed
3353 * via rtfree(), since the caller may have stored it inside a struct
3354 * route with a reference held for that placeholder.
3357 ifindex
= rt
->rt_ifp
->if_index
;
3358 RT_ADDREF_LOCKED(rt
);
3359 if (!(rt
->rt_flags
& RTF_UP
)) {
3360 RT_REMREF_LOCKED(rt
);
3362 /* route is down, find a new one */
3363 hint
= rt
= rtalloc1_scoped((struct sockaddr
*)
3364 (size_t)net_dest
, 1, 0, ifindex
);
3367 ifindex
= rt
->rt_ifp
->if_index
;
3369 senderr(EHOSTUNREACH
);
3374 * We have a reference to "rt" by now; it will either
3375 * be released or freed at the end of this routine.
3377 RT_LOCK_ASSERT_HELD(rt
);
3378 if ((gwroute
= (rt
->rt_flags
& RTF_GATEWAY
))) {
3379 struct rtentry
*gwrt
= rt
->rt_gwroute
;
3380 struct sockaddr_storage ss
;
3381 struct sockaddr
*gw
= (struct sockaddr
*)&ss
;
3384 RT_ADDREF_LOCKED(hint
);
3386 /* If there's no gateway rt, look it up */
3388 bcopy(rt
->rt_gateway
, gw
, MIN(sizeof (ss
),
3389 rt
->rt_gateway
->sa_len
));
3393 /* Become a regular mutex */
3394 RT_CONVERT_LOCK(rt
);
3397 * Take gwrt's lock while holding route's lock;
3398 * this is okay since gwrt never points back
3399 * to "rt", so no lock ordering issues.
3402 if (!(gwrt
->rt_flags
& RTF_UP
)) {
3403 rt
->rt_gwroute
= NULL
;
3405 bcopy(rt
->rt_gateway
, gw
, MIN(sizeof (ss
),
3406 rt
->rt_gateway
->sa_len
));
3410 lck_mtx_lock(rnh_lock
);
3411 gwrt
= rtalloc1_scoped_locked(gw
, 1, 0, ifindex
);
3415 * Bail out if the route is down, no route
3416 * to gateway, circular route, or if the
3417 * gateway portion of "rt" has changed.
3419 if (!(rt
->rt_flags
& RTF_UP
) || gwrt
== NULL
||
3420 gwrt
== rt
|| !equal(gw
, rt
->rt_gateway
)) {
3422 RT_REMREF_LOCKED(gwrt
);
3426 RT_REMREF_LOCKED(hint
);
3430 rtfree_locked(gwrt
);
3431 lck_mtx_unlock(rnh_lock
);
3432 senderr(EHOSTUNREACH
);
3434 VERIFY(gwrt
!= NULL
);
3436 * Set gateway route; callee adds ref to gwrt;
3437 * gwrt has an extra ref from rtalloc1() for
3440 rt_set_gwroute(rt
, rt_key(rt
), gwrt
);
3442 RT_REMREF_LOCKED(rt
); /* hint still holds a refcnt */
3444 lck_mtx_unlock(rnh_lock
);
3447 RT_ADDREF_LOCKED(gwrt
);
3450 RT_REMREF_LOCKED(rt
); /* hint still holds a refcnt */
3454 VERIFY(rt
== gwrt
&& rt
!= hint
);
3457 * This is an opportunity to revalidate the parent route's
3458 * rt_gwroute, in case it now points to a dead route entry.
3459 * Parent route won't go away since the clone (hint) holds
3460 * a reference to it. rt == gwrt.
3463 if ((hint
->rt_flags
& (RTF_WASCLONED
| RTF_UP
)) ==
3464 (RTF_WASCLONED
| RTF_UP
)) {
3465 struct rtentry
*prt
= hint
->rt_parent
;
3466 VERIFY(prt
!= NULL
);
3468 RT_CONVERT_LOCK(hint
);
3471 rt_revalidate_gwroute(prt
, rt
);
3477 /* Clean up "hint" now; see notes above regarding hint0 */
3484 /* rt == gwrt; if it is now down, give up */
3486 if (!(rt
->rt_flags
& RTF_UP
)) {
3488 senderr(EHOSTUNREACH
);
3492 if (rt
->rt_flags
& RTF_REJECT
) {
3493 VERIFY(rt
->rt_expire
== 0 || rt
->rt_rmx
.rmx_expire
!= 0);
3494 VERIFY(rt
->rt_expire
!= 0 || rt
->rt_rmx
.rmx_expire
== 0);
3495 timenow
= net_uptime();
3496 if (rt
->rt_expire
== 0 || timenow
< rt
->rt_expire
) {
3498 senderr(!gwroute
? EHOSTDOWN
: EHOSTUNREACH
);
3502 /* Become a regular mutex */
3503 RT_CONVERT_LOCK(rt
);
3505 /* Caller is responsible for cleaning up "rt" */
3510 /* Clean up route (either it is "rt" or "gwrt") */
3514 RT_REMREF_LOCKED(rt
);
3526 rt_revalidate_gwroute(struct rtentry
*rt
, struct rtentry
*gwrt
)
3528 VERIFY(rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
));
3529 VERIFY(gwrt
!= NULL
);
3532 if ((rt
->rt_flags
& (RTF_GATEWAY
| RTF_UP
)) == (RTF_GATEWAY
| RTF_UP
) &&
3533 rt
->rt_ifp
== gwrt
->rt_ifp
&& rt
->rt_gateway
->sa_family
==
3534 rt_key(gwrt
)->sa_family
&& (rt
->rt_gwroute
== NULL
||
3535 !(rt
->rt_gwroute
->rt_flags
& RTF_UP
))) {
3538 if (rt
->rt_gateway
->sa_family
== AF_INET
||
3539 rt
->rt_gateway
->sa_family
== AF_INET6
) {
3540 struct sockaddr_storage key_ss
, gw_ss
;
3542 * We need to compare rt_key and rt_gateway; create
3543 * local copies to get rid of any ifscope association.
3545 (void) sa_copy(rt_key(gwrt
), &key_ss
, NULL
);
3546 (void) sa_copy(rt
->rt_gateway
, &gw_ss
, NULL
);
3548 isequal
= equal(SA(&key_ss
), SA(&gw_ss
));
3550 isequal
= equal(rt_key(gwrt
), rt
->rt_gateway
);
3553 /* If they are the same, update gwrt */
3556 lck_mtx_lock(rnh_lock
);
3558 rt_set_gwroute(rt
, rt_key(rt
), gwrt
);
3560 lck_mtx_unlock(rnh_lock
);