2 * Copyright (c) 2000-2009 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 <kern/lock.h>
74 #include <kern/zalloc.h>
77 #include <net/route.h>
79 #include <netinet/in.h>
80 #include <netinet/in_var.h>
81 #include <netinet/ip_mroute.h>
82 #include <netinet/ip_var.h>
84 #include <net/if_dl.h>
86 #include <libkern/OSAtomic.h>
87 #include <libkern/OSDebug.h>
89 #include <pexpert/pexpert.h>
92 * Synchronization notes:
94 * Routing entries fall under two locking domains: the global routing table
95 * lock (rnh_lock) and the per-entry lock (rt_lock); the latter is a mutex that
96 * resides (statically defined) in the rtentry structure.
98 * The locking domains for routing are defined as follows:
100 * The global routing lock is used to serialize all accesses to the radix
101 * trees defined by rt_tables[], as well as the tree of masks. This includes
102 * lookups, insertions and removals of nodes to/from the respective tree.
103 * It is also used to protect certain fields in the route entry that aren't
104 * often modified and/or require global serialization (more details below.)
106 * The per-route entry lock is used to serialize accesses to several routing
107 * entry fields (more details below.) Acquiring and releasing this lock is
108 * done via RT_LOCK() and RT_UNLOCK() routines.
110 * In cases where both rnh_lock and rt_lock must be held, the former must be
111 * acquired first in order to maintain lock ordering. It is not a requirement
112 * that rnh_lock be acquired first before rt_lock, but in case both must be
113 * acquired in succession, the correct lock ordering must be followed.
115 * The fields of the rtentry structure are protected in the following way:
119 * - Routing table lock (rnh_lock).
121 * rt_parent, rt_mask, rt_llinfo_free
123 * - Set once during creation and never changes; no locks to read.
125 * rt_flags, rt_genmask, rt_llinfo, rt_rmx, rt_refcnt, rt_gwroute
127 * - Routing entry lock (rt_lock) for read/write access.
129 * - Some values of rt_flags are either set once at creation time,
130 * or aren't currently used, and thus checking against them can
131 * be done without rt_lock: RTF_GATEWAY, RTF_HOST, RTF_DYNAMIC,
132 * RTF_DONE, RTF_XRESOLVE, RTF_STATIC, RTF_BLACKHOLE, RTF_ANNOUNCE,
133 * RTF_USETRAILERS, RTF_WASCLONED, RTF_PINNED, RTF_LOCAL,
134 * RTF_BROADCAST, RTF_MULTICAST, RTF_IFSCOPE, RTF_IFREF.
136 * rt_key, rt_gateway, rt_ifp, rt_ifa
138 * - Always written/modified with both rnh_lock and rt_lock held.
140 * - May be read freely with rnh_lock held, else must hold rt_lock
141 * for read access; holding both locks for read is also okay.
143 * - In the event rnh_lock is not acquired, or is not possible to be
144 * acquired across the operation, setting RTF_CONDEMNED on a route
145 * entry will prevent its rt_key, rt_gateway, rt_ifp and rt_ifa
146 * from being modified. This is typically done on a route that
147 * has been chosen for a removal (from the tree) prior to dropping
148 * the rt_lock, so that those values will remain the same until
149 * the route is freed.
151 * When rnh_lock is held rt_setgate(), rt_setif(), and rtsetifa() are
152 * single-threaded, thus exclusive. This flag will also prevent the
153 * route from being looked up via rt_lookup().
157 * - Assumes that 32-bit writes are atomic; no locks.
161 * - Currently unused; no locks.
163 * Operations on a route entry can be described as follows:
165 * CREATE an entry with reference count set to 0 as part of RTM_ADD/RESOLVE.
167 * INSERTION of an entry into the radix tree holds the rnh_lock, checks
168 * for duplicates and then adds the entry. rtrequest returns the entry
169 * after bumping up the reference count to 1 (for the caller).
171 * LOOKUP of an entry holds the rnh_lock and bumps up the reference count
172 * before returning; it is valid to also bump up the reference count using
173 * RT_ADDREF after the lookup has returned an entry.
175 * REMOVAL of an entry from the radix tree holds the rnh_lock, removes the
176 * entry but does not decrement the reference count. Removal happens when
177 * the route is explicitly deleted (RTM_DELETE) or when it is in the cached
178 * state and it expires. The route is said to be "down" when it is no
179 * longer present in the tree. Freeing the entry will happen on the last
180 * reference release of such a "down" route.
182 * RT_ADDREF/RT_REMREF operates on the routing entry which increments/
183 * decrements the reference count, rt_refcnt, atomically on the rtentry.
184 * rt_refcnt is modified only using this routine. The general rule is to
185 * do RT_ADDREF in the function that is passing the entry as an argument,
186 * in order to prevent the entry from being freed by the callee.
189 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
190 #define SA(p) ((struct sockaddr *)(p))
192 extern void kdp_set_gateway_mac (void *gatewaymac
);
194 extern struct domain routedomain
;
195 struct route_cb route_cb
;
196 __private_extern__
struct rtstat rtstat
= { 0, 0, 0, 0, 0 };
197 struct radix_node_head
*rt_tables
[AF_MAX
+1];
199 lck_mtx_t
*rnh_lock
; /* global routing tables mutex */
200 static lck_attr_t
*rnh_lock_attr
;
201 static lck_grp_t
*rnh_lock_grp
;
202 static lck_grp_attr_t
*rnh_lock_grp_attr
;
204 /* Lock group and attribute for routing entry locks */
205 static lck_attr_t
*rte_mtx_attr
;
206 static lck_grp_t
*rte_mtx_grp
;
207 static lck_grp_attr_t
*rte_mtx_grp_attr
;
209 lck_mtx_t
*route_domain_mtx
; /*### global routing tables mutex for now */
210 int rttrash
= 0; /* routes not in table but not freed */
212 unsigned int rte_debug
;
214 /* Possible flags for rte_debug */
215 #define RTD_DEBUG 0x1 /* enable or disable rtentry debug facility */
216 #define RTD_TRACE 0x2 /* trace alloc, free, refcnt and lock */
217 #define RTD_NO_FREE 0x4 /* don't free (good to catch corruptions) */
219 #define RTE_NAME "rtentry" /* name for zone and rt_lock */
221 static struct zone
*rte_zone
; /* special zone for rtentry */
222 #define RTE_ZONE_MAX 65536 /* maximum elements in zone */
223 #define RTE_ZONE_NAME RTE_NAME /* name of rtentry zone */
225 #define RTD_INUSE 0xFEEDFACE /* entry is in use */
226 #define RTD_FREED 0xDEADBEEF /* entry is freed */
229 __private_extern__
unsigned int ctrace_stack_size
= CTRACE_STACK_SIZE
;
230 __private_extern__
unsigned int ctrace_hist_size
= CTRACE_HIST_SIZE
;
233 * Debug variant of rtentry structure.
236 struct rtentry rtd_entry
; /* rtentry */
237 struct rtentry rtd_entry_saved
; /* saved rtentry */
238 uint32_t rtd_inuse
; /* in use pattern */
239 uint16_t rtd_refhold_cnt
; /* # of rtref */
240 uint16_t rtd_refrele_cnt
; /* # of rtunref */
241 uint32_t rtd_lock_cnt
; /* # of locks */
242 uint32_t rtd_unlock_cnt
; /* # of unlocks */
244 * Alloc and free callers.
249 * Circular lists of rtref and rtunref callers.
251 ctrace_t rtd_refhold
[CTRACE_HIST_SIZE
];
252 ctrace_t rtd_refrele
[CTRACE_HIST_SIZE
];
254 * Circular lists of locks and unlocks.
256 ctrace_t rtd_lock
[CTRACE_HIST_SIZE
];
257 ctrace_t rtd_unlock
[CTRACE_HIST_SIZE
];
261 TAILQ_ENTRY(rtentry_dbg
) rtd_trash_link
;
264 #define atomic_add_16_ov(a, n) \
265 ((uint16_t) OSAddAtomic16(n, (volatile SInt16 *)a))
266 #define atomic_add_32_ov(a, n) \
267 ((uint32_t) OSAddAtomic(n, a))
269 /* List of trash route entries protected by rnh_lock */
270 static TAILQ_HEAD(, rtentry_dbg
) rttrash_head
;
272 static void rte_lock_init(struct rtentry
*);
273 static void rte_lock_destroy(struct rtentry
*);
274 static inline struct rtentry
*rte_alloc_debug(void);
275 static inline void rte_free_debug(struct rtentry
*);
276 static inline void rte_lock_debug(struct rtentry_dbg
*);
277 static inline void rte_unlock_debug(struct rtentry_dbg
*);
278 static void rt_maskedcopy(struct sockaddr
*,
279 struct sockaddr
*, struct sockaddr
*);
280 static void rtable_init(void **);
281 static inline void rtref_audit(struct rtentry_dbg
*);
282 static inline void rtunref_audit(struct rtentry_dbg
*);
283 static struct rtentry
*rtalloc1_common_locked(struct sockaddr
*, int, uint32_t,
285 static int rtrequest_common_locked(int, struct sockaddr
*,
286 struct sockaddr
*, struct sockaddr
*, int, struct rtentry
**,
288 static void rtalloc_ign_common_locked(struct route
*, uint32_t, unsigned int);
289 static inline void sa_set_ifscope(struct sockaddr
*, unsigned int);
290 static struct sockaddr
*sin_copy(struct sockaddr_in
*, struct sockaddr_in
*,
292 static struct sockaddr
*mask_copy(struct sockaddr
*, struct sockaddr_in
*,
294 static struct sockaddr
*sa_trim(struct sockaddr
*, int);
295 static struct radix_node
*node_lookup(struct sockaddr
*, struct sockaddr
*,
297 static struct radix_node
*node_lookup_default(void);
298 static int rn_match_ifscope(struct radix_node
*, void *);
299 static struct ifaddr
*ifa_ifwithroute_common_locked(int,
300 const struct sockaddr
*, const struct sockaddr
*, unsigned int);
301 static struct rtentry
*rte_alloc(void);
302 static void rte_free(struct rtentry
*);
303 static void rtfree_common(struct rtentry
*, boolean_t
);
304 #if IFNET_ROUTE_REFCNT
305 static void rte_if_ref(struct ifnet
*, int);
306 #endif /* IFNET_ROUTE_REFCNT */
308 uint32_t route_generation
= 0;
311 * sockaddr_in with embedded interface scope; this is used internally
312 * to keep track of scoped route entries in the routing table. The
313 * fact that such a scope is embedded in the structure is an artifact
314 * of the current implementation which could change in future.
316 struct sockaddr_inifscope
{
318 sa_family_t sin_family
;
320 struct in_addr sin_addr
;
322 * To avoid possible conflict with an overlaid sockaddr_inarp
323 * having sin_other set to SIN_PROXY, we use the first 4-bytes
324 * of sin_zero since sin_srcaddr is one of the unused fields
333 #define sin_ifscope un._in_index.ifscope
336 #define SIN(sa) ((struct sockaddr_in *)(size_t)(sa))
337 #define SINIFSCOPE(sa) ((struct sockaddr_inifscope *)(size_t)(sa))
339 #define ASSERT_SINIFSCOPE(sa) { \
340 if ((sa)->sa_family != AF_INET || \
341 (sa)->sa_len < sizeof (struct sockaddr_in)) \
342 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
346 * Argument to leaf-matching routine; at present it is scoped routing
347 * specific but can be expanded in future to include other search filters.
349 struct matchleaf_arg
{
350 unsigned int ifscope
; /* interface scope */
354 * For looking up the non-scoped default route (sockaddr instead
355 * of sockaddr_in for convenience).
357 static struct sockaddr sin_def
= {
358 sizeof (struct sockaddr_in
), AF_INET
, { 0, }
362 * Interface index (scope) of the primary interface; determined at
363 * the time when the default, non-scoped route gets added, changed
364 * or deleted. Protected by rnh_lock.
366 static unsigned int primary_ifscope
= IFSCOPE_NONE
;
368 #define INET_DEFAULT(dst) \
369 ((dst)->sa_family == AF_INET && SIN(dst)->sin_addr.s_addr == 0)
371 #define RT(r) ((struct rtentry *)r)
372 #define RT_HOST(r) (RT(r)->rt_flags & RTF_HOST)
374 #if IFNET_ROUTE_REFCNT
375 SYSCTL_DECL(_net_idle_route
);
377 static int rt_if_idle_expire_timeout
= RT_IF_IDLE_EXPIRE_TIMEOUT
;
378 SYSCTL_INT(_net_idle_route
, OID_AUTO
, expire_timeout
, CTLFLAG_RW
,
379 &rt_if_idle_expire_timeout
, 0, "Default expiration time on routes for "
380 "interface idle reference counting");
381 #endif /* IFNET_ROUTE_REFCNT */
384 * Given a route, determine whether or not it is the non-scoped default
385 * route; dst typically comes from rt_key(rt) but may be coming from
386 * a separate place when rt is in the process of being created.
389 rt_inet_default(struct rtentry
*rt
, struct sockaddr
*dst
)
391 return (INET_DEFAULT(dst
) && !(rt
->rt_flags
& RTF_IFSCOPE
));
395 * Set the ifscope of the primary interface; caller holds rnh_lock.
398 set_primary_ifscope(unsigned int ifscope
)
400 primary_ifscope
= ifscope
;
404 * Return the ifscope of the primary interface; caller holds rnh_lock.
407 get_primary_ifscope(void)
409 return (primary_ifscope
);
413 * Embed ifscope into a given a sockaddr_in.
416 sa_set_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
418 /* Caller must pass in sockaddr_in */
419 ASSERT_SINIFSCOPE(sa
);
421 SINIFSCOPE(sa
)->sin_ifscope
= ifscope
;
425 * Given a sockaddr_in, return the embedded ifscope to the caller.
428 sa_get_ifscope(struct sockaddr
*sa
)
430 /* Caller must pass in sockaddr_in */
431 ASSERT_SINIFSCOPE(sa
);
433 return (SINIFSCOPE(sa
)->sin_ifscope
);
437 * Copy a sockaddr_in src to dst and embed ifscope into dst.
439 static struct sockaddr
*
440 sin_copy(struct sockaddr_in
*src
, struct sockaddr_in
*dst
, unsigned int ifscope
)
443 sa_set_ifscope(SA(dst
), ifscope
);
449 * Copy a mask from src to a sockaddr_in dst and embed ifscope into dst.
451 static struct sockaddr
*
452 mask_copy(struct sockaddr
*src
, struct sockaddr_in
*dst
, unsigned int ifscope
)
454 /* We know dst is at least the size of sockaddr{_in} */
455 bzero(dst
, sizeof (*dst
));
456 rt_maskedcopy(src
, SA(dst
), src
);
459 * The length of the mask sockaddr would need to be adjusted
460 * to cover the additional sin_ifscope field; when ifscope is
461 * IFSCOPE_NONE, we'd end up clearing the embedded ifscope on
462 * the destination mask in addition to extending the length
463 * of the sockaddr, as a side effect. This is okay, as any
464 * trailing zeroes would be skipped by rn_addmask prior to
465 * inserting or looking up the mask in the mask tree.
467 SINIFSCOPE(dst
)->sin_ifscope
= ifscope
;
468 SINIFSCOPE(dst
)->sin_len
=
469 offsetof(struct sockaddr_inifscope
, sin_ifscope
) +
470 sizeof (SINIFSCOPE(dst
)->sin_ifscope
);
476 * Trim trailing zeroes on a sockaddr and update its length.
478 static struct sockaddr
*
479 sa_trim(struct sockaddr
*sa
, int skip
)
481 caddr_t cp
, base
= (caddr_t
)sa
+ skip
;
483 if (sa
->sa_len
<= skip
)
486 for (cp
= base
+ (sa
->sa_len
- skip
); cp
> base
&& cp
[-1] == 0;)
489 sa
->sa_len
= (cp
- base
) + skip
;
490 if (sa
->sa_len
< skip
) {
491 /* Must not happen, and if so, panic */
492 panic("%s: broken logic (sa_len %d < skip %d )", __func__
,
495 } else if (sa
->sa_len
== skip
) {
496 /* If we end up with all zeroes, then there's no mask */
504 * Called by rtm_msg{1,2} routines to "scrub" the embedded interface scope
505 * away from the socket address structure, so that clients of the routing
506 * socket will not be confused by the presence of the embedded scope, or the
507 * side effect of the increased length due to that. The source sockaddr is
508 * not modified; instead, the scrubbing happens on the destination sockaddr
509 * storage that is passed in by the caller.
512 rtm_scrub_ifscope(int idx
, struct sockaddr
*hint
, struct sockaddr
*sa
,
513 struct sockaddr_storage
*ss
)
515 struct sockaddr
*ret
= sa
;
520 * If this is for an AF_INET destination address, call
521 * sin_copy() with IFSCOPE_NONE as it does what we need.
523 if (sa
->sa_family
== AF_INET
&&
524 SINIFSCOPE(sa
)->sin_ifscope
!= IFSCOPE_NONE
) {
525 bzero(ss
, sizeof (*ss
));
526 ret
= sin_copy(SIN(sa
), SIN(ss
), IFSCOPE_NONE
);
532 * If this is for a mask, we can't tell whether or not
533 * there is an embedded interface scope, as the span of
534 * bytes between sa_len and the beginning of the mask
535 * (offset of sin_addr in the case of AF_INET) may be
536 * filled with all-ones by rn_addmask(), and hence we
537 * cannot rely on sa_family. Because of this, we use
538 * the sa_family of the hint sockaddr (RTAX_{DST,IFA})
539 * as indicator as to whether or not the mask is to be
540 * treated as one for AF_INET. Clearing the embedded
541 * scope involves setting it to IFSCOPE_NONE followed
542 * by calling sa_trim() to trim trailing zeroes from
543 * the storage sockaddr, which reverses what was done
544 * earlier by mask_copy() on the source sockaddr.
546 int skip
= offsetof(struct sockaddr_in
, sin_addr
);
547 if (sa
->sa_len
> skip
&& sa
->sa_len
<= sizeof (*ss
) &&
548 hint
!= NULL
&& hint
->sa_family
== AF_INET
) {
549 bzero(ss
, sizeof (*ss
));
550 bcopy(sa
, ss
, sa
->sa_len
);
551 SINIFSCOPE(ss
)->sin_ifscope
= IFSCOPE_NONE
;
552 ret
= sa_trim(SA(ss
), skip
);
564 * Callback leaf-matching routine for rn_matchaddr_args used
565 * for looking up an exact match for a scoped route entry.
568 rn_match_ifscope(struct radix_node
*rn
, void *arg
)
570 struct rtentry
*rt
= (struct rtentry
*)rn
;
571 struct matchleaf_arg
*ma
= arg
;
573 if (!(rt
->rt_flags
& RTF_IFSCOPE
) || rt_key(rt
)->sa_family
!= AF_INET
)
576 return (SINIFSCOPE(rt_key(rt
))->sin_ifscope
== ma
->ifscope
);
580 rtable_init(void **table
)
583 for (dom
= domains
; dom
; dom
= dom
->dom_next
)
584 if (dom
->dom_rtattach
)
585 dom
->dom_rtattach(&table
[dom
->dom_family
],
594 PE_parse_boot_argn("rte_debug", &rte_debug
, sizeof (rte_debug
));
596 rte_debug
|= RTD_DEBUG
;
598 rnh_lock_grp_attr
= lck_grp_attr_alloc_init();
599 rnh_lock_grp
= lck_grp_alloc_init("route", rnh_lock_grp_attr
);
600 rnh_lock_attr
= lck_attr_alloc_init();
601 if ((rnh_lock
= lck_mtx_alloc_init(rnh_lock_grp
,
602 rnh_lock_attr
)) == NULL
) {
603 printf("route_init: can't alloc rnh_lock\n");
607 rte_mtx_grp_attr
= lck_grp_attr_alloc_init();
608 rte_mtx_grp
= lck_grp_alloc_init(RTE_NAME
, rte_mtx_grp_attr
);
609 rte_mtx_attr
= lck_attr_alloc_init();
611 lck_mtx_lock(rnh_lock
);
612 rn_init(); /* initialize all zeroes, all ones, mask table */
613 lck_mtx_unlock(rnh_lock
);
614 rtable_init((void **)rt_tables
);
615 route_domain_mtx
= routedomain
.dom_mtx
;
617 if (rte_debug
& RTD_DEBUG
)
618 size
= sizeof (struct rtentry_dbg
);
620 size
= sizeof (struct rtentry
);
622 rte_zone
= zinit(size
, RTE_ZONE_MAX
* size
, 0, RTE_ZONE_NAME
);
623 if (rte_zone
== NULL
)
624 panic("route_init: failed allocating rte_zone");
626 zone_change(rte_zone
, Z_EXPAND
, TRUE
);
628 TAILQ_INIT(&rttrash_head
);
632 * Atomically increment route generation counter
635 routegenid_update(void)
637 (void) atomic_add_32_ov(&route_generation
, 1);
641 * Packet routing routines.
644 rtalloc(struct route
*ro
)
650 rtalloc_ign_locked(struct route
*ro
, uint32_t ignore
)
652 return (rtalloc_ign_common_locked(ro
, ignore
, IFSCOPE_NONE
));
656 rtalloc_scoped_ign_locked(struct route
*ro
, uint32_t ignore
,
657 unsigned int ifscope
)
659 return (rtalloc_ign_common_locked(ro
, ignore
, ifscope
));
663 rtalloc_ign_common_locked(struct route
*ro
, uint32_t ignore
,
664 unsigned int ifscope
)
668 if ((rt
= ro
->ro_rt
) != NULL
) {
670 if (rt
->rt_ifp
!= NULL
&& (rt
->rt_flags
& RTF_UP
) &&
671 rt
->generation_id
== route_generation
) {
679 ro
->ro_rt
= rtalloc1_common_locked(&ro
->ro_dst
, 1, ignore
, ifscope
);
680 if (ro
->ro_rt
!= NULL
) {
681 ro
->ro_rt
->generation_id
= route_generation
;
682 RT_LOCK_ASSERT_NOTHELD(ro
->ro_rt
);
687 rtalloc_ign(struct route
*ro
, uint32_t ignore
)
689 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
690 lck_mtx_lock(rnh_lock
);
691 rtalloc_ign_locked(ro
, ignore
);
692 lck_mtx_unlock(rnh_lock
);
696 rtalloc_scoped_ign(struct route
*ro
, uint32_t ignore
, unsigned int ifscope
)
698 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
699 lck_mtx_lock(rnh_lock
);
700 rtalloc_scoped_ign_locked(ro
, ignore
, ifscope
);
701 lck_mtx_unlock(rnh_lock
);
705 rtalloc1_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
707 return (rtalloc1_common_locked(dst
, report
, ignflags
, IFSCOPE_NONE
));
711 rtalloc1_scoped_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
712 unsigned int ifscope
)
714 return (rtalloc1_common_locked(dst
, report
, ignflags
, ifscope
));
718 * Look up the route that matches the address given
719 * Or, at least try.. Create a cloned route if needed.
721 static struct rtentry
*
722 rtalloc1_common_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
723 unsigned int ifscope
)
725 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
726 struct rtentry
*rt
, *newrt
= NULL
;
727 struct rt_addrinfo info
;
729 int err
= 0, msgtype
= RTM_MISS
;
735 * Find the longest prefix or exact (in the scoped case) address match;
736 * callee adds a reference to entry and checks for root node as well
738 rt
= rt_lookup(FALSE
, dst
, NULL
, rnh
, ifscope
);
744 nflags
= rt
->rt_flags
& ~ignflags
;
746 if (report
&& (nflags
& (RTF_CLONING
| RTF_PRCLONING
))) {
748 * We are apparently adding (report = 0 in delete).
749 * If it requires that it be cloned, do so.
750 * (This implies it wasn't a HOST route.)
752 err
= rtrequest_locked(RTM_RESOLVE
, dst
, NULL
, NULL
, 0, &newrt
);
755 * If the cloning didn't succeed, maybe what we
756 * have from lookup above will do. Return that;
757 * no need to hold another reference since it's
765 * We cloned it; drop the original route found during lookup.
766 * The resulted cloned route (newrt) would now have an extra
767 * reference held during rtrequest.
770 if ((rt
= newrt
) && (rt
->rt_flags
& RTF_XRESOLVE
)) {
772 * If the new route specifies it be
773 * externally resolved, then go do that.
775 msgtype
= RTM_RESOLVE
;
783 * Either we hit the root or couldn't find any match,
784 * Which basically means "cant get there from here"
786 rtstat
.rts_unreach
++;
790 * If required, report the failure to the supervising
792 * For a delete, this is not an error. (report == 0)
794 bzero((caddr_t
)&info
, sizeof(info
));
795 info
.rti_info
[RTAX_DST
] = dst
;
796 rt_missmsg(msgtype
, &info
, 0, err
);
803 rtalloc1(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
805 struct rtentry
* entry
;
806 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
807 lck_mtx_lock(rnh_lock
);
808 entry
= rtalloc1_locked(dst
, report
, ignflags
);
809 lck_mtx_unlock(rnh_lock
);
814 rtalloc1_scoped(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
815 unsigned int ifscope
)
817 struct rtentry
* entry
;
818 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
819 lck_mtx_lock(rnh_lock
);
820 entry
= rtalloc1_scoped_locked(dst
, report
, ignflags
, ifscope
);
821 lck_mtx_unlock(rnh_lock
);
826 * Remove a reference count from an rtentry.
827 * If the count gets low enough, take it out of the routing table
830 rtfree_locked(struct rtentry
*rt
)
832 rtfree_common(rt
, TRUE
);
836 rtfree_common(struct rtentry
*rt
, boolean_t locked
)
838 struct radix_node_head
*rnh
;
841 * Atomically decrement the reference count and if it reaches 0,
842 * and there is a close function defined, call the close function.
845 if (rtunref(rt
) > 0) {
851 * To avoid violating lock ordering, we must drop rt_lock before
852 * trying to acquire the global rnh_lock. If we are called with
853 * rnh_lock held, then we already have exclusive access; otherwise
854 * we do the lock dance.
858 * Note that we check it again below after grabbing rnh_lock,
859 * since it is possible that another thread doing a lookup wins
860 * the race, grabs the rnh_lock first, and bumps up the reference
861 * count in which case the route should be left alone as it is
862 * still in use. It's also possible that another thread frees
863 * the route after we drop rt_lock; to prevent the route from
864 * being freed, we hold an extra reference.
866 RT_ADDREF_LOCKED(rt
);
868 lck_mtx_lock(rnh_lock
);
870 RT_REMREF_LOCKED(rt
);
871 if (rt
->rt_refcnt
> 0) {
872 /* We've lost the race, so abort */
879 * We may be blocked on other lock(s) as part of freeing
880 * the entry below, so convert from spin to full mutex.
884 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
886 /* Negative refcnt must never happen */
887 if (rt
->rt_refcnt
!= 0)
888 panic("rt %p invalid refcnt %d", rt
, rt
->rt_refcnt
);
891 * find the tree for that address family
892 * Note: in the case of igmp packets, there might not be an rnh
894 rnh
= rt_tables
[rt_key(rt
)->sa_family
];
897 * On last reference give the "close method" a chance to cleanup
898 * private state. This also permits (for IPv4 and IPv6) a chance
899 * to decide if the routing table entry should be purged immediately
900 * or at a later time. When an immediate purge is to happen the
901 * close routine typically issues RTM_DELETE which clears the RTF_UP
902 * flag on the entry so that the code below reclaims the storage.
904 if (rnh
!= NULL
&& rnh
->rnh_close
!= NULL
)
905 rnh
->rnh_close((struct radix_node
*)rt
, rnh
);
908 * If we are no longer "up" (and ref == 0) then we can free the
909 * resources associated with the route.
911 if (!(rt
->rt_flags
& RTF_UP
)) {
912 if (rt
->rt_nodes
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
))
913 panic("rt %p freed while in radix tree\n", rt
);
915 * the rtentry must have been removed from the routing table
916 * so it is represented in rttrash; remove that now.
918 (void) OSDecrementAtomic(&rttrash
);
919 if (rte_debug
& RTD_DEBUG
) {
920 TAILQ_REMOVE(&rttrash_head
, (struct rtentry_dbg
*)rt
,
925 * Route is no longer in the tree and refcnt is 0;
926 * we have exclusive access, so destroy it.
931 * release references on items we hold them on..
932 * e.g other routes and ifaddrs.
934 if (rt
->rt_parent
!= NULL
) {
935 rtfree_locked(rt
->rt_parent
);
936 rt
->rt_parent
= NULL
;
939 if (rt
->rt_ifa
!= NULL
) {
945 * Now free any attached link-layer info.
947 if (rt
->rt_llinfo
!= NULL
) {
948 if (rt
->rt_llinfo_free
!= NULL
)
949 (*rt
->rt_llinfo_free
)(rt
->rt_llinfo
);
951 R_Free(rt
->rt_llinfo
);
952 rt
->rt_llinfo
= NULL
;
956 * The key is separately alloc'd so free it (see rt_setgate()).
957 * This also frees the gateway, as they are always malloc'd
963 * and the rtentry itself of course
965 rte_lock_destroy(rt
);
969 * The "close method" has been called, but the route is
970 * still in the radix tree with zero refcnt, i.e. "up"
971 * and in the cached state.
977 lck_mtx_unlock(rnh_lock
);
981 rtfree(struct rtentry
*rt
)
983 rtfree_common(rt
, FALSE
);
987 * Decrements the refcount but does not free the route when
988 * the refcount reaches zero. Unless you have really good reason,
989 * use rtfree not rtunref.
992 rtunref(struct rtentry
*p
)
994 RT_LOCK_ASSERT_HELD(p
);
996 if (p
->rt_refcnt
== 0)
997 panic("%s(%p) bad refcnt\n", __func__
, p
);
1001 if (rte_debug
& RTD_DEBUG
)
1002 rtunref_audit((struct rtentry_dbg
*)p
);
1004 /* Return new value */
1005 return (p
->rt_refcnt
);
1009 rtunref_audit(struct rtentry_dbg
*rte
)
1013 if (rte
->rtd_inuse
!= RTD_INUSE
)
1014 panic("rtunref: on freed rte=%p\n", rte
);
1016 idx
= atomic_add_16_ov(&rte
->rtd_refrele_cnt
, 1) % CTRACE_HIST_SIZE
;
1017 if (rte_debug
& RTD_TRACE
)
1018 ctrace_record(&rte
->rtd_refrele
[idx
]);
1022 * Add a reference count from an rtentry.
1025 rtref(struct rtentry
*p
)
1027 RT_LOCK_ASSERT_HELD(p
);
1029 if (++p
->rt_refcnt
== 0)
1030 panic("%s(%p) bad refcnt\n", __func__
, p
);
1032 if (rte_debug
& RTD_DEBUG
)
1033 rtref_audit((struct rtentry_dbg
*)p
);
1037 rtref_audit(struct rtentry_dbg
*rte
)
1041 if (rte
->rtd_inuse
!= RTD_INUSE
)
1042 panic("rtref_audit: on freed rte=%p\n", rte
);
1044 idx
= atomic_add_16_ov(&rte
->rtd_refhold_cnt
, 1) % CTRACE_HIST_SIZE
;
1045 if (rte_debug
& RTD_TRACE
)
1046 ctrace_record(&rte
->rtd_refhold
[idx
]);
1050 rtsetifa(struct rtentry
*rt
, struct ifaddr
* ifa
)
1052 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1054 RT_LOCK_ASSERT_HELD(rt
);
1056 if (rt
->rt_ifa
== ifa
)
1059 /* Release the old ifa */
1061 ifafree(rt
->rt_ifa
);
1066 /* Take a reference to the ifa */
1072 * Force a routing table entry to the specified
1073 * destination to go through the given gateway.
1074 * Normally called as a result of a routing redirect
1075 * message from the network layer.
1078 rtredirect(struct ifnet
*ifp
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1079 struct sockaddr
*netmask
, int flags
, struct sockaddr
*src
,
1080 struct rtentry
**rtp
)
1082 struct rtentry
*rt
= NULL
;
1085 struct rt_addrinfo info
;
1086 struct ifaddr
*ifa
= NULL
;
1087 unsigned int ifscope
= (ifp
!= NULL
) ? ifp
->if_index
: IFSCOPE_NONE
;
1088 struct sockaddr_in sin
;
1090 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1091 lck_mtx_lock(rnh_lock
);
1094 * Verify the gateway is directly reachable; if scoped routing
1095 * is enabled, verify that it is reachable from the interface
1096 * where the ICMP redirect arrived on.
1098 if ((ifa
= ifa_ifwithnet_scoped(gateway
, ifscope
)) == NULL
) {
1099 error
= ENETUNREACH
;
1103 /* Lookup route to the destination (from the original IP header) */
1104 rt
= rtalloc1_scoped_locked(dst
, 0, RTF_CLONING
|RTF_PRCLONING
, ifscope
);
1108 /* Embed scope in src for comparison against rt_gateway below */
1109 if (ip_doscopedroute
&& src
->sa_family
== AF_INET
)
1110 src
= sin_copy(SIN(src
), &sin
, ifscope
);
1113 * If the redirect isn't from our current router for this dst,
1114 * it's either old or wrong. If it redirects us to ourselves,
1115 * we have a routing loop, perhaps as a result of an interface
1116 * going down recently.
1118 if (!(flags
& RTF_DONE
) && rt
!= NULL
&&
1119 (!equal(src
, rt
->rt_gateway
) || !equal(rt
->rt_ifa
->ifa_addr
,
1124 if ((ifa
= ifa_ifwithaddr(gateway
))) {
1127 error
= EHOSTUNREACH
;
1143 * Create a new entry if we just got back a wildcard entry
1144 * or the the lookup failed. This is necessary for hosts
1145 * which use routing redirects generated by smart gateways
1146 * to dynamically build the routing tables.
1148 if ((rt
== NULL
) || (rt_mask(rt
) != NULL
&& rt_mask(rt
)->sa_len
< 2))
1151 * Don't listen to the redirect if it's
1152 * for a route to an interface.
1154 RT_LOCK_ASSERT_HELD(rt
);
1155 if (rt
->rt_flags
& RTF_GATEWAY
) {
1156 if (((rt
->rt_flags
& RTF_HOST
) == 0) && (flags
& RTF_HOST
)) {
1158 * Changing from route to net => route to host.
1159 * Create new route, rather than smashing route
1160 * to net; similar to cloned routes, the newly
1161 * created host route is scoped as well.
1166 flags
|= RTF_GATEWAY
| RTF_DYNAMIC
;
1167 error
= rtrequest_scoped_locked(RTM_ADD
, dst
,
1168 gateway
, netmask
, flags
, NULL
, ifscope
);
1169 stat
= &rtstat
.rts_dynamic
;
1172 * Smash the current notion of the gateway to
1173 * this destination. Should check about netmask!!!
1175 rt
->rt_flags
|= RTF_MODIFIED
;
1176 flags
|= RTF_MODIFIED
;
1177 stat
= &rtstat
.rts_newgateway
;
1179 * add the key and gateway (in one malloc'd chunk).
1181 error
= rt_setgate(rt
, rt_key(rt
), gateway
);
1186 error
= EHOSTUNREACH
;
1190 RT_LOCK_ASSERT_NOTHELD(rt
);
1198 rtstat
.rts_badredirect
++;
1203 routegenid_update();
1205 lck_mtx_unlock(rnh_lock
);
1206 bzero((caddr_t
)&info
, sizeof(info
));
1207 info
.rti_info
[RTAX_DST
] = dst
;
1208 info
.rti_info
[RTAX_GATEWAY
] = gateway
;
1209 info
.rti_info
[RTAX_NETMASK
] = netmask
;
1210 info
.rti_info
[RTAX_AUTHOR
] = src
;
1211 rt_missmsg(RTM_REDIRECT
, &info
, flags
, error
);
1215 * Routing table ioctl interface.
1218 rtioctl(unsigned long req
, caddr_t data
, struct proc
*p
)
1221 #if INET && MROUTING
1222 return mrt_ioctl(req
, data
);
1225 #pragma unused(data)
1233 const struct sockaddr
*dst
,
1234 const struct sockaddr
*gateway
)
1238 lck_mtx_lock(rnh_lock
);
1239 ifa
= ifa_ifwithroute_locked(flags
, dst
, gateway
);
1240 lck_mtx_unlock(rnh_lock
);
1246 ifa_ifwithroute_locked(int flags
, const struct sockaddr
*dst
,
1247 const struct sockaddr
*gateway
)
1249 return (ifa_ifwithroute_common_locked((flags
& ~RTF_IFSCOPE
), dst
,
1250 gateway
, IFSCOPE_NONE
));
1254 ifa_ifwithroute_scoped_locked(int flags
, const struct sockaddr
*dst
,
1255 const struct sockaddr
*gateway
, unsigned int ifscope
)
1257 if (ifscope
!= IFSCOPE_NONE
)
1258 flags
|= RTF_IFSCOPE
;
1260 flags
&= ~RTF_IFSCOPE
;
1262 return (ifa_ifwithroute_common_locked(flags
, dst
, gateway
, ifscope
));
1265 static struct ifaddr
*
1266 ifa_ifwithroute_common_locked(int flags
, const struct sockaddr
*dst
,
1267 const struct sockaddr
*gateway
, unsigned int ifscope
)
1269 struct ifaddr
*ifa
= NULL
;
1270 struct rtentry
*rt
= NULL
;
1271 struct sockaddr_in dst_in
, gw_in
;
1273 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1275 if (ip_doscopedroute
) {
1277 * Just in case the sockaddr passed in by the caller
1278 * contains embedded scope, make sure to clear it since
1279 * IPv4 interface addresses aren't scoped.
1281 if (dst
!= NULL
&& dst
->sa_family
== AF_INET
)
1282 dst
= sin_copy(SIN(dst
), &dst_in
, IFSCOPE_NONE
);
1283 if (gateway
!= NULL
&& gateway
->sa_family
== AF_INET
)
1284 gateway
= sin_copy(SIN(gateway
), &gw_in
, IFSCOPE_NONE
);
1287 if (!(flags
& RTF_GATEWAY
)) {
1289 * If we are adding a route to an interface,
1290 * and the interface is a pt to pt link
1291 * we should search for the destination
1292 * as our clue to the interface. Otherwise
1293 * we can use the local address.
1295 if (flags
& RTF_HOST
) {
1296 ifa
= ifa_ifwithdstaddr(dst
);
1299 ifa
= ifa_ifwithaddr_scoped(gateway
, ifscope
);
1302 * If we are adding a route to a remote net
1303 * or host, the gateway may still be on the
1304 * other end of a pt to pt link.
1306 ifa
= ifa_ifwithdstaddr(gateway
);
1309 ifa
= ifa_ifwithnet_scoped(gateway
, ifscope
);
1311 /* Workaround to avoid gcc warning regarding const variable */
1312 rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)dst
,
1319 RT_REMREF_LOCKED(rt
);
1324 if (ifa
!= NULL
&& ifa
->ifa_addr
->sa_family
!= dst
->sa_family
) {
1325 struct ifaddr
*newifa
;
1326 /* Callee adds reference to newifa upon success */
1327 newifa
= ifaof_ifpforaddr(dst
, ifa
->ifa_ifp
);
1328 if (newifa
!= NULL
) {
1334 * If we are adding a gateway, it is quite possible that the
1335 * routing table has a static entry in place for the gateway,
1336 * that may not agree with info garnered from the interfaces.
1337 * The routing table should carry more precedence than the
1338 * interfaces in this matter. Must be careful not to stomp
1339 * on new entries from rtinit, hence (ifa->ifa_addr != gateway).
1342 !equal(ifa
->ifa_addr
, (struct sockaddr
*)(size_t)gateway
)) &&
1343 (rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)gateway
,
1344 0, 0, ifscope
)) != NULL
) {
1351 RT_REMREF_LOCKED(rt
);
1355 * If an interface scope was specified, the interface index of
1356 * the found ifaddr must be equivalent to that of the scope;
1357 * otherwise there is no match.
1359 if ((flags
& RTF_IFSCOPE
) &&
1360 ifa
!= NULL
&& ifa
->ifa_ifp
->if_index
!= ifscope
) {
1368 static int rt_fixdelete(struct radix_node
*, void *);
1369 static int rt_fixchange(struct radix_node
*, void *);
1372 struct rtentry
*rt0
;
1373 struct radix_node_head
*rnh
;
1377 rtrequest_locked(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1378 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
)
1380 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1381 (flags
& ~RTF_IFSCOPE
), ret_nrt
, IFSCOPE_NONE
));
1385 rtrequest_scoped_locked(int req
, struct sockaddr
*dst
,
1386 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1387 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1389 if (ifscope
!= IFSCOPE_NONE
)
1390 flags
|= RTF_IFSCOPE
;
1392 flags
&= ~RTF_IFSCOPE
;
1394 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1395 flags
, ret_nrt
, ifscope
));
1399 * Do appropriate manipulations of a routing tree given all the bits of
1402 * Embedding the scope in the radix key is an internal job that should be
1403 * left to routines in this module. Callers should specify the scope value
1404 * to the "scoped" variants of route routines instead of manipulating the
1405 * key itself. This is typically done when creating a scoped route, e.g.
1406 * rtrequest(RTM_ADD). Once such a route is created and marked with the
1407 * RTF_IFSCOPE flag, callers can simply use its rt_key(rt) to clone it
1408 * (RTM_RESOLVE) or to remove it (RTM_DELETE). An exception to this is
1409 * during certain routing socket operations where the search key might be
1410 * derived from the routing message itself, in which case the caller must
1411 * specify the destination address and scope value for RTM_ADD/RTM_DELETE.
1414 rtrequest_common_locked(int req
, struct sockaddr
*dst0
,
1415 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1416 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1420 struct radix_node
*rn
;
1421 struct radix_node_head
*rnh
;
1422 struct ifaddr
*ifa
= NULL
;
1423 struct sockaddr
*ndst
, *dst
= dst0
;
1424 struct sockaddr_in sin
, mask
;
1425 #define senderr(x) { error = x ; goto bad; }
1427 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1429 * Find the correct routing tree to use for this Address Family
1431 if ((rnh
= rt_tables
[dst
->sa_family
]) == 0)
1434 * If we are adding a host route then we don't want to put
1435 * a netmask in the tree
1437 if (flags
& RTF_HOST
)
1441 * If RTF_IFSCOPE is specified, use a local copy of the destination
1442 * address to embed the scope into. This logic is repeated below
1443 * in the RTM_RESOLVE handler since the caller does not normally
1444 * specify such a flag during a resolve; instead it passes in the
1445 * route used for cloning for which the scope info is derived from.
1446 * Note also that in the case of RTM_DELETE, the address passed in
1447 * by the caller might already contain the embedded scope info when
1448 * it is the key itself, thus making RTF_IFSCOPE unnecessary; one
1449 * instance where it is explicitly set is inside route_output()
1450 * as part of handling a routing socket request.
1452 if (req
!= RTM_RESOLVE
&& (flags
& RTF_IFSCOPE
)) {
1453 /* Scoped routing is for AF_INET only */
1454 if (dst
->sa_family
!= AF_INET
||
1455 (req
== RTM_ADD
&& !ip_doscopedroute
))
1458 if (ifscope
== IFSCOPE_NONE
) {
1459 flags
&= ~RTF_IFSCOPE
;
1461 /* Embed ifscope into the key (local copy) */
1462 dst
= sin_copy(SIN(dst
), &sin
, ifscope
);
1464 /* Embed ifscope into netmask (local copy) */
1465 if (netmask
!= NULL
)
1466 netmask
= mask_copy(netmask
, &mask
, ifscope
);
1473 * Remove the item from the tree and return it.
1474 * Complain if it is not there and do no more processing.
1476 if ((rn
= rnh
->rnh_deladdr(dst
, netmask
, rnh
)) == 0)
1478 if (rn
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
))
1479 panic ("rtrequest delete");
1480 rt
= (struct rtentry
*)rn
;
1483 * Take an extra reference to handle the deletion of a route
1484 * entry whose reference count is already 0; e.g. an expiring
1485 * cloned route entry or an entry that was added to the table
1486 * with 0 reference. If the caller is interested in this route,
1487 * we will return it with the reference intact. Otherwise we
1488 * will decrement the reference via rtfree_locked() and then
1489 * possibly deallocate it.
1492 RT_ADDREF_LOCKED(rt
);
1493 rt
->rt_flags
&= ~RTF_UP
;
1496 * For consistency, in case the caller didn't set the flag.
1498 rt
->rt_flags
|= RTF_CONDEMNED
;
1501 * Now search what's left of the subtree for any cloned
1502 * routes which might have been formed from this node.
1504 if ((rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) &&
1507 rnh
->rnh_walktree_from(rnh
, dst
, rt_mask(rt
),
1513 * Remove any external references we may have.
1514 * This might result in another rtentry being freed if
1515 * we held its last reference.
1517 if (rt
->rt_gwroute
!= NULL
) {
1518 rtfree_locked(rt
->rt_gwroute
);
1519 rt
->rt_gwroute
= NULL
;
1523 * give the protocol a chance to keep things in sync.
1525 if ((ifa
= rt
->rt_ifa
) && ifa
->ifa_rtrequest
)
1526 ifa
->ifa_rtrequest(RTM_DELETE
, rt
, SA(0));
1530 * one more rtentry floating around that is not
1531 * linked to the routing table.
1533 (void) OSIncrementAtomic(&rttrash
);
1534 if (rte_debug
& RTD_DEBUG
) {
1535 TAILQ_INSERT_TAIL(&rttrash_head
,
1536 (struct rtentry_dbg
*)rt
, rtd_trash_link
);
1540 * If this is the (non-scoped) default route, clear
1541 * the interface index used for the primary ifscope.
1543 if (rt_inet_default(rt
, rt_key(rt
)))
1544 set_primary_ifscope(IFSCOPE_NONE
);
1546 #if IFNET_ROUTE_REFCNT
1547 if (rt
->rt_if_ref_fn
!= NULL
) {
1548 rt
->rt_if_ref_fn(rt
->rt_ifp
, -1);
1549 rt
->rt_flags
&= ~RTF_IFREF
;
1551 #endif /* IFNET_ROUTE_REFCNT */
1556 * If the caller wants it, then it can have it,
1557 * but it's up to it to free the rtentry as we won't be
1560 if (ret_nrt
!= NULL
) {
1561 /* Return the route to caller with reference intact */
1564 /* Dereference or deallocate the route */
1570 if (ret_nrt
== 0 || (rt
= *ret_nrt
) == 0)
1573 * If cloning, we have the parent route given by the caller
1574 * and will use its rt_gateway, rt_rmx as part of the cloning
1575 * process below. Since rnh_lock is held at this point, the
1576 * parent's rt_ifa and rt_gateway will not change, and its
1577 * relevant rt_flags will not change as well. The only thing
1578 * that could change are the metrics, and thus we hold the
1579 * parent route's rt_lock later on during the actual copying
1584 flags
= rt
->rt_flags
&
1585 ~(RTF_CLONING
| RTF_PRCLONING
| RTF_STATIC
);
1586 flags
|= RTF_WASCLONED
;
1587 gateway
= rt
->rt_gateway
;
1588 if ((netmask
= rt
->rt_genmask
) == 0)
1591 if (!ip_doscopedroute
|| dst
->sa_family
!= AF_INET
)
1594 * When scoped routing is enabled, cloned entries are
1595 * always scoped according to the interface portion of
1596 * the parent route. The exception to this are IPv4
1597 * link local addresses.
1599 if (!IN_LINKLOCAL(ntohl(SIN(dst
)->sin_addr
.s_addr
))) {
1600 if (flags
& RTF_IFSCOPE
) {
1601 ifscope
= sa_get_ifscope(rt_key(rt
));
1603 ifscope
= rt
->rt_ifp
->if_index
;
1604 flags
|= RTF_IFSCOPE
;
1607 ifscope
= IFSCOPE_NONE
;
1608 flags
&= ~RTF_IFSCOPE
;
1611 /* Embed or clear ifscope into/from the key (local copy) */
1612 dst
= sin_copy(SIN(dst
), &sin
, ifscope
);
1614 /* Embed or clear ifscope into/from netmask (local copy) */
1615 if (netmask
!= NULL
)
1616 netmask
= mask_copy(netmask
, &mask
, ifscope
);
1621 if ((flags
& RTF_GATEWAY
) && !gateway
)
1622 panic("rtrequest: RTF_GATEWAY but no gateway");
1624 if (flags
& RTF_IFSCOPE
) {
1625 ifa
= ifa_ifwithroute_scoped_locked(flags
, dst0
,
1628 ifa
= ifa_ifwithroute_locked(flags
, dst0
, gateway
);
1631 senderr(ENETUNREACH
);
1633 if ((rt
= rte_alloc()) == NULL
)
1635 Bzero(rt
, sizeof(*rt
));
1638 rt
->rt_flags
= RTF_UP
| flags
;
1641 * Add the gateway. Possibly re-malloc-ing the storage for it
1642 * also add the rt_gwroute if possible.
1644 if ((error
= rt_setgate(rt
, dst
, gateway
)) != 0) {
1646 rte_lock_destroy(rt
);
1652 * point to the (possibly newly malloc'd) dest address.
1657 * make sure it contains the value we want (masked if needed).
1660 rt_maskedcopy(dst
, ndst
, netmask
);
1662 Bcopy(dst
, ndst
, dst
->sa_len
);
1665 * Note that we now have a reference to the ifa.
1666 * This moved from below so that rnh->rnh_addaddr() can
1667 * examine the ifa and ifa->ifa_ifp if it so desires.
1670 rt
->rt_ifp
= rt
->rt_ifa
->ifa_ifp
;
1672 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1674 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
, (caddr_t
)netmask
,
1677 struct rtentry
*rt2
;
1679 * Uh-oh, we already have one of these in the tree.
1680 * We do a special hack: if the route that's already
1681 * there was generated by the protocol-cloning
1682 * mechanism, then we just blow it away and retry
1683 * the insertion of the new one.
1685 if (flags
& RTF_IFSCOPE
) {
1686 rt2
= rtalloc1_scoped_locked(dst0
, 0,
1687 RTF_CLONING
| RTF_PRCLONING
, ifscope
);
1689 rt2
= rtalloc1_locked(dst
, 0,
1690 RTF_CLONING
| RTF_PRCLONING
);
1692 if (rt2
&& rt2
->rt_parent
) {
1694 * rnh_lock is held here, so rt_key and
1695 * rt_gateway of rt2 will not change.
1697 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt2
),
1698 rt2
->rt_gateway
, rt_mask(rt2
),
1701 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
,
1705 /* undo the extra ref we got */
1711 * If it still failed to go into the tree,
1712 * then un-make it (this should be a function)
1715 if (rt
->rt_gwroute
) {
1716 rtfree_locked(rt
->rt_gwroute
);
1717 rt
->rt_gwroute
= NULL
;
1720 ifafree(rt
->rt_ifa
);
1725 rte_lock_destroy(rt
);
1733 * If we got here from RESOLVE, then we are cloning so clone
1734 * the rest, and note that we are a clone (and increment the
1735 * parent's references). rnh_lock is still held, which prevents
1736 * a lookup from returning the newly-created route. Hence
1737 * holding and releasing the parent's rt_lock while still
1738 * holding the route's rt_lock is safe since the new route
1739 * is not yet externally visible.
1741 if (req
== RTM_RESOLVE
) {
1742 RT_LOCK_SPIN(*ret_nrt
);
1743 rt
->rt_rmx
= (*ret_nrt
)->rt_rmx
; /* copy metrics */
1744 if ((*ret_nrt
)->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) {
1745 rt
->rt_parent
= (*ret_nrt
);
1746 RT_ADDREF_LOCKED(*ret_nrt
);
1748 RT_UNLOCK(*ret_nrt
);
1750 #if IFNET_ROUTE_REFCNT
1752 * Enable interface reference counting for unicast
1753 * cloned routes and bump up the reference count.
1755 if (rt
->rt_parent
!= NULL
&&
1756 !(rt
->rt_flags
& (RTF_BROADCAST
| RTF_MULTICAST
))) {
1757 rt
->rt_if_ref_fn
= rte_if_ref
;
1758 rt
->rt_if_ref_fn(rt
->rt_ifp
, 1);
1759 rt
->rt_flags
|= RTF_IFREF
;
1761 #endif /* IFNET_ROUTE_REFCNT */
1765 * if this protocol has something to add to this then
1766 * allow it to do that as well.
1768 if (ifa
->ifa_rtrequest
)
1769 ifa
->ifa_rtrequest(req
, rt
, SA(ret_nrt
? *ret_nrt
: 0));
1774 * If this is the (non-scoped) default route, record
1775 * the interface index used for the primary ifscope.
1777 if (rt_inet_default(rt
, rt_key(rt
)))
1778 set_primary_ifscope(rt
->rt_ifp
->if_index
);
1781 * actually return a resultant rtentry and
1782 * give the caller a single reference.
1786 RT_ADDREF_LOCKED(rt
);
1790 * We repeat the same procedure from rt_setgate() here because
1791 * it doesn't fire when we call it there because the node
1792 * hasn't been added to the tree yet.
1794 if (req
== RTM_ADD
&&
1795 !(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != 0) {
1796 struct rtfc_arg arg
;
1800 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
1801 rt_fixchange
, &arg
);
1816 struct sockaddr
*dst
,
1817 struct sockaddr
*gateway
,
1818 struct sockaddr
*netmask
,
1820 struct rtentry
**ret_nrt
)
1823 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1824 lck_mtx_lock(rnh_lock
);
1825 error
= rtrequest_locked(req
, dst
, gateway
, netmask
, flags
, ret_nrt
);
1826 lck_mtx_unlock(rnh_lock
);
1830 * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
1831 * (i.e., the routes related to it by the operation of cloning). This
1832 * routine is iterated over all potential former-child-routes by way of
1833 * rnh->rnh_walktree_from() above, and those that actually are children of
1834 * the late parent (passed in as VP here) are themselves deleted.
1837 rt_fixdelete(struct radix_node
*rn
, void *vp
)
1839 struct rtentry
*rt
= (struct rtentry
*)rn
;
1840 struct rtentry
*rt0
= vp
;
1842 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1845 if (rt
->rt_parent
== rt0
&&
1846 !(rt
->rt_flags
& (RTF_PINNED
| RTF_CLONING
| RTF_PRCLONING
))) {
1848 * Safe to drop rt_lock and use rt_key, since holding
1849 * rnh_lock here prevents another thread from calling
1850 * rt_setgate() on this route.
1853 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
1854 rt_mask(rt
), rt
->rt_flags
, NULL
));
1861 * This routine is called from rt_setgate() to do the analogous thing for
1862 * adds and changes. There is the added complication in this case of a
1863 * middle insert; i.e., insertion of a new network route between an older
1864 * network route and (cloned) host routes. For this reason, a simple check
1865 * of rt->rt_parent is insufficient; each candidate route must be tested
1866 * against the (mask, value) of the new route (passed as before in vp)
1867 * to see if the new route matches it.
1869 * XXX - it may be possible to do fixdelete() for changes and reserve this
1870 * routine just for adds. I'm not sure why I thought it was necessary to do
1874 rt_fixchange(struct radix_node
*rn
, void *vp
)
1876 struct rtentry
*rt
= (struct rtentry
*)rn
;
1877 struct rtfc_arg
*ap
= vp
;
1878 struct rtentry
*rt0
= ap
->rt0
;
1879 struct radix_node_head
*rnh
= ap
->rnh
;
1880 u_char
*xk1
, *xm1
, *xk2
, *xmp
;
1883 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1887 if (!rt
->rt_parent
||
1888 (rt
->rt_flags
& (RTF_PINNED
| RTF_CLONING
| RTF_PRCLONING
))) {
1893 if (rt
->rt_parent
== rt0
)
1897 * There probably is a function somewhere which does this...
1898 * if not, there should be.
1900 len
= imin(rt_key(rt0
)->sa_len
, rt_key(rt
)->sa_len
);
1902 xk1
= (u_char
*)rt_key(rt0
);
1903 xm1
= (u_char
*)rt_mask(rt0
);
1904 xk2
= (u_char
*)rt_key(rt
);
1907 * Avoid applying a less specific route; do this only if the parent
1908 * route (rt->rt_parent) is a network route, since otherwise its mask
1909 * will be NULL if it is a cloning host route.
1911 if ((xmp
= (u_char
*)rt_mask(rt
->rt_parent
)) != NULL
) {
1912 int mlen
= rt_mask(rt
->rt_parent
)->sa_len
;
1913 if (mlen
> rt_mask(rt0
)->sa_len
) {
1918 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< mlen
; i
++) {
1919 if ((xmp
[i
] & ~(xmp
[i
] ^ xm1
[i
])) != xmp
[i
]) {
1926 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< len
; i
++) {
1927 if ((xk2
[i
] & xm1
[i
]) != xk1
[i
]) {
1934 * OK, this node is a clone, and matches the node currently being
1935 * changed/added under the node's mask. So, get rid of it.
1939 * Safe to drop rt_lock and use rt_key, since holding rnh_lock here
1940 * prevents another thread from calling rt_setgate() on this route.
1943 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
1944 rt_mask(rt
), rt
->rt_flags
, NULL
));
1948 * Round up sockaddr len to multiples of 32-bytes. This will reduce
1949 * or even eliminate the need to re-allocate the chunk of memory used
1950 * for rt_key and rt_gateway in the event the gateway portion changes.
1951 * Certain code paths (e.g. IPSec) are notorious for caching the address
1952 * of rt_gateway; this rounding-up would help ensure that the gateway
1953 * portion never gets deallocated (though it may change contents) and
1954 * thus greatly simplifies things.
1956 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
1959 * Sets the gateway and/or gateway route portion of a route; may be
1960 * called on an existing route to modify the gateway portion. Both
1961 * rt_key and rt_gateway are allocated out of the same memory chunk.
1962 * Route entry lock must be held by caller; this routine will return
1963 * with the lock held.
1966 rt_setgate(struct rtentry
*rt
, struct sockaddr
*dst
, struct sockaddr
*gate
)
1968 int dlen
= SA_SIZE(dst
->sa_len
), glen
= SA_SIZE(gate
->sa_len
);
1969 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
1971 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1972 RT_LOCK_ASSERT_HELD(rt
);
1975 * If this is for a route that is on its way of being removed,
1976 * or is temporarily frozen, reject the modification request.
1978 if (rt
->rt_flags
& RTF_CONDEMNED
)
1981 /* Add an extra ref for ourselves */
1982 RT_ADDREF_LOCKED(rt
);
1985 * A host route with the destination equal to the gateway
1986 * will interfere with keeping LLINFO in the routing
1987 * table, so disallow it.
1989 if (((rt
->rt_flags
& (RTF_HOST
|RTF_GATEWAY
|RTF_LLINFO
)) ==
1990 (RTF_HOST
|RTF_GATEWAY
)) && (dst
->sa_len
== gate
->sa_len
) &&
1991 (bcmp(dst
, gate
, dst
->sa_len
) == 0)) {
1993 * The route might already exist if this is an RTM_CHANGE
1994 * or a routing redirect, so try to delete it.
1996 if (rt_key(rt
) != NULL
) {
1998 * Safe to drop rt_lock and use rt_key, rt_gateway,
1999 * since holding rnh_lock here prevents another thread
2000 * from calling rt_setgate() on this route.
2003 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt
),
2004 rt
->rt_gateway
, rt_mask(rt
), rt
->rt_flags
, NULL
);
2007 /* Release extra ref */
2008 RT_REMREF_LOCKED(rt
);
2009 return (EADDRNOTAVAIL
);
2013 * The destination is not directly reachable. Get a route
2014 * to the next-hop gateway and store it in rt_gwroute.
2016 if (rt
->rt_flags
& RTF_GATEWAY
) {
2017 struct rtentry
*gwrt
;
2018 unsigned int ifscope
;
2020 ifscope
= (dst
->sa_family
== AF_INET
) ?
2021 sa_get_ifscope(dst
) : IFSCOPE_NONE
;
2024 gwrt
= rtalloc1_scoped_locked(gate
, 1, RTF_PRCLONING
, ifscope
);
2026 RT_LOCK_ASSERT_NOTHELD(gwrt
);
2030 * Cloning loop avoidance:
2032 * In the presence of protocol-cloning and bad configuration,
2033 * it is possible to get stuck in bottomless mutual recursion
2034 * (rtrequest rt_setgate rtalloc1). We avoid this by not
2035 * allowing protocol-cloning to operate for gateways (which
2036 * is probably the correct choice anyway), and avoid the
2037 * resulting reference loops by disallowing any route to run
2038 * through itself as a gateway. This is obviously mandatory
2039 * when we get rt->rt_output(). It implies that a route to
2040 * the gateway must already be present in the system in order
2041 * for the gateway to be referred to by another route.
2044 RT_REMREF_LOCKED(gwrt
);
2045 /* Release extra ref */
2046 RT_REMREF_LOCKED(rt
);
2047 return (EADDRINUSE
); /* failure */
2051 * If scoped, the gateway route must use the same interface;
2052 * we're holding rnh_lock now, so rt_gateway and rt_ifp of gwrt
2053 * should not change and are freely accessible.
2055 if (ifscope
!= IFSCOPE_NONE
&& (rt
->rt_flags
& RTF_IFSCOPE
) &&
2056 gwrt
!= NULL
&& gwrt
->rt_ifp
!= NULL
&&
2057 gwrt
->rt_ifp
->if_index
!= ifscope
) {
2058 rtfree_locked(gwrt
); /* rt != gwrt, no deadlock */
2059 /* Release extra ref */
2060 RT_REMREF_LOCKED(rt
);
2061 return ((rt
->rt_flags
& RTF_HOST
) ?
2062 EHOSTUNREACH
: ENETUNREACH
);
2065 /* Check again since we dropped the lock above */
2066 if (rt
->rt_flags
& RTF_CONDEMNED
) {
2068 rtfree_locked(gwrt
);
2069 /* Release extra ref */
2070 RT_REMREF_LOCKED(rt
);
2074 if (rt
->rt_gwroute
!= NULL
)
2075 rtfree_locked(rt
->rt_gwroute
);
2076 rt
->rt_gwroute
= gwrt
;
2079 * In case the (non-scoped) default route gets modified via
2080 * an ICMP redirect, record the interface index used for the
2081 * primary ifscope. Also done in rt_setif() to take care
2082 * of the non-redirect cases.
2084 if (rt_inet_default(rt
, dst
) && rt
->rt_ifp
!= NULL
)
2085 set_primary_ifscope(rt
->rt_ifp
->if_index
);
2088 * Tell the kernel debugger about the new default gateway
2089 * if the gateway route uses the primary interface, or
2090 * if we are in a transient state before the non-scoped
2091 * default gateway is installed (similar to how the system
2092 * was behaving in the past). In future, it would be good
2093 * to do all this only when KDP is enabled.
2095 if ((dst
->sa_family
== AF_INET
) &&
2096 gwrt
!= NULL
&& gwrt
->rt_gateway
->sa_family
== AF_LINK
&&
2097 (gwrt
->rt_ifp
->if_index
== get_primary_ifscope() ||
2098 get_primary_ifscope() == IFSCOPE_NONE
))
2099 kdp_set_gateway_mac(SDL(gwrt
->rt_gateway
)->sdl_data
);
2103 * Prepare to store the gateway in rt_gateway. Both dst and gateway
2104 * are stored one after the other in the same malloc'd chunk. If we
2105 * have room, reuse the old buffer since rt_gateway already points
2106 * to the right place. Otherwise, malloc a new block and update
2107 * the 'dst' address and point rt_gateway to the right place.
2109 if (rt
->rt_gateway
== NULL
|| glen
> SA_SIZE(rt
->rt_gateway
->sa_len
)) {
2112 /* The underlying allocation is done with M_WAITOK set */
2113 R_Malloc(new, caddr_t
, dlen
+ glen
);
2115 if (rt
->rt_gwroute
!= NULL
)
2116 rtfree_locked(rt
->rt_gwroute
);
2117 rt
->rt_gwroute
= NULL
;
2118 /* Release extra ref */
2119 RT_REMREF_LOCKED(rt
);
2124 * Copy from 'dst' and not rt_key(rt) because we can get
2125 * here to initialize a newly allocated route entry, in
2126 * which case rt_key(rt) is NULL (and so does rt_gateway).
2128 bzero(new, dlen
+ glen
);
2129 Bcopy(dst
, new, dst
->sa_len
);
2130 R_Free(rt_key(rt
)); /* free old block; NULL is okay */
2131 rt
->rt_nodes
->rn_key
= new;
2132 rt
->rt_gateway
= (struct sockaddr
*)(new + dlen
);
2136 * Copy the new gateway value into the memory chunk.
2138 Bcopy(gate
, rt
->rt_gateway
, gate
->sa_len
);
2141 * For consistency between rt_gateway and rt_key(gwrt).
2143 if ((rt
->rt_flags
& RTF_GATEWAY
) && rt
->rt_gwroute
!= NULL
&&
2144 (rt
->rt_gwroute
->rt_flags
& RTF_IFSCOPE
) &&
2145 rt
->rt_gateway
->sa_family
== AF_INET
&&
2146 rt_key(rt
->rt_gwroute
)->sa_family
== AF_INET
) {
2147 sa_set_ifscope(rt
->rt_gateway
,
2148 sa_get_ifscope(rt_key(rt
->rt_gwroute
)));
2152 * This isn't going to do anything useful for host routes, so
2153 * don't bother. Also make sure we have a reasonable mask
2154 * (we don't yet have one during adds).
2156 if (!(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != 0) {
2157 struct rtfc_arg arg
;
2161 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
2162 rt_fixchange
, &arg
);
2166 /* Release extra ref */
2167 RT_REMREF_LOCKED(rt
);
2174 rt_maskedcopy(struct sockaddr
*src
, struct sockaddr
*dst
,
2175 struct sockaddr
*netmask
)
2177 u_char
*cp1
= (u_char
*)src
;
2178 u_char
*cp2
= (u_char
*)dst
;
2179 u_char
*cp3
= (u_char
*)netmask
;
2180 u_char
*cplim
= cp2
+ *cp3
;
2181 u_char
*cplim2
= cp2
+ *cp1
;
2183 *cp2
++ = *cp1
++; *cp2
++ = *cp1
++; /* copies sa_len & sa_family */
2188 *cp2
++ = *cp1
++ & *cp3
++;
2190 bzero((caddr_t
)cp2
, (unsigned)(cplim2
- cp2
));
2194 * Lookup an AF_INET scoped or non-scoped route depending on the ifscope
2195 * value passed in by the caller (IFSCOPE_NONE implies non-scoped).
2197 static struct radix_node
*
2198 node_lookup(struct sockaddr
*dst
, struct sockaddr
*netmask
,
2199 unsigned int ifscope
)
2201 struct radix_node_head
*rnh
= rt_tables
[AF_INET
];
2202 struct radix_node
*rn
;
2203 struct sockaddr_in sin
, mask
;
2204 struct matchleaf_arg ma
= { ifscope
};
2205 rn_matchf_t
*f
= rn_match_ifscope
;
2208 if (dst
->sa_family
!= AF_INET
)
2212 * Embed ifscope into the search key; for a non-scoped
2213 * search this will clear out any embedded scope value.
2215 dst
= sin_copy(SIN(dst
), &sin
, ifscope
);
2217 /* Embed (or clear) ifscope into netmask */
2218 if (netmask
!= NULL
)
2219 netmask
= mask_copy(netmask
, &mask
, ifscope
);
2221 if (ifscope
== IFSCOPE_NONE
)
2224 rn
= rnh
->rnh_lookup_args(dst
, netmask
, rnh
, f
, w
);
2225 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2232 * Lookup the AF_INET non-scoped default route.
2234 static struct radix_node
*
2235 node_lookup_default(void)
2237 struct radix_node_head
*rnh
= rt_tables
[AF_INET
];
2238 return (rnh
->rnh_lookup(&sin_def
, NULL
, rnh
));
2242 * Common routine to lookup/match a route. It invokes the lookup/matchaddr
2243 * callback which could be address family-specific. The main difference
2244 * between the two (at least for AF_INET/AF_INET6) is that a lookup does
2245 * not alter the expiring state of a route, whereas a match would unexpire
2246 * or revalidate the route.
2248 * The optional scope or interface index property of a route allows for a
2249 * per-interface route instance. This permits multiple route entries having
2250 * the same destination (but not necessarily the same gateway) to exist in
2251 * the routing table; each of these entries is specific to the corresponding
2252 * interface. This is made possible by embedding the scope value into the
2253 * radix key, thus making each route entry unique. These scoped entries
2254 * exist along with the regular, non-scoped entries in the same radix tree
2255 * for a given address family (currently AF_INET only); the scope logically
2256 * partitions it into multiple per-interface sub-trees.
2258 * When a scoped route lookup is performed, the routing table is searched for
2259 * the best match that would result in a route using the same interface as the
2260 * one associated with the scope (the exception to this are routes that point
2261 * to the loopback interface). The search rule follows the longest matching
2262 * prefix with the additional interface constraint.
2265 rt_lookup(boolean_t lookup_only
, struct sockaddr
*dst
, struct sockaddr
*netmask
,
2266 struct radix_node_head
*rnh
, unsigned int ifscope
)
2268 struct radix_node
*rn0
, *rn
;
2269 boolean_t dontcare
= (ifscope
== IFSCOPE_NONE
);
2271 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2277 * Non-scoped route lookup.
2279 if (!ip_doscopedroute
|| dst
->sa_family
!= AF_INET
) {
2281 rn
= rnh
->rnh_lookup(dst
, netmask
, rnh
);
2283 rn
= rnh
->rnh_matchaddr(dst
, rnh
);
2286 * Don't return a root node; also, rnh_matchaddr callback
2287 * would have done the necessary work to clear RTPRF_OURS
2288 * for certain protocol families.
2290 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2293 RT_LOCK_SPIN(RT(rn
));
2294 if (!(RT(rn
)->rt_flags
& RTF_CONDEMNED
)) {
2295 RT_ADDREF_LOCKED(RT(rn
));
2306 * Scoped route lookup:
2308 * We first perform a non-scoped lookup for the original result.
2309 * Afterwards, depending on whether or not the caller has specified
2310 * a scope, we perform a more specific scoped search and fallback
2311 * to this original result upon failure.
2313 rn0
= rn
= node_lookup(dst
, netmask
, IFSCOPE_NONE
);
2316 * If the caller did not specify a scope, use the primary scope
2317 * derived from the system's non-scoped default route. If, for
2318 * any reason, there is no primary interface, return what we have.
2320 if (dontcare
&& (ifscope
= get_primary_ifscope()) == IFSCOPE_NONE
)
2324 * Keep the original result if either of the following is true:
2326 * 1) The interface portion of the route has the same interface
2327 * index as the scope value and it is marked with RTF_IFSCOPE.
2328 * 2) The route uses the loopback interface, in which case the
2329 * destination (host/net) is local/loopback.
2331 * Otherwise, do a more specified search using the scope;
2332 * we're holding rnh_lock now, so rt_ifp should not change.
2335 struct rtentry
*rt
= RT(rn
);
2336 if (rt
->rt_ifp
!= lo_ifp
) {
2337 if (rt
->rt_ifp
->if_index
!= ifscope
) {
2339 * Wrong interface; keep the original result
2340 * only if the caller did not specify a scope,
2341 * and do a more specific scoped search using
2342 * the scope of the found route. Otherwise,
2343 * start again from scratch.
2347 ifscope
= rt
->rt_ifp
->if_index
;
2350 } else if (!(rt
->rt_flags
& RTF_IFSCOPE
)) {
2352 * Right interface, except that this route
2353 * isn't marked with RTF_IFSCOPE. Do a more
2354 * specific scoped search. Keep the original
2355 * result and return it it in case the scoped
2364 * Scoped search. Find the most specific entry having the same
2365 * interface scope as the one requested. The following will result
2366 * in searching for the longest prefix scoped match.
2369 rn
= node_lookup(dst
, netmask
, ifscope
);
2372 * Use the original result if either of the following is true:
2374 * 1) The scoped search did not yield any result.
2375 * 2) The result from the scoped search is a scoped default route,
2376 * and the original (non-scoped) result is not a default route,
2377 * i.e. the original result is a more specific host/net route.
2378 * 3) The scoped search yielded a net route but the original
2379 * result is a host route, i.e. the original result is treated
2380 * as a more specific route.
2382 if (rn
== NULL
|| (rn0
!= NULL
&&
2383 ((INET_DEFAULT(rt_key(RT(rn
))) && !INET_DEFAULT(rt_key(RT(rn0
)))) ||
2384 (!RT_HOST(rn
) && RT_HOST(rn0
)))))
2388 * If we still don't have a route, use the non-scoped default
2389 * route as long as the interface portion satistifes the scope.
2391 if (rn
== NULL
&& (rn
= node_lookup_default()) != NULL
&&
2392 RT(rn
)->rt_ifp
->if_index
!= ifscope
)
2398 * Manually clear RTPRF_OURS using in_validate() and
2399 * bump up the reference count after, and not before;
2400 * we only get here for AF_INET. node_lookup() has
2401 * done the check against RNF_ROOT, so we can be sure
2402 * that we're not returning a root node here.
2404 RT_LOCK_SPIN(RT(rn
));
2405 if (!(RT(rn
)->rt_flags
& RTF_CONDEMNED
)) {
2407 (void) in_validate(rn
);
2408 RT_ADDREF_LOCKED(RT(rn
));
2420 * Set up a routing table entry, normally
2424 rtinit(struct ifaddr
*ifa
, int cmd
, int flags
)
2427 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2428 lck_mtx_lock(rnh_lock
);
2429 error
= rtinit_locked(ifa
, cmd
, flags
);
2430 lck_mtx_unlock(rnh_lock
);
2435 rtinit_locked(struct ifaddr
*ifa
, int cmd
, int flags
)
2438 struct sockaddr
*dst
;
2439 struct sockaddr
*deldst
;
2441 struct rtentry
*nrt
= 0;
2444 dst
= flags
& RTF_HOST
? ifa
->ifa_dstaddr
: ifa
->ifa_addr
;
2446 * If it's a delete, check that if it exists, it's on the correct
2447 * interface or we might scrub a route to another ifa which would
2448 * be confusing at best and possibly worse.
2450 if (cmd
== RTM_DELETE
) {
2452 * It's a delete, so it should already exist..
2453 * If it's a net, mask off the host bits
2454 * (Assuming we have a mask)
2456 if ((flags
& RTF_HOST
) == 0 && ifa
->ifa_netmask
) {
2457 m
= m_get(M_DONTWAIT
, MT_SONAME
);
2461 deldst
= mtod(m
, struct sockaddr
*);
2462 rt_maskedcopy(dst
, deldst
, ifa
->ifa_netmask
);
2466 * Get an rtentry that is in the routing tree and
2467 * contains the correct info. (if this fails, can't get there).
2468 * We set "report" to FALSE so that if it doesn't exist,
2469 * it doesn't report an error or clone a route, etc. etc.
2471 rt
= rtalloc1_locked(dst
, 0, 0);
2474 * Ok so we found the rtentry. it has an extra reference
2475 * for us at this stage. we won't need that so
2479 if (rt
->rt_ifa
!= ifa
) {
2480 RT_REMREF_LOCKED(rt
);
2483 * If the interface in the rtentry doesn't match
2484 * the interface we are using, then we don't
2485 * want to delete it, so return an error.
2486 * This seems to be the only point of
2487 * this whole RTM_DELETE clause.
2491 return (flags
& RTF_HOST
? EHOSTUNREACH
2494 RT_REMREF_LOCKED(rt
);
2502 * One would think that as we are deleting, and we know
2503 * it doesn't exist, we could just return at this point
2504 * with an "ELSE" clause, but apparently not..
2506 lck_mtx_unlock(rnh_lock
);
2507 return (flags
& RTF_HOST
? EHOSTUNREACH
2513 * Do the actual request
2515 error
= rtrequest_locked(cmd
, dst
, ifa
->ifa_addr
, ifa
->ifa_netmask
,
2516 flags
| ifa
->ifa_flags
, &nrt
);
2520 * If we are deleting, and we found an entry, then
2521 * it's been removed from the tree.. now throw it away.
2523 if (cmd
== RTM_DELETE
&& error
== 0 && (rt
= nrt
)) {
2525 * notify any listening routing agents of the change
2528 rt_newaddrmsg(cmd
, ifa
, error
, nrt
);
2530 routegenid_update();
2536 * We are adding, and we have a returned routing entry.
2537 * We need to sanity check the result.
2539 if (cmd
== RTM_ADD
&& error
== 0 && (rt
= nrt
)) {
2542 * If it came back with an unexpected interface, then it must
2543 * have already existed or something. (XXX)
2545 if (rt
->rt_ifa
!= ifa
) {
2546 if (!(rt
->rt_ifa
->ifa_ifp
->if_flags
&
2547 (IFF_POINTOPOINT
|IFF_LOOPBACK
)))
2548 printf("rtinit: wrong ifa (%p) was (%p)\n",
2551 * Ask that the protocol in question
2552 * remove anything it has associated with
2553 * this route and ifaddr.
2555 if (rt
->rt_ifa
->ifa_rtrequest
)
2556 rt
->rt_ifa
->ifa_rtrequest(RTM_DELETE
, rt
, SA(0));
2558 * Set the route's ifa.
2561 #if IFNET_ROUTE_REFCNT
2563 * Adjust route ref count for the interfaces.
2565 if (rt
->rt_if_ref_fn
!= NULL
&&
2566 rt
->rt_ifp
!= ifa
->ifa_ifp
) {
2567 rt
->rt_if_ref_fn(ifa
->ifa_ifp
, 1);
2568 rt
->rt_if_ref_fn(rt
->rt_ifp
, -1);
2570 #endif /* IFNET_ROUTE_REFCNT */
2572 * And substitute in references to the ifaddr
2575 rt
->rt_ifp
= ifa
->ifa_ifp
;
2576 rt
->rt_rmx
.rmx_mtu
= ifa
->ifa_ifp
->if_mtu
; /*XXX*/
2578 * Now ask the protocol to check if it needs
2579 * any special processing in its new form.
2581 if (ifa
->ifa_rtrequest
)
2582 ifa
->ifa_rtrequest(RTM_ADD
, rt
, SA(0));
2585 * notify any listenning routing agents of the change
2587 rt_newaddrmsg(cmd
, ifa
, error
, nrt
);
2589 routegenid_update();
2591 * We just wanted to add it; we don't actually need a
2592 * reference. This will result in a route that's added
2593 * to the routing table without a reference count. The
2594 * RTM_DELETE code will do the necessary step to adjust
2595 * the reference count at deletion time.
2597 RT_REMREF_LOCKED(rt
);
2604 rt_expiry(struct rtentry
*rt
, u_int64_t base
, u_int32_t delta
)
2606 #if IFNET_ROUTE_REFCNT
2610 * If the interface of the route doesn't demand aggressive draining,
2611 * return the expiration time based on the caller-supplied delta.
2612 * Otherwise use the more aggressive route expiration delta (or
2613 * the caller-supplied delta, whichever is less.)
2615 if (rt
->rt_ifp
== NULL
|| rt
->rt_ifp
->if_want_aggressive_drain
== 0)
2616 retval
= base
+ delta
;
2618 retval
= base
+ MIN(rt_if_idle_expire_timeout
, delta
);
2623 return (base
+ delta
);
2624 #endif /* IFNET_ROUTE_REFCNT */
2628 rte_lock_init(struct rtentry
*rt
)
2630 lck_mtx_init(&rt
->rt_lock
, rte_mtx_grp
, rte_mtx_attr
);
2634 rte_lock_destroy(struct rtentry
*rt
)
2636 RT_LOCK_ASSERT_NOTHELD(rt
);
2637 lck_mtx_destroy(&rt
->rt_lock
, rte_mtx_grp
);
2641 rt_lock(struct rtentry
*rt
, boolean_t spin
)
2643 RT_LOCK_ASSERT_NOTHELD(rt
);
2645 lck_mtx_lock_spin(&rt
->rt_lock
);
2647 lck_mtx_lock(&rt
->rt_lock
);
2648 if (rte_debug
& RTD_DEBUG
)
2649 rte_lock_debug((struct rtentry_dbg
*)rt
);
2653 rt_unlock(struct rtentry
*rt
)
2655 RT_LOCK_ASSERT_HELD(rt
);
2656 if (rte_debug
& RTD_DEBUG
)
2657 rte_unlock_debug((struct rtentry_dbg
*)rt
);
2658 lck_mtx_unlock(&rt
->rt_lock
);
2663 rte_lock_debug(struct rtentry_dbg
*rte
)
2667 idx
= atomic_add_32_ov(&rte
->rtd_lock_cnt
, 1) % CTRACE_HIST_SIZE
;
2668 if (rte_debug
& RTD_TRACE
)
2669 ctrace_record(&rte
->rtd_lock
[idx
]);
2673 rte_unlock_debug(struct rtentry_dbg
*rte
)
2677 idx
= atomic_add_32_ov(&rte
->rtd_unlock_cnt
, 1) % CTRACE_HIST_SIZE
;
2678 if (rte_debug
& RTD_TRACE
)
2679 ctrace_record(&rte
->rtd_unlock
[idx
]);
2682 static struct rtentry
*
2685 if (rte_debug
& RTD_DEBUG
)
2686 return (rte_alloc_debug());
2688 return ((struct rtentry
*)zalloc(rte_zone
));
2692 rte_free(struct rtentry
*p
)
2694 if (rte_debug
& RTD_DEBUG
) {
2699 if (p
->rt_refcnt
!= 0)
2700 panic("rte_free: rte=%p refcnt=%d non-zero\n", p
, p
->rt_refcnt
);
2705 #if IFNET_ROUTE_REFCNT
2707 rte_if_ref(struct ifnet
*ifp
, int cnt
)
2709 struct kev_msg ev_msg
;
2710 struct net_event_data ev_data
;
2713 /* Force cnt to 1 increment/decrement */
2714 if (cnt
< -1 || cnt
> 1)
2715 panic("%s: invalid count argument (%d)", __func__
, cnt
);
2717 old
= atomic_add_32_ov(&ifp
->if_route_refcnt
, cnt
);
2718 if (cnt
< 0 && old
== 0)
2719 panic("%s: ifp=%p negative route refcnt!", __func__
, ifp
);
2722 * The following is done without first holding the ifnet lock,
2723 * for performance reasons. The relevant ifnet fields, with
2724 * the exception of the if_idle_flags, are never changed
2725 * during the lifetime of the ifnet. The if_idle_flags
2726 * may possibly be modified, so in the event that the value
2727 * is stale because IFRF_IDLE_NOTIFY was cleared, we'd end up
2728 * sending the event anyway. This is harmless as it is just
2729 * a notification to the monitoring agent in user space, and
2730 * it is expected to check via SIOCGIFGETRTREFCNT again anyway.
2732 if ((ifp
->if_idle_flags
& IFRF_IDLE_NOTIFY
) && cnt
< 0 && old
== 1) {
2733 bzero(&ev_msg
, sizeof (ev_msg
));
2734 bzero(&ev_data
, sizeof (ev_data
));
2736 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
2737 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
2738 ev_msg
.kev_subclass
= KEV_DL_SUBCLASS
;
2739 ev_msg
.event_code
= KEV_DL_IF_IDLE_ROUTE_REFCNT
;
2741 strlcpy(&ev_data
.if_name
[0], ifp
->if_name
, IFNAMSIZ
);
2743 ev_data
.if_family
= ifp
->if_family
;
2744 ev_data
.if_unit
= ifp
->if_unit
;
2745 ev_msg
.dv
[0].data_length
= sizeof (struct net_event_data
);
2746 ev_msg
.dv
[0].data_ptr
= &ev_data
;
2748 kev_post_msg(&ev_msg
);
2751 #endif /* IFNET_ROUTE_REFCNT */
2753 static inline struct rtentry
*
2754 rte_alloc_debug(void)
2756 struct rtentry_dbg
*rte
;
2758 rte
= ((struct rtentry_dbg
*)zalloc(rte_zone
));
2760 bzero(rte
, sizeof (*rte
));
2761 if (rte_debug
& RTD_TRACE
)
2762 ctrace_record(&rte
->rtd_alloc
);
2763 rte
->rtd_inuse
= RTD_INUSE
;
2765 return ((struct rtentry
*)rte
);
2769 rte_free_debug(struct rtentry
*p
)
2771 struct rtentry_dbg
*rte
= (struct rtentry_dbg
*)p
;
2773 if (p
->rt_refcnt
!= 0)
2774 panic("rte_free: rte=%p refcnt=%d\n", p
, p
->rt_refcnt
);
2776 if (rte
->rtd_inuse
== RTD_FREED
)
2777 panic("rte_free: double free rte=%p\n", rte
);
2778 else if (rte
->rtd_inuse
!= RTD_INUSE
)
2779 panic("rte_free: corrupted rte=%p\n", rte
);
2781 bcopy((caddr_t
)p
, (caddr_t
)&rte
->rtd_entry_saved
, sizeof (*p
));
2782 /* Preserve rt_lock to help catch use-after-free cases */
2783 bzero((caddr_t
)p
, offsetof(struct rtentry
, rt_lock
));
2785 rte
->rtd_inuse
= RTD_FREED
;
2787 if (rte_debug
& RTD_TRACE
)
2788 ctrace_record(&rte
->rtd_free
);
2790 if (!(rte_debug
& RTD_NO_FREE
))
2795 ctrace_record(ctrace_t
*tr
)
2797 tr
->th
= current_thread();
2798 bzero(tr
->pc
, sizeof (tr
->pc
));
2799 (void) OSBacktrace(tr
->pc
, CTRACE_STACK_SIZE
);