]>
git.saurik.com Git - apple/xnu.git/blob - bsd/net/route.c
2 * Copyright (c) 2000-2008 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/systm.h>
66 #include <sys/malloc.h>
68 #include <sys/socket.h>
69 #include <sys/domain.h>
70 #include <sys/syslog.h>
71 #include <sys/queue.h>
72 #include <kern/lock.h>
73 #include <kern/zalloc.h>
76 #include <net/route.h>
78 #include <netinet/in.h>
79 #include <netinet/in_var.h>
80 #include <netinet/ip_mroute.h>
81 #include <netinet/ip_var.h>
83 #include <net/if_dl.h>
85 #include <libkern/OSAtomic.h>
86 #include <libkern/OSDebug.h>
88 #include <pexpert/pexpert.h>
91 * Synchronization notes:
93 * Routing entries fall under two locking domains: the global routing table
94 * lock (rnh_lock) and the per-entry lock (rt_lock); the latter is a mutex that
95 * resides (statically defined) in the rtentry structure.
97 * The locking domains for routing are defined as follows:
99 * The global routing lock is used to serialize all accesses to the radix
100 * trees defined by rt_tables[], as well as the tree of masks. This includes
101 * lookups, insertions and removals of nodes to/from the respective tree.
102 * It is also used to protect certain fields in the route entry that aren't
103 * often modified and/or require global serialization (more details below.)
105 * The per-route entry lock is used to serialize accesses to several routing
106 * entry fields (more details below.) Acquiring and releasing this lock is
107 * done via RT_LOCK() and RT_UNLOCK() routines.
109 * In cases where both rnh_lock and rt_lock must be held, the former must be
110 * acquired first in order to maintain lock ordering. It is not a requirement
111 * that rnh_lock be acquired first before rt_lock, but in case both must be
112 * acquired in succession, the correct lock ordering must be followed.
114 * The fields of the rtentry structure are protected in the following way:
118 * - Routing table lock (rnh_lock).
120 * rt_parent, rt_mask, rt_llinfo_free
122 * - Set once during creation and never changes; no locks to read.
124 * rt_flags, rt_genmask, rt_llinfo, rt_rmx, rt_refcnt, rt_gwroute
126 * - Routing entry lock (rt_lock) for read/write access.
128 * - Some values of rt_flags are either set once at creation time,
129 * or aren't currently used, and thus checking against them can
130 * be done without rt_lock: RTF_GATEWAY, RTF_HOST, RTF_DYNAMIC,
131 * RTF_DONE, RTF_XRESOLVE, RTF_STATIC, RTF_BLACKHOLE, RTF_ANNOUNCE,
132 * RTF_USETRAILERS, RTF_WASCLONED, RTF_PINNED, RTF_LOCAL,
133 * RTF_BROADCAST, RTF_MULTICAST, RTF_IFSCOPE.
135 * rt_key, rt_gateway, rt_ifp, rt_ifa
137 * - Always written/modified with both rnh_lock and rt_lock held.
139 * - May be read freely with rnh_lock held, else must hold rt_lock
140 * for read access; holding both locks for read is also okay.
142 * - In the event rnh_lock is not acquired, or is not possible to be
143 * acquired across the operation, setting RTF_CONDEMNED on a route
144 * entry will prevent its rt_key, rt_gateway, rt_ifp and rt_ifa
145 * from being modified. This is typically done on a route that
146 * has been chosen for a removal (from the tree) prior to dropping
147 * the rt_lock, so that those values will remain the same until
148 * the route is freed.
150 * When rnh_lock is held rt_setgate(), rt_setif(), and rtsetifa() are
151 * single-threaded, thus exclusive. This flag will also prevent the
152 * route from being looked up via rt_lookup().
156 * - Assumes that 32-bit writes are atomic; no locks.
160 * - Currently unused; no locks.
162 * Operations on a route entry can be described as follows:
164 * CREATE an entry with reference count set to 0 as part of RTM_ADD/RESOLVE.
166 * INSERTION of an entry into the radix tree holds the rnh_lock, checks
167 * for duplicates and then adds the entry. rtrequest returns the entry
168 * after bumping up the reference count to 1 (for the caller).
170 * LOOKUP of an entry holds the rnh_lock and bumps up the reference count
171 * before returning; it is valid to also bump up the reference count using
172 * RT_ADDREF after the lookup has returned an entry.
174 * REMOVAL of an entry from the radix tree holds the rnh_lock, removes the
175 * entry but does not decrement the reference count. Removal happens when
176 * the route is explicitly deleted (RTM_DELETE) or when it is in the cached
177 * state and it expires. The route is said to be "down" when it is no
178 * longer present in the tree. Freeing the entry will happen on the last
179 * reference release of such a "down" route.
181 * RT_ADDREF/RT_REMREF operates on the routing entry which increments/
182 * decrements the reference count, rt_refcnt, atomically on the rtentry.
183 * rt_refcnt is modified only using this routine. The general rule is to
184 * do RT_ADDREF in the function that is passing the entry as an argument,
185 * in order to prevent the entry from being freed by the callee.
188 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
189 #define SA(p) ((struct sockaddr *)(p))
191 extern void kdp_set_gateway_mac (void *gatewaymac
);
193 extern struct domain routedomain
;
194 struct route_cb route_cb
;
195 __private_extern__
struct rtstat rtstat
= { 0, 0, 0, 0, 0 };
196 struct radix_node_head
*rt_tables
[AF_MAX
+1];
198 lck_mtx_t
*rnh_lock
; /* global routing tables mutex */
199 static lck_attr_t
*rnh_lock_attr
;
200 static lck_grp_t
*rnh_lock_grp
;
201 static lck_grp_attr_t
*rnh_lock_grp_attr
;
203 /* Lock group and attribute for routing entry locks */
204 static lck_attr_t
*rte_mtx_attr
;
205 static lck_grp_t
*rte_mtx_grp
;
206 static lck_grp_attr_t
*rte_mtx_grp_attr
;
208 lck_mtx_t
*route_domain_mtx
; /*### global routing tables mutex for now */
209 int rttrash
= 0; /* routes not in table but not freed */
211 unsigned int rte_debug
;
213 /* Possible flags for rte_debug */
214 #define RTD_DEBUG 0x1 /* enable or disable rtentry debug facility */
215 #define RTD_TRACE 0x2 /* trace alloc, free, refcnt and lock */
216 #define RTD_NO_FREE 0x4 /* don't free (good to catch corruptions) */
218 #define RTE_NAME "rtentry" /* name for zone and rt_lock */
220 static struct zone
*rte_zone
; /* special zone for rtentry */
221 #define RTE_ZONE_MAX 65536 /* maximum elements in zone */
222 #define RTE_ZONE_NAME RTE_NAME /* name of rtentry zone */
224 #define RTD_INUSE 0xFEEDFACE /* entry is in use */
225 #define RTD_FREED 0xDEADBEEF /* entry is freed */
228 __private_extern__
unsigned int ctrace_stack_size
= CTRACE_STACK_SIZE
;
229 __private_extern__
unsigned int ctrace_hist_size
= CTRACE_HIST_SIZE
;
232 * Debug variant of rtentry structure.
235 struct rtentry rtd_entry
; /* rtentry */
236 struct rtentry rtd_entry_saved
; /* saved rtentry */
237 uint32_t rtd_inuse
; /* in use pattern */
238 uint16_t rtd_refhold_cnt
; /* # of rtref */
239 uint16_t rtd_refrele_cnt
; /* # of rtunref */
240 uint32_t rtd_lock_cnt
; /* # of locks */
241 uint32_t rtd_unlock_cnt
; /* # of unlocks */
243 * Alloc and free callers.
248 * Circular lists of rtref and rtunref callers.
250 ctrace_t rtd_refhold
[CTRACE_HIST_SIZE
];
251 ctrace_t rtd_refrele
[CTRACE_HIST_SIZE
];
253 * Circular lists of locks and unlocks.
255 ctrace_t rtd_lock
[CTRACE_HIST_SIZE
];
256 ctrace_t rtd_unlock
[CTRACE_HIST_SIZE
];
260 TAILQ_ENTRY(rtentry_dbg
) rtd_trash_link
;
263 #define atomic_add_16_ov(a, n) \
264 ((uint16_t) OSAddAtomic16(n, (volatile SInt16 *)a))
265 #define atomic_add_32_ov(a, n) \
266 ((uint32_t) OSAddAtomic(n, a))
268 /* List of trash route entries protected by rnh_lock */
269 static TAILQ_HEAD(, rtentry_dbg
) rttrash_head
;
271 static void rte_lock_init(struct rtentry
*);
272 static void rte_lock_destroy(struct rtentry
*);
273 static inline struct rtentry
*rte_alloc_debug(void);
274 static inline void rte_free_debug(struct rtentry
*);
275 static inline void rte_lock_debug(struct rtentry_dbg
*);
276 static inline void rte_unlock_debug(struct rtentry_dbg
*);
277 static void rt_maskedcopy(struct sockaddr
*,
278 struct sockaddr
*, struct sockaddr
*);
279 static void rtable_init(void **);
280 static inline void rtref_audit(struct rtentry_dbg
*);
281 static inline void rtunref_audit(struct rtentry_dbg
*);
282 static struct rtentry
*rtalloc1_common_locked(struct sockaddr
*, int, uint32_t,
284 static int rtrequest_common_locked(int, struct sockaddr
*,
285 struct sockaddr
*, struct sockaddr
*, int, struct rtentry
**,
287 static void rtalloc_ign_common_locked(struct route
*, uint32_t, unsigned int);
288 static inline void sa_set_ifscope(struct sockaddr
*, unsigned int);
289 static struct sockaddr
*sin_copy(struct sockaddr_in
*, struct sockaddr_in
*,
291 static struct sockaddr
*mask_copy(struct sockaddr
*, struct sockaddr_in
*,
293 static struct sockaddr
*sa_trim(struct sockaddr
*, int);
294 static struct radix_node
*node_lookup(struct sockaddr
*, struct sockaddr
*,
296 static struct radix_node
*node_lookup_default(void);
297 static int rn_match_ifscope(struct radix_node
*, void *);
298 static struct ifaddr
*ifa_ifwithroute_common_locked(int,
299 const struct sockaddr
*, const struct sockaddr
*, unsigned int);
300 static struct rtentry
*rte_alloc(void);
301 static void rte_free(struct rtentry
*);
302 static void rtfree_common(struct rtentry
*, boolean_t
);
304 uint32_t route_generation
= 0;
307 * sockaddr_in with embedded interface scope; this is used internally
308 * to keep track of scoped route entries in the routing table. The
309 * fact that such a scope is embedded in the structure is an artifact
310 * of the current implementation which could change in future.
312 struct sockaddr_inifscope
{
314 sa_family_t sin_family
;
316 struct in_addr sin_addr
;
318 * To avoid possible conflict with an overlaid sockaddr_inarp
319 * having sin_other set to SIN_PROXY, we use the first 4-bytes
320 * of sin_zero since sin_srcaddr is one of the unused fields
329 #define sin_ifscope un._in_index.ifscope
332 #define SIN(sa) ((struct sockaddr_in *)(size_t)(sa))
333 #define SINIFSCOPE(sa) ((struct sockaddr_inifscope *)(size_t)(sa))
335 #define ASSERT_SINIFSCOPE(sa) { \
336 if ((sa)->sa_family != AF_INET || \
337 (sa)->sa_len < sizeof (struct sockaddr_in)) \
338 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
342 * Argument to leaf-matching routine; at present it is scoped routing
343 * specific but can be expanded in future to include other search filters.
345 struct matchleaf_arg
{
346 unsigned int ifscope
; /* interface scope */
350 * For looking up the non-scoped default route (sockaddr instead
351 * of sockaddr_in for convenience).
353 static struct sockaddr sin_def
= {
354 sizeof (struct sockaddr_in
), AF_INET
, { 0, }
358 * Interface index (scope) of the primary interface; determined at
359 * the time when the default, non-scoped route gets added, changed
360 * or deleted. Protected by rnh_lock.
362 static unsigned int primary_ifscope
= IFSCOPE_NONE
;
364 #define INET_DEFAULT(dst) \
365 ((dst)->sa_family == AF_INET && SIN(dst)->sin_addr.s_addr == 0)
367 #define RT(r) ((struct rtentry *)r)
368 #define RT_HOST(r) (RT(r)->rt_flags & RTF_HOST)
371 * Given a route, determine whether or not it is the non-scoped default
372 * route; dst typically comes from rt_key(rt) but may be coming from
373 * a separate place when rt is in the process of being created.
376 rt_inet_default(struct rtentry
*rt
, struct sockaddr
*dst
)
378 return (INET_DEFAULT(dst
) && !(rt
->rt_flags
& RTF_IFSCOPE
));
382 * Set the ifscope of the primary interface; caller holds rnh_lock.
385 set_primary_ifscope(unsigned int ifscope
)
387 primary_ifscope
= ifscope
;
391 * Return the ifscope of the primary interface; caller holds rnh_lock.
394 get_primary_ifscope(void)
396 return (primary_ifscope
);
400 * Embed ifscope into a given a sockaddr_in.
403 sa_set_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
405 /* Caller must pass in sockaddr_in */
406 ASSERT_SINIFSCOPE(sa
);
408 SINIFSCOPE(sa
)->sin_ifscope
= ifscope
;
412 * Given a sockaddr_in, return the embedded ifscope to the caller.
415 sa_get_ifscope(struct sockaddr
*sa
)
417 /* Caller must pass in sockaddr_in */
418 ASSERT_SINIFSCOPE(sa
);
420 return (SINIFSCOPE(sa
)->sin_ifscope
);
424 * Copy a sockaddr_in src to dst and embed ifscope into dst.
426 static struct sockaddr
*
427 sin_copy(struct sockaddr_in
*src
, struct sockaddr_in
*dst
, unsigned int ifscope
)
430 sa_set_ifscope(SA(dst
), ifscope
);
436 * Copy a mask from src to a sockaddr_in dst and embed ifscope into dst.
438 static struct sockaddr
*
439 mask_copy(struct sockaddr
*src
, struct sockaddr_in
*dst
, unsigned int ifscope
)
441 /* We know dst is at least the size of sockaddr{_in} */
442 bzero(dst
, sizeof (*dst
));
443 rt_maskedcopy(src
, SA(dst
), src
);
446 * The length of the mask sockaddr would need to be adjusted
447 * to cover the additional sin_ifscope field; when ifscope is
448 * IFSCOPE_NONE, we'd end up clearing the embedded ifscope on
449 * the destination mask in addition to extending the length
450 * of the sockaddr, as a side effect. This is okay, as any
451 * trailing zeroes would be skipped by rn_addmask prior to
452 * inserting or looking up the mask in the mask tree.
454 SINIFSCOPE(dst
)->sin_ifscope
= ifscope
;
455 SINIFSCOPE(dst
)->sin_len
=
456 offsetof(struct sockaddr_inifscope
, sin_ifscope
) +
457 sizeof (SINIFSCOPE(dst
)->sin_ifscope
);
463 * Trim trailing zeroes on a sockaddr and update its length.
465 static struct sockaddr
*
466 sa_trim(struct sockaddr
*sa
, int skip
)
468 caddr_t cp
, base
= (caddr_t
)sa
+ skip
;
470 if (sa
->sa_len
<= skip
)
473 for (cp
= base
+ (sa
->sa_len
- skip
); cp
> base
&& cp
[-1] == 0;)
476 sa
->sa_len
= (cp
- base
) + skip
;
477 if (sa
->sa_len
< skip
) {
478 /* Must not happen, and if so, panic */
479 panic("%s: broken logic (sa_len %d < skip %d )", __func__
,
482 } else if (sa
->sa_len
== skip
) {
483 /* If we end up with all zeroes, then there's no mask */
491 * Called by rtm_msg{1,2} routines to "scrub" the embedded interface scope
492 * away from the socket address structure, so that clients of the routing
493 * socket will not be confused by the presence of the embedded scope, or the
494 * side effect of the increased length due to that. The source sockaddr is
495 * not modified; instead, the scrubbing happens on the destination sockaddr
496 * storage that is passed in by the caller.
499 rtm_scrub_ifscope(int idx
, struct sockaddr
*hint
, struct sockaddr
*sa
,
500 struct sockaddr_storage
*ss
)
502 struct sockaddr
*ret
= sa
;
507 * If this is for an AF_INET destination address, call
508 * sin_copy() with IFSCOPE_NONE as it does what we need.
510 if (sa
->sa_family
== AF_INET
&&
511 SINIFSCOPE(sa
)->sin_ifscope
!= IFSCOPE_NONE
) {
512 bzero(ss
, sizeof (*ss
));
513 ret
= sin_copy(SIN(sa
), SIN(ss
), IFSCOPE_NONE
);
519 * If this is for a mask, we can't tell whether or not
520 * there is an embedded interface scope, as the span of
521 * bytes between sa_len and the beginning of the mask
522 * (offset of sin_addr in the case of AF_INET) may be
523 * filled with all-ones by rn_addmask(), and hence we
524 * cannot rely on sa_family. Because of this, we use
525 * the sa_family of the hint sockaddr (RTAX_{DST,IFA})
526 * as indicator as to whether or not the mask is to be
527 * treated as one for AF_INET. Clearing the embedded
528 * scope involves setting it to IFSCOPE_NONE followed
529 * by calling sa_trim() to trim trailing zeroes from
530 * the storage sockaddr, which reverses what was done
531 * earlier by mask_copy() on the source sockaddr.
533 int skip
= offsetof(struct sockaddr_in
, sin_addr
);
534 if (sa
->sa_len
> skip
&& sa
->sa_len
<= sizeof (*ss
) &&
535 hint
!= NULL
&& hint
->sa_family
== AF_INET
) {
536 bzero(ss
, sizeof (*ss
));
537 bcopy(sa
, ss
, sa
->sa_len
);
538 SINIFSCOPE(ss
)->sin_ifscope
= IFSCOPE_NONE
;
539 ret
= sa_trim(SA(ss
), skip
);
551 * Callback leaf-matching routine for rn_matchaddr_args used
552 * for looking up an exact match for a scoped route entry.
555 rn_match_ifscope(struct radix_node
*rn
, void *arg
)
557 struct rtentry
*rt
= (struct rtentry
*)rn
;
558 struct matchleaf_arg
*ma
= arg
;
560 if (!(rt
->rt_flags
& RTF_IFSCOPE
) || rt_key(rt
)->sa_family
!= AF_INET
)
563 return (SINIFSCOPE(rt_key(rt
))->sin_ifscope
== ma
->ifscope
);
567 rtable_init(void **table
)
570 for (dom
= domains
; dom
; dom
= dom
->dom_next
)
571 if (dom
->dom_rtattach
)
572 dom
->dom_rtattach(&table
[dom
->dom_family
],
581 PE_parse_boot_argn("rte_debug", &rte_debug
, sizeof (rte_debug
));
583 rte_debug
|= RTD_DEBUG
;
585 rnh_lock_grp_attr
= lck_grp_attr_alloc_init();
586 rnh_lock_grp
= lck_grp_alloc_init("route", rnh_lock_grp_attr
);
587 rnh_lock_attr
= lck_attr_alloc_init();
588 if ((rnh_lock
= lck_mtx_alloc_init(rnh_lock_grp
,
589 rnh_lock_attr
)) == NULL
) {
590 printf("route_init: can't alloc rnh_lock\n");
594 rte_mtx_grp_attr
= lck_grp_attr_alloc_init();
595 rte_mtx_grp
= lck_grp_alloc_init(RTE_NAME
, rte_mtx_grp_attr
);
596 rte_mtx_attr
= lck_attr_alloc_init();
598 lck_mtx_lock(rnh_lock
);
599 rn_init(); /* initialize all zeroes, all ones, mask table */
600 lck_mtx_unlock(rnh_lock
);
601 rtable_init((void **)rt_tables
);
602 route_domain_mtx
= routedomain
.dom_mtx
;
604 if (rte_debug
& RTD_DEBUG
)
605 size
= sizeof (struct rtentry_dbg
);
607 size
= sizeof (struct rtentry
);
609 rte_zone
= zinit(size
, RTE_ZONE_MAX
* size
, 0, RTE_ZONE_NAME
);
610 if (rte_zone
== NULL
)
611 panic("route_init: failed allocating rte_zone");
613 zone_change(rte_zone
, Z_EXPAND
, TRUE
);
615 TAILQ_INIT(&rttrash_head
);
619 * Atomically increment route generation counter
622 routegenid_update(void)
624 (void) atomic_add_32_ov(&route_generation
, 1);
628 * Packet routing routines.
631 rtalloc(struct route
*ro
)
637 rtalloc_ign_locked(struct route
*ro
, uint32_t ignore
)
639 return (rtalloc_ign_common_locked(ro
, ignore
, IFSCOPE_NONE
));
643 rtalloc_scoped_ign_locked(struct route
*ro
, uint32_t ignore
,
644 unsigned int ifscope
)
646 return (rtalloc_ign_common_locked(ro
, ignore
, ifscope
));
650 rtalloc_ign_common_locked(struct route
*ro
, uint32_t ignore
,
651 unsigned int ifscope
)
655 if ((rt
= ro
->ro_rt
) != NULL
) {
657 if (rt
->rt_ifp
!= NULL
&& (rt
->rt_flags
& RTF_UP
) &&
658 rt
->generation_id
== route_generation
) {
666 ro
->ro_rt
= rtalloc1_common_locked(&ro
->ro_dst
, 1, ignore
, ifscope
);
667 if (ro
->ro_rt
!= NULL
) {
668 ro
->ro_rt
->generation_id
= route_generation
;
669 RT_LOCK_ASSERT_NOTHELD(ro
->ro_rt
);
674 rtalloc_ign(struct route
*ro
, uint32_t ignore
)
676 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
677 lck_mtx_lock(rnh_lock
);
678 rtalloc_ign_locked(ro
, ignore
);
679 lck_mtx_unlock(rnh_lock
);
683 rtalloc_scoped_ign(struct route
*ro
, uint32_t ignore
, unsigned int ifscope
)
685 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
686 lck_mtx_lock(rnh_lock
);
687 rtalloc_scoped_ign_locked(ro
, ignore
, ifscope
);
688 lck_mtx_unlock(rnh_lock
);
692 rtalloc1_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
694 return (rtalloc1_common_locked(dst
, report
, ignflags
, IFSCOPE_NONE
));
698 rtalloc1_scoped_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
699 unsigned int ifscope
)
701 return (rtalloc1_common_locked(dst
, report
, ignflags
, ifscope
));
705 * Look up the route that matches the address given
706 * Or, at least try.. Create a cloned route if needed.
708 static struct rtentry
*
709 rtalloc1_common_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
710 unsigned int ifscope
)
712 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
713 struct rtentry
*rt
, *newrt
= NULL
;
714 struct rt_addrinfo info
;
716 int err
= 0, msgtype
= RTM_MISS
;
722 * Find the longest prefix or exact (in the scoped case) address match;
723 * callee adds a reference to entry and checks for root node as well
725 rt
= rt_lookup(FALSE
, dst
, NULL
, rnh
, ifscope
);
731 nflags
= rt
->rt_flags
& ~ignflags
;
733 if (report
&& (nflags
& (RTF_CLONING
| RTF_PRCLONING
))) {
735 * We are apparently adding (report = 0 in delete).
736 * If it requires that it be cloned, do so.
737 * (This implies it wasn't a HOST route.)
739 err
= rtrequest_locked(RTM_RESOLVE
, dst
, NULL
, NULL
, 0, &newrt
);
742 * If the cloning didn't succeed, maybe what we
743 * have from lookup above will do. Return that;
744 * no need to hold another reference since it's
752 * We cloned it; drop the original route found during lookup.
753 * The resulted cloned route (newrt) would now have an extra
754 * reference held during rtrequest.
757 if ((rt
= newrt
) && (rt
->rt_flags
& RTF_XRESOLVE
)) {
759 * If the new route specifies it be
760 * externally resolved, then go do that.
762 msgtype
= RTM_RESOLVE
;
770 * Either we hit the root or couldn't find any match,
771 * Which basically means "cant get there from here"
773 rtstat
.rts_unreach
++;
777 * If required, report the failure to the supervising
779 * For a delete, this is not an error. (report == 0)
781 bzero((caddr_t
)&info
, sizeof(info
));
782 info
.rti_info
[RTAX_DST
] = dst
;
783 rt_missmsg(msgtype
, &info
, 0, err
);
790 rtalloc1(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
792 struct rtentry
* entry
;
793 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
794 lck_mtx_lock(rnh_lock
);
795 entry
= rtalloc1_locked(dst
, report
, ignflags
);
796 lck_mtx_unlock(rnh_lock
);
801 rtalloc1_scoped(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
802 unsigned int ifscope
)
804 struct rtentry
* entry
;
805 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
806 lck_mtx_lock(rnh_lock
);
807 entry
= rtalloc1_scoped_locked(dst
, report
, ignflags
, ifscope
);
808 lck_mtx_unlock(rnh_lock
);
813 * Remove a reference count from an rtentry.
814 * If the count gets low enough, take it out of the routing table
817 rtfree_locked(struct rtentry
*rt
)
819 rtfree_common(rt
, TRUE
);
823 rtfree_common(struct rtentry
*rt
, boolean_t locked
)
825 struct radix_node_head
*rnh
;
828 * Atomically decrement the reference count and if it reaches 0,
829 * and there is a close function defined, call the close function.
832 if (rtunref(rt
) > 0) {
838 * To avoid violating lock ordering, we must drop rt_lock before
839 * trying to acquire the global rnh_lock. If we are called with
840 * rnh_lock held, then we already have exclusive access; otherwise
841 * we do the lock dance.
845 * Note that we check it again below after grabbing rnh_lock,
846 * since it is possible that another thread doing a lookup wins
847 * the race, grabs the rnh_lock first, and bumps up the reference
848 * count in which case the route should be left alone as it is
849 * still in use. It's also possible that another thread frees
850 * the route after we drop rt_lock; to prevent the route from
851 * being freed, we hold an extra reference.
853 RT_ADDREF_LOCKED(rt
);
855 lck_mtx_lock(rnh_lock
);
857 RT_REMREF_LOCKED(rt
);
858 if (rt
->rt_refcnt
> 0) {
859 /* We've lost the race, so abort */
866 * We may be blocked on other lock(s) as part of freeing
867 * the entry below, so convert from spin to full mutex.
871 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
873 /* Negative refcnt must never happen */
874 if (rt
->rt_refcnt
!= 0)
875 panic("rt %p invalid refcnt %d", rt
, rt
->rt_refcnt
);
878 * find the tree for that address family
879 * Note: in the case of igmp packets, there might not be an rnh
881 rnh
= rt_tables
[rt_key(rt
)->sa_family
];
884 * On last reference give the "close method" a chance to cleanup
885 * private state. This also permits (for IPv4 and IPv6) a chance
886 * to decide if the routing table entry should be purged immediately
887 * or at a later time. When an immediate purge is to happen the
888 * close routine typically issues RTM_DELETE which clears the RTF_UP
889 * flag on the entry so that the code below reclaims the storage.
891 if (rnh
!= NULL
&& rnh
->rnh_close
!= NULL
)
892 rnh
->rnh_close((struct radix_node
*)rt
, rnh
);
895 * If we are no longer "up" (and ref == 0) then we can free the
896 * resources associated with the route.
898 if (!(rt
->rt_flags
& RTF_UP
)) {
899 if (rt
->rt_nodes
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
))
900 panic("rt %p freed while in radix tree\n", rt
);
902 * the rtentry must have been removed from the routing table
903 * so it is represented in rttrash; remove that now.
905 (void) OSDecrementAtomic(&rttrash
);
906 if (rte_debug
& RTD_DEBUG
) {
907 TAILQ_REMOVE(&rttrash_head
, (struct rtentry_dbg
*)rt
,
912 * Route is no longer in the tree and refcnt is 0;
913 * we have exclusive access, so destroy it.
918 * release references on items we hold them on..
919 * e.g other routes and ifaddrs.
921 if (rt
->rt_parent
!= NULL
) {
922 rtfree_locked(rt
->rt_parent
);
923 rt
->rt_parent
= NULL
;
926 if (rt
->rt_ifa
!= NULL
) {
932 * Now free any attached link-layer info.
934 if (rt
->rt_llinfo
!= NULL
) {
935 if (rt
->rt_llinfo_free
!= NULL
)
936 (*rt
->rt_llinfo_free
)(rt
->rt_llinfo
);
938 R_Free(rt
->rt_llinfo
);
939 rt
->rt_llinfo
= NULL
;
943 * The key is separately alloc'd so free it (see rt_setgate()).
944 * This also frees the gateway, as they are always malloc'd
950 * and the rtentry itself of course
952 rte_lock_destroy(rt
);
956 * The "close method" has been called, but the route is
957 * still in the radix tree with zero refcnt, i.e. "up"
958 * and in the cached state.
964 lck_mtx_unlock(rnh_lock
);
968 rtfree(struct rtentry
*rt
)
970 rtfree_common(rt
, FALSE
);
974 * Decrements the refcount but does not free the route when
975 * the refcount reaches zero. Unless you have really good reason,
976 * use rtfree not rtunref.
979 rtunref(struct rtentry
*p
)
981 RT_LOCK_ASSERT_HELD(p
);
983 if (p
->rt_refcnt
== 0)
984 panic("%s(%p) bad refcnt\n", __func__
, p
);
988 if (rte_debug
& RTD_DEBUG
)
989 rtunref_audit((struct rtentry_dbg
*)p
);
991 /* Return new value */
992 return (p
->rt_refcnt
);
996 rtunref_audit(struct rtentry_dbg
*rte
)
1000 if (rte
->rtd_inuse
!= RTD_INUSE
)
1001 panic("rtunref: on freed rte=%p\n", rte
);
1003 idx
= atomic_add_16_ov(&rte
->rtd_refrele_cnt
, 1) % CTRACE_HIST_SIZE
;
1004 if (rte_debug
& RTD_TRACE
)
1005 ctrace_record(&rte
->rtd_refrele
[idx
]);
1009 * Add a reference count from an rtentry.
1012 rtref(struct rtentry
*p
)
1014 RT_LOCK_ASSERT_HELD(p
);
1016 if (++p
->rt_refcnt
== 0)
1017 panic("%s(%p) bad refcnt\n", __func__
, p
);
1019 if (rte_debug
& RTD_DEBUG
)
1020 rtref_audit((struct rtentry_dbg
*)p
);
1024 rtref_audit(struct rtentry_dbg
*rte
)
1028 if (rte
->rtd_inuse
!= RTD_INUSE
)
1029 panic("rtref_audit: on freed rte=%p\n", rte
);
1031 idx
= atomic_add_16_ov(&rte
->rtd_refhold_cnt
, 1) % CTRACE_HIST_SIZE
;
1032 if (rte_debug
& RTD_TRACE
)
1033 ctrace_record(&rte
->rtd_refhold
[idx
]);
1037 rtsetifa(struct rtentry
*rt
, struct ifaddr
* ifa
)
1039 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1041 RT_LOCK_ASSERT_HELD(rt
);
1043 if (rt
->rt_ifa
== ifa
)
1046 /* Release the old ifa */
1048 ifafree(rt
->rt_ifa
);
1053 /* Take a reference to the ifa */
1059 * Force a routing table entry to the specified
1060 * destination to go through the given gateway.
1061 * Normally called as a result of a routing redirect
1062 * message from the network layer.
1065 rtredirect(struct ifnet
*ifp
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1066 struct sockaddr
*netmask
, int flags
, struct sockaddr
*src
,
1067 struct rtentry
**rtp
)
1069 struct rtentry
*rt
= NULL
;
1072 struct rt_addrinfo info
;
1073 struct ifaddr
*ifa
= NULL
;
1074 unsigned int ifscope
= (ifp
!= NULL
) ? ifp
->if_index
: IFSCOPE_NONE
;
1075 struct sockaddr_in sin
;
1077 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1078 lck_mtx_lock(rnh_lock
);
1081 * Verify the gateway is directly reachable; if scoped routing
1082 * is enabled, verify that it is reachable from the interface
1083 * where the ICMP redirect arrived on.
1085 if ((ifa
= ifa_ifwithnet_scoped(gateway
, ifscope
)) == NULL
) {
1086 error
= ENETUNREACH
;
1090 /* Lookup route to the destination (from the original IP header) */
1091 rt
= rtalloc1_scoped_locked(dst
, 0, RTF_CLONING
|RTF_PRCLONING
, ifscope
);
1095 /* Embed scope in src for comparison against rt_gateway below */
1096 if (ip_doscopedroute
&& src
->sa_family
== AF_INET
)
1097 src
= sin_copy(SIN(src
), &sin
, ifscope
);
1100 * If the redirect isn't from our current router for this dst,
1101 * it's either old or wrong. If it redirects us to ourselves,
1102 * we have a routing loop, perhaps as a result of an interface
1103 * going down recently.
1105 if (!(flags
& RTF_DONE
) && rt
!= NULL
&&
1106 (!equal(src
, rt
->rt_gateway
) || !equal(rt
->rt_ifa
->ifa_addr
,
1111 if ((ifa
= ifa_ifwithaddr(gateway
))) {
1114 error
= EHOSTUNREACH
;
1130 * Create a new entry if we just got back a wildcard entry
1131 * or the the lookup failed. This is necessary for hosts
1132 * which use routing redirects generated by smart gateways
1133 * to dynamically build the routing tables.
1135 if ((rt
== NULL
) || (rt_mask(rt
) != NULL
&& rt_mask(rt
)->sa_len
< 2))
1138 * Don't listen to the redirect if it's
1139 * for a route to an interface.
1141 RT_LOCK_ASSERT_HELD(rt
);
1142 if (rt
->rt_flags
& RTF_GATEWAY
) {
1143 if (((rt
->rt_flags
& RTF_HOST
) == 0) && (flags
& RTF_HOST
)) {
1145 * Changing from route to net => route to host.
1146 * Create new route, rather than smashing route
1147 * to net; similar to cloned routes, the newly
1148 * created host route is scoped as well.
1153 flags
|= RTF_GATEWAY
| RTF_DYNAMIC
;
1154 error
= rtrequest_scoped_locked(RTM_ADD
, dst
,
1155 gateway
, netmask
, flags
, NULL
, ifscope
);
1156 stat
= &rtstat
.rts_dynamic
;
1159 * Smash the current notion of the gateway to
1160 * this destination. Should check about netmask!!!
1162 rt
->rt_flags
|= RTF_MODIFIED
;
1163 flags
|= RTF_MODIFIED
;
1164 stat
= &rtstat
.rts_newgateway
;
1166 * add the key and gateway (in one malloc'd chunk).
1168 error
= rt_setgate(rt
, rt_key(rt
), gateway
);
1173 error
= EHOSTUNREACH
;
1177 RT_LOCK_ASSERT_NOTHELD(rt
);
1185 rtstat
.rts_badredirect
++;
1190 routegenid_update();
1192 lck_mtx_unlock(rnh_lock
);
1193 bzero((caddr_t
)&info
, sizeof(info
));
1194 info
.rti_info
[RTAX_DST
] = dst
;
1195 info
.rti_info
[RTAX_GATEWAY
] = gateway
;
1196 info
.rti_info
[RTAX_NETMASK
] = netmask
;
1197 info
.rti_info
[RTAX_AUTHOR
] = src
;
1198 rt_missmsg(RTM_REDIRECT
, &info
, flags
, error
);
1202 * Routing table ioctl interface.
1205 rtioctl(unsigned long req
, caddr_t data
, struct proc
*p
)
1208 #if INET && MROUTING
1209 return mrt_ioctl(req
, data
);
1212 #pragma unused(data)
1220 const struct sockaddr
*dst
,
1221 const struct sockaddr
*gateway
)
1225 lck_mtx_lock(rnh_lock
);
1226 ifa
= ifa_ifwithroute_locked(flags
, dst
, gateway
);
1227 lck_mtx_unlock(rnh_lock
);
1233 ifa_ifwithroute_locked(int flags
, const struct sockaddr
*dst
,
1234 const struct sockaddr
*gateway
)
1236 return (ifa_ifwithroute_common_locked((flags
& ~RTF_IFSCOPE
), dst
,
1237 gateway
, IFSCOPE_NONE
));
1241 ifa_ifwithroute_scoped_locked(int flags
, const struct sockaddr
*dst
,
1242 const struct sockaddr
*gateway
, unsigned int ifscope
)
1244 if (ifscope
!= IFSCOPE_NONE
)
1245 flags
|= RTF_IFSCOPE
;
1247 flags
&= ~RTF_IFSCOPE
;
1249 return (ifa_ifwithroute_common_locked(flags
, dst
, gateway
, ifscope
));
1252 static struct ifaddr
*
1253 ifa_ifwithroute_common_locked(int flags
, const struct sockaddr
*dst
,
1254 const struct sockaddr
*gateway
, unsigned int ifscope
)
1256 struct ifaddr
*ifa
= NULL
;
1257 struct rtentry
*rt
= NULL
;
1258 struct sockaddr_in dst_in
, gw_in
;
1260 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1262 if (ip_doscopedroute
) {
1264 * Just in case the sockaddr passed in by the caller
1265 * contains embedded scope, make sure to clear it since
1266 * IPv4 interface addresses aren't scoped.
1268 if (dst
!= NULL
&& dst
->sa_family
== AF_INET
)
1269 dst
= sin_copy(SIN(dst
), &dst_in
, IFSCOPE_NONE
);
1270 if (gateway
!= NULL
&& gateway
->sa_family
== AF_INET
)
1271 gateway
= sin_copy(SIN(gateway
), &gw_in
, IFSCOPE_NONE
);
1274 if (!(flags
& RTF_GATEWAY
)) {
1276 * If we are adding a route to an interface,
1277 * and the interface is a pt to pt link
1278 * we should search for the destination
1279 * as our clue to the interface. Otherwise
1280 * we can use the local address.
1282 if (flags
& RTF_HOST
) {
1283 ifa
= ifa_ifwithdstaddr(dst
);
1286 ifa
= ifa_ifwithaddr_scoped(gateway
, ifscope
);
1289 * If we are adding a route to a remote net
1290 * or host, the gateway may still be on the
1291 * other end of a pt to pt link.
1293 ifa
= ifa_ifwithdstaddr(gateway
);
1296 ifa
= ifa_ifwithnet_scoped(gateway
, ifscope
);
1298 /* Workaround to avoid gcc warning regarding const variable */
1299 rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)dst
,
1306 RT_REMREF_LOCKED(rt
);
1311 if (ifa
!= NULL
&& ifa
->ifa_addr
->sa_family
!= dst
->sa_family
) {
1312 struct ifaddr
*newifa
;
1313 /* Callee adds reference to newifa upon success */
1314 newifa
= ifaof_ifpforaddr(dst
, ifa
->ifa_ifp
);
1315 if (newifa
!= NULL
) {
1321 * If we are adding a gateway, it is quite possible that the
1322 * routing table has a static entry in place for the gateway,
1323 * that may not agree with info garnered from the interfaces.
1324 * The routing table should carry more precedence than the
1325 * interfaces in this matter. Must be careful not to stomp
1326 * on new entries from rtinit, hence (ifa->ifa_addr != gateway).
1329 !equal(ifa
->ifa_addr
, (struct sockaddr
*)(size_t)gateway
)) &&
1330 (rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)gateway
,
1331 0, 0, ifscope
)) != NULL
) {
1338 RT_REMREF_LOCKED(rt
);
1342 * If an interface scope was specified, the interface index of
1343 * the found ifaddr must be equivalent to that of the scope;
1344 * otherwise there is no match.
1346 if ((flags
& RTF_IFSCOPE
) &&
1347 ifa
!= NULL
&& ifa
->ifa_ifp
->if_index
!= ifscope
) {
1355 static int rt_fixdelete(struct radix_node
*, void *);
1356 static int rt_fixchange(struct radix_node
*, void *);
1359 struct rtentry
*rt0
;
1360 struct radix_node_head
*rnh
;
1364 rtrequest_locked(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1365 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
)
1367 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1368 (flags
& ~RTF_IFSCOPE
), ret_nrt
, IFSCOPE_NONE
));
1372 rtrequest_scoped_locked(int req
, struct sockaddr
*dst
,
1373 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1374 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1376 if (ifscope
!= IFSCOPE_NONE
)
1377 flags
|= RTF_IFSCOPE
;
1379 flags
&= ~RTF_IFSCOPE
;
1381 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1382 flags
, ret_nrt
, ifscope
));
1386 * Do appropriate manipulations of a routing tree given all the bits of
1389 * Embedding the scope in the radix key is an internal job that should be
1390 * left to routines in this module. Callers should specify the scope value
1391 * to the "scoped" variants of route routines instead of manipulating the
1392 * key itself. This is typically done when creating a scoped route, e.g.
1393 * rtrequest(RTM_ADD). Once such a route is created and marked with the
1394 * RTF_IFSCOPE flag, callers can simply use its rt_key(rt) to clone it
1395 * (RTM_RESOLVE) or to remove it (RTM_DELETE). An exception to this is
1396 * during certain routing socket operations where the search key might be
1397 * derived from the routing message itself, in which case the caller must
1398 * specify the destination address and scope value for RTM_ADD/RTM_DELETE.
1401 rtrequest_common_locked(int req
, struct sockaddr
*dst0
,
1402 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1403 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1407 struct radix_node
*rn
;
1408 struct radix_node_head
*rnh
;
1409 struct ifaddr
*ifa
= NULL
;
1410 struct sockaddr
*ndst
, *dst
= dst0
;
1411 struct sockaddr_in sin
, mask
;
1412 #define senderr(x) { error = x ; goto bad; }
1414 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1416 * Find the correct routing tree to use for this Address Family
1418 if ((rnh
= rt_tables
[dst
->sa_family
]) == 0)
1421 * If we are adding a host route then we don't want to put
1422 * a netmask in the tree
1424 if (flags
& RTF_HOST
)
1428 * If RTF_IFSCOPE is specified, use a local copy of the destination
1429 * address to embed the scope into. This logic is repeated below
1430 * in the RTM_RESOLVE handler since the caller does not normally
1431 * specify such a flag during a resolve; instead it passes in the
1432 * route used for cloning for which the scope info is derived from.
1433 * Note also that in the case of RTM_DELETE, the address passed in
1434 * by the caller might already contain the embedded scope info when
1435 * it is the key itself, thus making RTF_IFSCOPE unnecessary; one
1436 * instance where it is explicitly set is inside route_output()
1437 * as part of handling a routing socket request.
1439 if (req
!= RTM_RESOLVE
&& (flags
& RTF_IFSCOPE
)) {
1440 /* Scoped routing is for AF_INET only */
1441 if (dst
->sa_family
!= AF_INET
||
1442 (req
== RTM_ADD
&& !ip_doscopedroute
))
1445 if (ifscope
== IFSCOPE_NONE
) {
1446 flags
&= ~RTF_IFSCOPE
;
1448 /* Embed ifscope into the key (local copy) */
1449 dst
= sin_copy(SIN(dst
), &sin
, ifscope
);
1451 /* Embed ifscope into netmask (local copy) */
1452 if (netmask
!= NULL
)
1453 netmask
= mask_copy(netmask
, &mask
, ifscope
);
1460 * Remove the item from the tree and return it.
1461 * Complain if it is not there and do no more processing.
1463 if ((rn
= rnh
->rnh_deladdr(dst
, netmask
, rnh
)) == 0)
1465 if (rn
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
))
1466 panic ("rtrequest delete");
1467 rt
= (struct rtentry
*)rn
;
1470 * Take an extra reference to handle the deletion of a route
1471 * entry whose reference count is already 0; e.g. an expiring
1472 * cloned route entry or an entry that was added to the table
1473 * with 0 reference. If the caller is interested in this route,
1474 * we will return it with the reference intact. Otherwise we
1475 * will decrement the reference via rtfree_locked() and then
1476 * possibly deallocate it.
1479 RT_ADDREF_LOCKED(rt
);
1480 rt
->rt_flags
&= ~RTF_UP
;
1483 * For consistency, in case the caller didn't set the flag.
1485 rt
->rt_flags
|= RTF_CONDEMNED
;
1488 * Now search what's left of the subtree for any cloned
1489 * routes which might have been formed from this node.
1491 if ((rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) &&
1494 rnh
->rnh_walktree_from(rnh
, dst
, rt_mask(rt
),
1500 * Remove any external references we may have.
1501 * This might result in another rtentry being freed if
1502 * we held its last reference.
1504 if (rt
->rt_gwroute
!= NULL
) {
1505 rtfree_locked(rt
->rt_gwroute
);
1506 rt
->rt_gwroute
= NULL
;
1510 * give the protocol a chance to keep things in sync.
1512 if ((ifa
= rt
->rt_ifa
) && ifa
->ifa_rtrequest
)
1513 ifa
->ifa_rtrequest(RTM_DELETE
, rt
, SA(0));
1517 * one more rtentry floating around that is not
1518 * linked to the routing table.
1520 (void) OSIncrementAtomic(&rttrash
);
1521 if (rte_debug
& RTD_DEBUG
) {
1522 TAILQ_INSERT_TAIL(&rttrash_head
,
1523 (struct rtentry_dbg
*)rt
, rtd_trash_link
);
1527 * If this is the (non-scoped) default route, clear
1528 * the interface index used for the primary ifscope.
1530 if (rt_inet_default(rt
, rt_key(rt
)))
1531 set_primary_ifscope(IFSCOPE_NONE
);
1536 * If the caller wants it, then it can have it,
1537 * but it's up to it to free the rtentry as we won't be
1540 if (ret_nrt
!= NULL
) {
1541 /* Return the route to caller with reference intact */
1544 /* Dereference or deallocate the route */
1550 if (ret_nrt
== 0 || (rt
= *ret_nrt
) == 0)
1553 * If cloning, we have the parent route given by the caller
1554 * and will use its rt_gateway, rt_rmx as part of the cloning
1555 * process below. Since rnh_lock is held at this point, the
1556 * parent's rt_ifa and rt_gateway will not change, and its
1557 * relevant rt_flags will not change as well. The only thing
1558 * that could change are the metrics, and thus we hold the
1559 * parent route's rt_lock later on during the actual copying
1564 flags
= rt
->rt_flags
&
1565 ~(RTF_CLONING
| RTF_PRCLONING
| RTF_STATIC
);
1566 flags
|= RTF_WASCLONED
;
1567 gateway
= rt
->rt_gateway
;
1568 if ((netmask
= rt
->rt_genmask
) == 0)
1571 if (!ip_doscopedroute
|| dst
->sa_family
!= AF_INET
)
1574 * When scoped routing is enabled, cloned entries are
1575 * always scoped according to the interface portion of
1576 * the parent route. The exception to this are IPv4
1577 * link local addresses.
1579 if (!IN_LINKLOCAL(ntohl(SIN(dst
)->sin_addr
.s_addr
))) {
1580 if (flags
& RTF_IFSCOPE
) {
1581 ifscope
= sa_get_ifscope(rt_key(rt
));
1583 ifscope
= rt
->rt_ifp
->if_index
;
1584 flags
|= RTF_IFSCOPE
;
1587 ifscope
= IFSCOPE_NONE
;
1588 flags
&= ~RTF_IFSCOPE
;
1591 /* Embed or clear ifscope into/from the key (local copy) */
1592 dst
= sin_copy(SIN(dst
), &sin
, ifscope
);
1594 /* Embed or clear ifscope into/from netmask (local copy) */
1595 if (netmask
!= NULL
)
1596 netmask
= mask_copy(netmask
, &mask
, ifscope
);
1601 if ((flags
& RTF_GATEWAY
) && !gateway
)
1602 panic("rtrequest: RTF_GATEWAY but no gateway");
1604 if (flags
& RTF_IFSCOPE
) {
1605 ifa
= ifa_ifwithroute_scoped_locked(flags
, dst0
,
1608 ifa
= ifa_ifwithroute_locked(flags
, dst0
, gateway
);
1611 senderr(ENETUNREACH
);
1613 if ((rt
= rte_alloc()) == NULL
)
1615 Bzero(rt
, sizeof(*rt
));
1618 rt
->rt_flags
= RTF_UP
| flags
;
1621 * Add the gateway. Possibly re-malloc-ing the storage for it
1622 * also add the rt_gwroute if possible.
1624 if ((error
= rt_setgate(rt
, dst
, gateway
)) != 0) {
1626 rte_lock_destroy(rt
);
1632 * point to the (possibly newly malloc'd) dest address.
1637 * make sure it contains the value we want (masked if needed).
1640 rt_maskedcopy(dst
, ndst
, netmask
);
1642 Bcopy(dst
, ndst
, dst
->sa_len
);
1645 * Note that we now have a reference to the ifa.
1646 * This moved from below so that rnh->rnh_addaddr() can
1647 * examine the ifa and ifa->ifa_ifp if it so desires.
1650 rt
->rt_ifp
= rt
->rt_ifa
->ifa_ifp
;
1652 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1654 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
, (caddr_t
)netmask
,
1657 struct rtentry
*rt2
;
1659 * Uh-oh, we already have one of these in the tree.
1660 * We do a special hack: if the route that's already
1661 * there was generated by the protocol-cloning
1662 * mechanism, then we just blow it away and retry
1663 * the insertion of the new one.
1665 if (flags
& RTF_IFSCOPE
) {
1666 rt2
= rtalloc1_scoped_locked(dst0
, 0,
1667 RTF_CLONING
| RTF_PRCLONING
, ifscope
);
1669 rt2
= rtalloc1_locked(dst
, 0,
1670 RTF_CLONING
| RTF_PRCLONING
);
1672 if (rt2
&& rt2
->rt_parent
) {
1674 * rnh_lock is held here, so rt_key and
1675 * rt_gateway of rt2 will not change.
1677 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt2
),
1678 rt2
->rt_gateway
, rt_mask(rt2
),
1681 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
,
1685 /* undo the extra ref we got */
1691 * If it still failed to go into the tree,
1692 * then un-make it (this should be a function)
1695 if (rt
->rt_gwroute
) {
1696 rtfree_locked(rt
->rt_gwroute
);
1697 rt
->rt_gwroute
= NULL
;
1700 ifafree(rt
->rt_ifa
);
1705 rte_lock_destroy(rt
);
1713 * If we got here from RESOLVE, then we are cloning so clone
1714 * the rest, and note that we are a clone (and increment the
1715 * parent's references). rnh_lock is still held, which prevents
1716 * a lookup from returning the newly-created route. Hence
1717 * holding and releasing the parent's rt_lock while still
1718 * holding the route's rt_lock is safe since the new route
1719 * is not yet externally visible.
1721 if (req
== RTM_RESOLVE
) {
1722 RT_LOCK_SPIN(*ret_nrt
);
1723 rt
->rt_rmx
= (*ret_nrt
)->rt_rmx
; /* copy metrics */
1724 if ((*ret_nrt
)->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) {
1725 rt
->rt_parent
= (*ret_nrt
);
1726 RT_ADDREF_LOCKED(*ret_nrt
);
1728 RT_UNLOCK(*ret_nrt
);
1732 * if this protocol has something to add to this then
1733 * allow it to do that as well.
1735 if (ifa
->ifa_rtrequest
)
1736 ifa
->ifa_rtrequest(req
, rt
, SA(ret_nrt
? *ret_nrt
: 0));
1741 * If this is the (non-scoped) default route, record
1742 * the interface index used for the primary ifscope.
1744 if (rt_inet_default(rt
, rt_key(rt
)))
1745 set_primary_ifscope(rt
->rt_ifp
->if_index
);
1748 * actually return a resultant rtentry and
1749 * give the caller a single reference.
1753 RT_ADDREF_LOCKED(rt
);
1757 * We repeat the same procedure from rt_setgate() here because
1758 * it doesn't fire when we call it there because the node
1759 * hasn't been added to the tree yet.
1761 if (req
== RTM_ADD
&&
1762 !(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != 0) {
1763 struct rtfc_arg arg
;
1767 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
1768 rt_fixchange
, &arg
);
1783 struct sockaddr
*dst
,
1784 struct sockaddr
*gateway
,
1785 struct sockaddr
*netmask
,
1787 struct rtentry
**ret_nrt
)
1790 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1791 lck_mtx_lock(rnh_lock
);
1792 error
= rtrequest_locked(req
, dst
, gateway
, netmask
, flags
, ret_nrt
);
1793 lck_mtx_unlock(rnh_lock
);
1797 * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
1798 * (i.e., the routes related to it by the operation of cloning). This
1799 * routine is iterated over all potential former-child-routes by way of
1800 * rnh->rnh_walktree_from() above, and those that actually are children of
1801 * the late parent (passed in as VP here) are themselves deleted.
1804 rt_fixdelete(struct radix_node
*rn
, void *vp
)
1806 struct rtentry
*rt
= (struct rtentry
*)rn
;
1807 struct rtentry
*rt0
= vp
;
1809 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1812 if (rt
->rt_parent
== rt0
&&
1813 !(rt
->rt_flags
& (RTF_PINNED
| RTF_CLONING
| RTF_PRCLONING
))) {
1815 * Safe to drop rt_lock and use rt_key, since holding
1816 * rnh_lock here prevents another thread from calling
1817 * rt_setgate() on this route.
1820 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
1821 rt_mask(rt
), rt
->rt_flags
, NULL
));
1828 * This routine is called from rt_setgate() to do the analogous thing for
1829 * adds and changes. There is the added complication in this case of a
1830 * middle insert; i.e., insertion of a new network route between an older
1831 * network route and (cloned) host routes. For this reason, a simple check
1832 * of rt->rt_parent is insufficient; each candidate route must be tested
1833 * against the (mask, value) of the new route (passed as before in vp)
1834 * to see if the new route matches it.
1836 * XXX - it may be possible to do fixdelete() for changes and reserve this
1837 * routine just for adds. I'm not sure why I thought it was necessary to do
1841 rt_fixchange(struct radix_node
*rn
, void *vp
)
1843 struct rtentry
*rt
= (struct rtentry
*)rn
;
1844 struct rtfc_arg
*ap
= vp
;
1845 struct rtentry
*rt0
= ap
->rt0
;
1846 struct radix_node_head
*rnh
= ap
->rnh
;
1847 u_char
*xk1
, *xm1
, *xk2
, *xmp
;
1850 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1854 if (!rt
->rt_parent
||
1855 (rt
->rt_flags
& (RTF_PINNED
| RTF_CLONING
| RTF_PRCLONING
))) {
1860 if (rt
->rt_parent
== rt0
)
1864 * There probably is a function somewhere which does this...
1865 * if not, there should be.
1867 len
= imin(rt_key(rt0
)->sa_len
, rt_key(rt
)->sa_len
);
1869 xk1
= (u_char
*)rt_key(rt0
);
1870 xm1
= (u_char
*)rt_mask(rt0
);
1871 xk2
= (u_char
*)rt_key(rt
);
1874 * Avoid applying a less specific route; do this only if the parent
1875 * route (rt->rt_parent) is a network route, since otherwise its mask
1876 * will be NULL if it is a cloning host route.
1878 if ((xmp
= (u_char
*)rt_mask(rt
->rt_parent
)) != NULL
) {
1879 int mlen
= rt_mask(rt
->rt_parent
)->sa_len
;
1880 if (mlen
> rt_mask(rt0
)->sa_len
) {
1885 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< mlen
; i
++) {
1886 if ((xmp
[i
] & ~(xmp
[i
] ^ xm1
[i
])) != xmp
[i
]) {
1893 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< len
; i
++) {
1894 if ((xk2
[i
] & xm1
[i
]) != xk1
[i
]) {
1901 * OK, this node is a clone, and matches the node currently being
1902 * changed/added under the node's mask. So, get rid of it.
1906 * Safe to drop rt_lock and use rt_key, since holding rnh_lock here
1907 * prevents another thread from calling rt_setgate() on this route.
1910 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
1911 rt_mask(rt
), rt
->rt_flags
, NULL
));
1915 * Round up sockaddr len to multiples of 32-bytes. This will reduce
1916 * or even eliminate the need to re-allocate the chunk of memory used
1917 * for rt_key and rt_gateway in the event the gateway portion changes.
1918 * Certain code paths (e.g. IPSec) are notorious for caching the address
1919 * of rt_gateway; this rounding-up would help ensure that the gateway
1920 * portion never gets deallocated (though it may change contents) and
1921 * thus greatly simplifies things.
1923 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
1926 * Sets the gateway and/or gateway route portion of a route; may be
1927 * called on an existing route to modify the gateway portion. Both
1928 * rt_key and rt_gateway are allocated out of the same memory chunk.
1929 * Route entry lock must be held by caller; this routine will return
1930 * with the lock held.
1933 rt_setgate(struct rtentry
*rt
, struct sockaddr
*dst
, struct sockaddr
*gate
)
1935 int dlen
= SA_SIZE(dst
->sa_len
), glen
= SA_SIZE(gate
->sa_len
);
1936 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
1938 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1939 RT_LOCK_ASSERT_HELD(rt
);
1942 * If this is for a route that is on its way of being removed,
1943 * or is temporarily frozen, reject the modification request.
1945 if (rt
->rt_flags
& RTF_CONDEMNED
)
1948 /* Add an extra ref for ourselves */
1949 RT_ADDREF_LOCKED(rt
);
1952 * A host route with the destination equal to the gateway
1953 * will interfere with keeping LLINFO in the routing
1954 * table, so disallow it.
1956 if (((rt
->rt_flags
& (RTF_HOST
|RTF_GATEWAY
|RTF_LLINFO
)) ==
1957 (RTF_HOST
|RTF_GATEWAY
)) && (dst
->sa_len
== gate
->sa_len
) &&
1958 (bcmp(dst
, gate
, dst
->sa_len
) == 0)) {
1960 * The route might already exist if this is an RTM_CHANGE
1961 * or a routing redirect, so try to delete it.
1963 if (rt_key(rt
) != NULL
) {
1965 * Safe to drop rt_lock and use rt_key, rt_gateway,
1966 * since holding rnh_lock here prevents another thread
1967 * from calling rt_setgate() on this route.
1970 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt
),
1971 rt
->rt_gateway
, rt_mask(rt
), rt
->rt_flags
, NULL
);
1974 /* Release extra ref */
1975 RT_REMREF_LOCKED(rt
);
1976 return (EADDRNOTAVAIL
);
1980 * The destination is not directly reachable. Get a route
1981 * to the next-hop gateway and store it in rt_gwroute.
1983 if (rt
->rt_flags
& RTF_GATEWAY
) {
1984 struct rtentry
*gwrt
;
1985 unsigned int ifscope
;
1987 ifscope
= (dst
->sa_family
== AF_INET
) ?
1988 sa_get_ifscope(dst
) : IFSCOPE_NONE
;
1991 gwrt
= rtalloc1_scoped_locked(gate
, 1, RTF_PRCLONING
, ifscope
);
1993 RT_LOCK_ASSERT_NOTHELD(gwrt
);
1997 * Cloning loop avoidance:
1999 * In the presence of protocol-cloning and bad configuration,
2000 * it is possible to get stuck in bottomless mutual recursion
2001 * (rtrequest rt_setgate rtalloc1). We avoid this by not
2002 * allowing protocol-cloning to operate for gateways (which
2003 * is probably the correct choice anyway), and avoid the
2004 * resulting reference loops by disallowing any route to run
2005 * through itself as a gateway. This is obviously mandatory
2006 * when we get rt->rt_output(). It implies that a route to
2007 * the gateway must already be present in the system in order
2008 * for the gateway to be referred to by another route.
2011 RT_REMREF_LOCKED(gwrt
);
2012 /* Release extra ref */
2013 RT_REMREF_LOCKED(rt
);
2014 return (EADDRINUSE
); /* failure */
2018 * If scoped, the gateway route must use the same interface;
2019 * we're holding rnh_lock now, so rt_gateway and rt_ifp of gwrt
2020 * should not change and are freely accessible.
2022 if (ifscope
!= IFSCOPE_NONE
&& (rt
->rt_flags
& RTF_IFSCOPE
) &&
2023 gwrt
!= NULL
&& gwrt
->rt_ifp
!= NULL
&&
2024 gwrt
->rt_ifp
->if_index
!= ifscope
) {
2025 rtfree_locked(gwrt
); /* rt != gwrt, no deadlock */
2026 /* Release extra ref */
2027 RT_REMREF_LOCKED(rt
);
2028 return ((rt
->rt_flags
& RTF_HOST
) ?
2029 EHOSTUNREACH
: ENETUNREACH
);
2032 /* Check again since we dropped the lock above */
2033 if (rt
->rt_flags
& RTF_CONDEMNED
) {
2035 rtfree_locked(gwrt
);
2036 /* Release extra ref */
2037 RT_REMREF_LOCKED(rt
);
2041 if (rt
->rt_gwroute
!= NULL
)
2042 rtfree_locked(rt
->rt_gwroute
);
2043 rt
->rt_gwroute
= gwrt
;
2046 * In case the (non-scoped) default route gets modified via
2047 * an ICMP redirect, record the interface index used for the
2048 * primary ifscope. Also done in rt_setif() to take care
2049 * of the non-redirect cases.
2051 if (rt_inet_default(rt
, dst
) && rt
->rt_ifp
!= NULL
)
2052 set_primary_ifscope(rt
->rt_ifp
->if_index
);
2055 * Tell the kernel debugger about the new default gateway
2056 * if the gateway route uses the primary interface, or
2057 * if we are in a transient state before the non-scoped
2058 * default gateway is installed (similar to how the system
2059 * was behaving in the past). In future, it would be good
2060 * to do all this only when KDP is enabled.
2062 if ((dst
->sa_family
== AF_INET
) &&
2063 gwrt
!= NULL
&& gwrt
->rt_gateway
->sa_family
== AF_LINK
&&
2064 (gwrt
->rt_ifp
->if_index
== get_primary_ifscope() ||
2065 get_primary_ifscope() == IFSCOPE_NONE
))
2066 kdp_set_gateway_mac(SDL(gwrt
->rt_gateway
)->sdl_data
);
2070 * Prepare to store the gateway in rt_gateway. Both dst and gateway
2071 * are stored one after the other in the same malloc'd chunk. If we
2072 * have room, reuse the old buffer since rt_gateway already points
2073 * to the right place. Otherwise, malloc a new block and update
2074 * the 'dst' address and point rt_gateway to the right place.
2076 if (rt
->rt_gateway
== NULL
|| glen
> SA_SIZE(rt
->rt_gateway
->sa_len
)) {
2079 /* The underlying allocation is done with M_WAITOK set */
2080 R_Malloc(new, caddr_t
, dlen
+ glen
);
2082 if (rt
->rt_gwroute
!= NULL
)
2083 rtfree_locked(rt
->rt_gwroute
);
2084 rt
->rt_gwroute
= NULL
;
2085 /* Release extra ref */
2086 RT_REMREF_LOCKED(rt
);
2091 * Copy from 'dst' and not rt_key(rt) because we can get
2092 * here to initialize a newly allocated route entry, in
2093 * which case rt_key(rt) is NULL (and so does rt_gateway).
2095 bzero(new, dlen
+ glen
);
2096 Bcopy(dst
, new, dst
->sa_len
);
2097 R_Free(rt_key(rt
)); /* free old block; NULL is okay */
2098 rt
->rt_nodes
->rn_key
= new;
2099 rt
->rt_gateway
= (struct sockaddr
*)(new + dlen
);
2103 * Copy the new gateway value into the memory chunk.
2105 Bcopy(gate
, rt
->rt_gateway
, gate
->sa_len
);
2108 * For consistency between rt_gateway and rt_key(gwrt).
2110 if ((rt
->rt_flags
& RTF_GATEWAY
) && rt
->rt_gwroute
!= NULL
&&
2111 (rt
->rt_gwroute
->rt_flags
& RTF_IFSCOPE
) &&
2112 rt
->rt_gateway
->sa_family
== AF_INET
&&
2113 rt_key(rt
->rt_gwroute
)->sa_family
== AF_INET
) {
2114 sa_set_ifscope(rt
->rt_gateway
,
2115 sa_get_ifscope(rt_key(rt
->rt_gwroute
)));
2119 * This isn't going to do anything useful for host routes, so
2120 * don't bother. Also make sure we have a reasonable mask
2121 * (we don't yet have one during adds).
2123 if (!(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != 0) {
2124 struct rtfc_arg arg
;
2128 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
2129 rt_fixchange
, &arg
);
2133 /* Release extra ref */
2134 RT_REMREF_LOCKED(rt
);
2141 rt_maskedcopy(struct sockaddr
*src
, struct sockaddr
*dst
,
2142 struct sockaddr
*netmask
)
2144 u_char
*cp1
= (u_char
*)src
;
2145 u_char
*cp2
= (u_char
*)dst
;
2146 u_char
*cp3
= (u_char
*)netmask
;
2147 u_char
*cplim
= cp2
+ *cp3
;
2148 u_char
*cplim2
= cp2
+ *cp1
;
2150 *cp2
++ = *cp1
++; *cp2
++ = *cp1
++; /* copies sa_len & sa_family */
2155 *cp2
++ = *cp1
++ & *cp3
++;
2157 bzero((caddr_t
)cp2
, (unsigned)(cplim2
- cp2
));
2161 * Lookup an AF_INET scoped or non-scoped route depending on the ifscope
2162 * value passed in by the caller (IFSCOPE_NONE implies non-scoped).
2164 static struct radix_node
*
2165 node_lookup(struct sockaddr
*dst
, struct sockaddr
*netmask
,
2166 unsigned int ifscope
)
2168 struct radix_node_head
*rnh
= rt_tables
[AF_INET
];
2169 struct radix_node
*rn
;
2170 struct sockaddr_in sin
, mask
;
2171 struct matchleaf_arg ma
= { ifscope
};
2172 rn_matchf_t
*f
= rn_match_ifscope
;
2175 if (dst
->sa_family
!= AF_INET
)
2179 * Embed ifscope into the search key; for a non-scoped
2180 * search this will clear out any embedded scope value.
2182 dst
= sin_copy(SIN(dst
), &sin
, ifscope
);
2184 /* Embed (or clear) ifscope into netmask */
2185 if (netmask
!= NULL
)
2186 netmask
= mask_copy(netmask
, &mask
, ifscope
);
2188 if (ifscope
== IFSCOPE_NONE
)
2191 rn
= rnh
->rnh_lookup_args(dst
, netmask
, rnh
, f
, w
);
2192 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2199 * Lookup the AF_INET non-scoped default route.
2201 static struct radix_node
*
2202 node_lookup_default(void)
2204 struct radix_node_head
*rnh
= rt_tables
[AF_INET
];
2205 return (rnh
->rnh_lookup(&sin_def
, NULL
, rnh
));
2209 * Common routine to lookup/match a route. It invokes the lookup/matchaddr
2210 * callback which could be address family-specific. The main difference
2211 * between the two (at least for AF_INET/AF_INET6) is that a lookup does
2212 * not alter the expiring state of a route, whereas a match would unexpire
2213 * or revalidate the route.
2215 * The optional scope or interface index property of a route allows for a
2216 * per-interface route instance. This permits multiple route entries having
2217 * the same destination (but not necessarily the same gateway) to exist in
2218 * the routing table; each of these entries is specific to the corresponding
2219 * interface. This is made possible by embedding the scope value into the
2220 * radix key, thus making each route entry unique. These scoped entries
2221 * exist along with the regular, non-scoped entries in the same radix tree
2222 * for a given address family (currently AF_INET only); the scope logically
2223 * partitions it into multiple per-interface sub-trees.
2225 * When a scoped route lookup is performed, the routing table is searched for
2226 * the best match that would result in a route using the same interface as the
2227 * one associated with the scope (the exception to this are routes that point
2228 * to the loopback interface). The search rule follows the longest matching
2229 * prefix with the additional interface constraint.
2232 rt_lookup(boolean_t lookup_only
, struct sockaddr
*dst
, struct sockaddr
*netmask
,
2233 struct radix_node_head
*rnh
, unsigned int ifscope
)
2235 struct radix_node
*rn0
, *rn
;
2236 boolean_t dontcare
= (ifscope
== IFSCOPE_NONE
);
2238 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2244 * Non-scoped route lookup.
2246 if (!ip_doscopedroute
|| dst
->sa_family
!= AF_INET
) {
2248 rn
= rnh
->rnh_lookup(dst
, netmask
, rnh
);
2250 rn
= rnh
->rnh_matchaddr(dst
, rnh
);
2253 * Don't return a root node; also, rnh_matchaddr callback
2254 * would have done the necessary work to clear RTPRF_OURS
2255 * for certain protocol families.
2257 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2260 RT_LOCK_SPIN(RT(rn
));
2261 if (!(RT(rn
)->rt_flags
& RTF_CONDEMNED
)) {
2262 RT_ADDREF_LOCKED(RT(rn
));
2273 * Scoped route lookup:
2275 * We first perform a non-scoped lookup for the original result.
2276 * Afterwards, depending on whether or not the caller has specified
2277 * a scope, we perform a more specific scoped search and fallback
2278 * to this original result upon failure.
2280 rn0
= rn
= node_lookup(dst
, netmask
, IFSCOPE_NONE
);
2283 * If the caller did not specify a scope, use the primary scope
2284 * derived from the system's non-scoped default route. If, for
2285 * any reason, there is no primary interface, return what we have.
2287 if (dontcare
&& (ifscope
= get_primary_ifscope()) == IFSCOPE_NONE
)
2291 * Keep the original result if either of the following is true:
2293 * 1) The interface portion of the route has the same interface
2294 * index as the scope value and it is marked with RTF_IFSCOPE.
2295 * 2) The route uses the loopback interface, in which case the
2296 * destination (host/net) is local/loopback.
2298 * Otherwise, do a more specified search using the scope;
2299 * we're holding rnh_lock now, so rt_ifp should not change.
2302 struct rtentry
*rt
= RT(rn
);
2303 if (rt
->rt_ifp
!= lo_ifp
) {
2304 if (rt
->rt_ifp
->if_index
!= ifscope
) {
2306 * Wrong interface; keep the original result
2307 * only if the caller did not specify a scope,
2308 * and do a more specific scoped search using
2309 * the scope of the found route. Otherwise,
2310 * start again from scratch.
2314 ifscope
= rt
->rt_ifp
->if_index
;
2317 } else if (!(rt
->rt_flags
& RTF_IFSCOPE
)) {
2319 * Right interface, except that this route
2320 * isn't marked with RTF_IFSCOPE. Do a more
2321 * specific scoped search. Keep the original
2322 * result and return it it in case the scoped
2331 * Scoped search. Find the most specific entry having the same
2332 * interface scope as the one requested. The following will result
2333 * in searching for the longest prefix scoped match.
2336 rn
= node_lookup(dst
, netmask
, ifscope
);
2339 * Use the original result if either of the following is true:
2341 * 1) The scoped search did not yield any result.
2342 * 2) The result from the scoped search is a scoped default route,
2343 * and the original (non-scoped) result is not a default route,
2344 * i.e. the original result is a more specific host/net route.
2345 * 3) The scoped search yielded a net route but the original
2346 * result is a host route, i.e. the original result is treated
2347 * as a more specific route.
2349 if (rn
== NULL
|| (rn0
!= NULL
&&
2350 ((INET_DEFAULT(rt_key(RT(rn
))) && !INET_DEFAULT(rt_key(RT(rn0
)))) ||
2351 (!RT_HOST(rn
) && RT_HOST(rn0
)))))
2355 * If we still don't have a route, use the non-scoped default
2356 * route as long as the interface portion satistifes the scope.
2358 if (rn
== NULL
&& (rn
= node_lookup_default()) != NULL
&&
2359 RT(rn
)->rt_ifp
->if_index
!= ifscope
)
2365 * Manually clear RTPRF_OURS using in_validate() and
2366 * bump up the reference count after, and not before;
2367 * we only get here for AF_INET. node_lookup() has
2368 * done the check against RNF_ROOT, so we can be sure
2369 * that we're not returning a root node here.
2371 RT_LOCK_SPIN(RT(rn
));
2372 if (!(RT(rn
)->rt_flags
& RTF_CONDEMNED
)) {
2374 (void) in_validate(rn
);
2375 RT_ADDREF_LOCKED(RT(rn
));
2387 * Set up a routing table entry, normally
2391 rtinit(struct ifaddr
*ifa
, int cmd
, int flags
)
2394 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2395 lck_mtx_lock(rnh_lock
);
2396 error
= rtinit_locked(ifa
, cmd
, flags
);
2397 lck_mtx_unlock(rnh_lock
);
2402 rtinit_locked(struct ifaddr
*ifa
, int cmd
, int flags
)
2405 struct sockaddr
*dst
;
2406 struct sockaddr
*deldst
;
2408 struct rtentry
*nrt
= 0;
2411 dst
= flags
& RTF_HOST
? ifa
->ifa_dstaddr
: ifa
->ifa_addr
;
2413 * If it's a delete, check that if it exists, it's on the correct
2414 * interface or we might scrub a route to another ifa which would
2415 * be confusing at best and possibly worse.
2417 if (cmd
== RTM_DELETE
) {
2419 * It's a delete, so it should already exist..
2420 * If it's a net, mask off the host bits
2421 * (Assuming we have a mask)
2423 if ((flags
& RTF_HOST
) == 0 && ifa
->ifa_netmask
) {
2424 m
= m_get(M_DONTWAIT
, MT_SONAME
);
2428 deldst
= mtod(m
, struct sockaddr
*);
2429 rt_maskedcopy(dst
, deldst
, ifa
->ifa_netmask
);
2433 * Get an rtentry that is in the routing tree and
2434 * contains the correct info. (if this fails, can't get there).
2435 * We set "report" to FALSE so that if it doesn't exist,
2436 * it doesn't report an error or clone a route, etc. etc.
2438 rt
= rtalloc1_locked(dst
, 0, 0);
2441 * Ok so we found the rtentry. it has an extra reference
2442 * for us at this stage. we won't need that so
2446 if (rt
->rt_ifa
!= ifa
) {
2447 RT_REMREF_LOCKED(rt
);
2450 * If the interface in the rtentry doesn't match
2451 * the interface we are using, then we don't
2452 * want to delete it, so return an error.
2453 * This seems to be the only point of
2454 * this whole RTM_DELETE clause.
2458 return (flags
& RTF_HOST
? EHOSTUNREACH
2461 RT_REMREF_LOCKED(rt
);
2469 * One would think that as we are deleting, and we know
2470 * it doesn't exist, we could just return at this point
2471 * with an "ELSE" clause, but apparently not..
2473 lck_mtx_unlock(rnh_lock
);
2474 return (flags
& RTF_HOST
? EHOSTUNREACH
2480 * Do the actual request
2482 error
= rtrequest_locked(cmd
, dst
, ifa
->ifa_addr
, ifa
->ifa_netmask
,
2483 flags
| ifa
->ifa_flags
, &nrt
);
2487 * If we are deleting, and we found an entry, then
2488 * it's been removed from the tree.. now throw it away.
2490 if (cmd
== RTM_DELETE
&& error
== 0 && (rt
= nrt
)) {
2492 * notify any listening routing agents of the change
2495 rt_newaddrmsg(cmd
, ifa
, error
, nrt
);
2497 routegenid_update();
2503 * We are adding, and we have a returned routing entry.
2504 * We need to sanity check the result.
2506 if (cmd
== RTM_ADD
&& error
== 0 && (rt
= nrt
)) {
2509 * If it came back with an unexpected interface, then it must
2510 * have already existed or something. (XXX)
2512 if (rt
->rt_ifa
!= ifa
) {
2513 if (!(rt
->rt_ifa
->ifa_ifp
->if_flags
&
2514 (IFF_POINTOPOINT
|IFF_LOOPBACK
)))
2515 printf("rtinit: wrong ifa (%p) was (%p)\n",
2518 * Ask that the protocol in question
2519 * remove anything it has associated with
2520 * this route and ifaddr.
2522 if (rt
->rt_ifa
->ifa_rtrequest
)
2523 rt
->rt_ifa
->ifa_rtrequest(RTM_DELETE
, rt
, SA(0));
2525 * Set the route's ifa.
2529 * And substitute in references to the ifaddr
2532 rt
->rt_ifp
= ifa
->ifa_ifp
;
2533 rt
->rt_rmx
.rmx_mtu
= ifa
->ifa_ifp
->if_mtu
; /*XXX*/
2535 * Now ask the protocol to check if it needs
2536 * any special processing in its new form.
2538 if (ifa
->ifa_rtrequest
)
2539 ifa
->ifa_rtrequest(RTM_ADD
, rt
, SA(0));
2542 * notify any listenning routing agents of the change
2544 rt_newaddrmsg(cmd
, ifa
, error
, nrt
);
2546 routegenid_update();
2548 * We just wanted to add it; we don't actually need a
2549 * reference. This will result in a route that's added
2550 * to the routing table without a reference count. The
2551 * RTM_DELETE code will do the necessary step to adjust
2552 * the reference count at deletion time.
2554 RT_REMREF_LOCKED(rt
);
2561 rte_lock_init(struct rtentry
*rt
)
2563 lck_mtx_init(&rt
->rt_lock
, rte_mtx_grp
, rte_mtx_attr
);
2567 rte_lock_destroy(struct rtentry
*rt
)
2569 RT_LOCK_ASSERT_NOTHELD(rt
);
2570 lck_mtx_destroy(&rt
->rt_lock
, rte_mtx_grp
);
2574 rt_lock(struct rtentry
*rt
, boolean_t spin
)
2576 RT_LOCK_ASSERT_NOTHELD(rt
);
2578 lck_mtx_lock_spin(&rt
->rt_lock
);
2580 lck_mtx_lock(&rt
->rt_lock
);
2581 if (rte_debug
& RTD_DEBUG
)
2582 rte_lock_debug((struct rtentry_dbg
*)rt
);
2586 rt_unlock(struct rtentry
*rt
)
2588 RT_LOCK_ASSERT_HELD(rt
);
2589 if (rte_debug
& RTD_DEBUG
)
2590 rte_unlock_debug((struct rtentry_dbg
*)rt
);
2591 lck_mtx_unlock(&rt
->rt_lock
);
2596 rte_lock_debug(struct rtentry_dbg
*rte
)
2600 idx
= atomic_add_32_ov(&rte
->rtd_lock_cnt
, 1) % CTRACE_HIST_SIZE
;
2601 if (rte_debug
& RTD_TRACE
)
2602 ctrace_record(&rte
->rtd_lock
[idx
]);
2606 rte_unlock_debug(struct rtentry_dbg
*rte
)
2610 idx
= atomic_add_32_ov(&rte
->rtd_unlock_cnt
, 1) % CTRACE_HIST_SIZE
;
2611 if (rte_debug
& RTD_TRACE
)
2612 ctrace_record(&rte
->rtd_unlock
[idx
]);
2615 static struct rtentry
*
2618 if (rte_debug
& RTD_DEBUG
)
2619 return (rte_alloc_debug());
2621 return ((struct rtentry
*)zalloc(rte_zone
));
2625 rte_free(struct rtentry
*p
)
2627 if (rte_debug
& RTD_DEBUG
) {
2632 if (p
->rt_refcnt
!= 0)
2633 panic("rte_free: rte=%p refcnt=%d non-zero\n", p
, p
->rt_refcnt
);
2638 static inline struct rtentry
*
2639 rte_alloc_debug(void)
2641 struct rtentry_dbg
*rte
;
2643 rte
= ((struct rtentry_dbg
*)zalloc(rte_zone
));
2645 bzero(rte
, sizeof (*rte
));
2646 if (rte_debug
& RTD_TRACE
)
2647 ctrace_record(&rte
->rtd_alloc
);
2648 rte
->rtd_inuse
= RTD_INUSE
;
2650 return ((struct rtentry
*)rte
);
2654 rte_free_debug(struct rtentry
*p
)
2656 struct rtentry_dbg
*rte
= (struct rtentry_dbg
*)p
;
2658 if (p
->rt_refcnt
!= 0)
2659 panic("rte_free: rte=%p refcnt=%d\n", p
, p
->rt_refcnt
);
2661 if (rte
->rtd_inuse
== RTD_FREED
)
2662 panic("rte_free: double free rte=%p\n", rte
);
2663 else if (rte
->rtd_inuse
!= RTD_INUSE
)
2664 panic("rte_free: corrupted rte=%p\n", rte
);
2666 bcopy((caddr_t
)p
, (caddr_t
)&rte
->rtd_entry_saved
, sizeof (*p
));
2667 /* Preserve rt_lock to help catch use-after-free cases */
2668 bzero((caddr_t
)p
, offsetof(struct rtentry
, rt_lock
));
2670 rte
->rtd_inuse
= RTD_FREED
;
2672 if (rte_debug
& RTD_TRACE
)
2673 ctrace_record(&rte
->rtd_free
);
2675 if (!(rte_debug
& RTD_NO_FREE
))
2680 ctrace_record(ctrace_t
*tr
)
2682 tr
->th
= current_thread();
2683 bzero(tr
->pc
, sizeof (tr
->pc
));
2684 (void) OSBacktrace(tr
->pc
, CTRACE_STACK_SIZE
);