]> git.saurik.com Git - apple/xnu.git/blob - bsd/net/route.c
28f921b0dc43c876a38a3bf38910fb97a68bd138
[apple/xnu.git] / bsd / net / route.c
1 /*
2 * Copyright (c) 2000-2009 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1980, 1986, 1991, 1993
30 * The Regents of the University of California. All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
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.
47 *
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
58 * SUCH DAMAGE.
59 *
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 $
62 */
63
64 #include <sys/param.h>
65 #include <sys/sysctl.h>
66 #include <sys/systm.h>
67 #include <sys/malloc.h>
68 #include <sys/mbuf.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>
75
76 #include <net/if.h>
77 #include <net/route.h>
78
79 #include <netinet/in.h>
80 #include <netinet/in_var.h>
81 #include <netinet/ip_mroute.h>
82 #include <netinet/ip_var.h>
83
84 #include <net/if_dl.h>
85
86 #include <libkern/OSAtomic.h>
87 #include <libkern/OSDebug.h>
88
89 #include <pexpert/pexpert.h>
90
91 /*
92 * Synchronization notes:
93 *
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.
97 *
98 * The locking domains for routing are defined as follows:
99 *
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.)
105 *
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.
109 *
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.
114 *
115 * The fields of the rtentry structure are protected in the following way:
116 *
117 * rt_nodes[]
118 *
119 * - Routing table lock (rnh_lock).
120 *
121 * rt_parent, rt_mask, rt_llinfo_free
122 *
123 * - Set once during creation and never changes; no locks to read.
124 *
125 * rt_flags, rt_genmask, rt_llinfo, rt_rmx, rt_refcnt, rt_gwroute
126 *
127 * - Routing entry lock (rt_lock) for read/write access.
128 *
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.
135 *
136 * rt_key, rt_gateway, rt_ifp, rt_ifa
137 *
138 * - Always written/modified with both rnh_lock and rt_lock held.
139 *
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.
142 *
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.
150 *
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().
154 *
155 * generation_id
156 *
157 * - Assumes that 32-bit writes are atomic; no locks.
158 *
159 * rt_dlt, rt_output
160 *
161 * - Currently unused; no locks.
162 *
163 * Operations on a route entry can be described as follows:
164 *
165 * CREATE an entry with reference count set to 0 as part of RTM_ADD/RESOLVE.
166 *
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).
170 *
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.
174 *
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.
181 *
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.
187 */
188
189 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
190 #define SA(p) ((struct sockaddr *)(p))
191
192 extern void kdp_set_gateway_mac (void *gatewaymac);
193
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];
198
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;
203
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;
208
209 lck_mtx_t *route_domain_mtx; /*### global routing tables mutex for now */
210 int rttrash = 0; /* routes not in table but not freed */
211
212 unsigned int rte_debug;
213
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) */
218
219 #define RTE_NAME "rtentry" /* name for zone and rt_lock */
220
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 */
224
225 #define RTD_INUSE 0xFEEDFACE /* entry is in use */
226 #define RTD_FREED 0xDEADBEEF /* entry is freed */
227
228 /* For gdb */
229 __private_extern__ unsigned int ctrace_stack_size = CTRACE_STACK_SIZE;
230 __private_extern__ unsigned int ctrace_hist_size = CTRACE_HIST_SIZE;
231
232 /*
233 * Debug variant of rtentry structure.
234 */
235 struct rtentry_dbg {
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 */
243 /*
244 * Alloc and free callers.
245 */
246 ctrace_t rtd_alloc;
247 ctrace_t rtd_free;
248 /*
249 * Circular lists of rtref and rtunref callers.
250 */
251 ctrace_t rtd_refhold[CTRACE_HIST_SIZE];
252 ctrace_t rtd_refrele[CTRACE_HIST_SIZE];
253 /*
254 * Circular lists of locks and unlocks.
255 */
256 ctrace_t rtd_lock[CTRACE_HIST_SIZE];
257 ctrace_t rtd_unlock[CTRACE_HIST_SIZE];
258 /*
259 * Trash list linkage
260 */
261 TAILQ_ENTRY(rtentry_dbg) rtd_trash_link;
262 };
263
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))
268
269 /* List of trash route entries protected by rnh_lock */
270 static TAILQ_HEAD(, rtentry_dbg) rttrash_head;
271
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,
284 unsigned int);
285 static int rtrequest_common_locked(int, struct sockaddr *,
286 struct sockaddr *, struct sockaddr *, int, struct rtentry **,
287 unsigned int);
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 *,
291 unsigned int);
292 static struct sockaddr *mask_copy(struct sockaddr *, struct sockaddr_in *,
293 unsigned int);
294 static struct sockaddr *sa_trim(struct sockaddr *, int);
295 static struct radix_node *node_lookup(struct sockaddr *, struct sockaddr *,
296 unsigned int);
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 */
307
308 uint32_t route_generation = 0;
309
310 /*
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.
315 */
316 struct sockaddr_inifscope {
317 __uint8_t sin_len;
318 sa_family_t sin_family;
319 in_port_t sin_port;
320 struct in_addr sin_addr;
321 /*
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
325 * in sockaddr_inarp.
326 */
327 union {
328 char sin_zero[8];
329 struct {
330 __uint32_t ifscope;
331 } _in_index;
332 } un;
333 #define sin_ifscope un._in_index.ifscope
334 };
335
336 #define SIN(sa) ((struct sockaddr_in *)(size_t)(sa))
337 #define SINIFSCOPE(sa) ((struct sockaddr_inifscope *)(size_t)(sa))
338
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); \
343 }
344
345 /*
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.
348 */
349 struct matchleaf_arg {
350 unsigned int ifscope; /* interface scope */
351 };
352
353 /*
354 * For looking up the non-scoped default route (sockaddr instead
355 * of sockaddr_in for convenience).
356 */
357 static struct sockaddr sin_def = {
358 sizeof (struct sockaddr_in), AF_INET, { 0, }
359 };
360
361 /*
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.
365 */
366 static unsigned int primary_ifscope = IFSCOPE_NONE;
367
368 #define INET_DEFAULT(dst) \
369 ((dst)->sa_family == AF_INET && SIN(dst)->sin_addr.s_addr == 0)
370
371 #define RT(r) ((struct rtentry *)r)
372 #define RT_HOST(r) (RT(r)->rt_flags & RTF_HOST)
373
374 #if IFNET_ROUTE_REFCNT
375 SYSCTL_DECL(_net_idle_route);
376
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 */
382
383 /*
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.
387 */
388 boolean_t
389 rt_inet_default(struct rtentry *rt, struct sockaddr *dst)
390 {
391 return (INET_DEFAULT(dst) && !(rt->rt_flags & RTF_IFSCOPE));
392 }
393
394 /*
395 * Set the ifscope of the primary interface; caller holds rnh_lock.
396 */
397 void
398 set_primary_ifscope(unsigned int ifscope)
399 {
400 primary_ifscope = ifscope;
401 }
402
403 /*
404 * Return the ifscope of the primary interface; caller holds rnh_lock.
405 */
406 unsigned int
407 get_primary_ifscope(void)
408 {
409 return (primary_ifscope);
410 }
411
412 /*
413 * Embed ifscope into a given a sockaddr_in.
414 */
415 static inline void
416 sa_set_ifscope(struct sockaddr *sa, unsigned int ifscope)
417 {
418 /* Caller must pass in sockaddr_in */
419 ASSERT_SINIFSCOPE(sa);
420
421 SINIFSCOPE(sa)->sin_ifscope = ifscope;
422 }
423
424 /*
425 * Given a sockaddr_in, return the embedded ifscope to the caller.
426 */
427 unsigned int
428 sa_get_ifscope(struct sockaddr *sa)
429 {
430 /* Caller must pass in sockaddr_in */
431 ASSERT_SINIFSCOPE(sa);
432
433 return (SINIFSCOPE(sa)->sin_ifscope);
434 }
435
436 /*
437 * Copy a sockaddr_in src to dst and embed ifscope into dst.
438 */
439 static struct sockaddr *
440 sin_copy(struct sockaddr_in *src, struct sockaddr_in *dst, unsigned int ifscope)
441 {
442 *dst = *src;
443 sa_set_ifscope(SA(dst), ifscope);
444
445 return (SA(dst));
446 }
447
448 /*
449 * Copy a mask from src to a sockaddr_in dst and embed ifscope into dst.
450 */
451 static struct sockaddr *
452 mask_copy(struct sockaddr *src, struct sockaddr_in *dst, unsigned int ifscope)
453 {
454 /* We know dst is at least the size of sockaddr{_in} */
455 bzero(dst, sizeof (*dst));
456 rt_maskedcopy(src, SA(dst), src);
457
458 /*
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.
466 */
467 SINIFSCOPE(dst)->sin_ifscope = ifscope;
468 SINIFSCOPE(dst)->sin_len =
469 offsetof(struct sockaddr_inifscope, sin_ifscope) +
470 sizeof (SINIFSCOPE(dst)->sin_ifscope);
471
472 return (SA(dst));
473 }
474
475 /*
476 * Trim trailing zeroes on a sockaddr and update its length.
477 */
478 static struct sockaddr *
479 sa_trim(struct sockaddr *sa, int skip)
480 {
481 caddr_t cp, base = (caddr_t)sa + skip;
482
483 if (sa->sa_len <= skip)
484 return (sa);
485
486 for (cp = base + (sa->sa_len - skip); cp > base && cp[-1] == 0;)
487 cp--;
488
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__,
493 sa->sa_len, skip);
494 /* NOTREACHED */
495 } else if (sa->sa_len == skip) {
496 /* If we end up with all zeroes, then there's no mask */
497 sa->sa_len = 0;
498 }
499
500 return (sa);
501 }
502
503 /*
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.
510 */
511 struct sockaddr *
512 rtm_scrub_ifscope(int idx, struct sockaddr *hint, struct sockaddr *sa,
513 struct sockaddr_storage *ss)
514 {
515 struct sockaddr *ret = sa;
516
517 switch (idx) {
518 case RTAX_DST:
519 /*
520 * If this is for an AF_INET destination address, call
521 * sin_copy() with IFSCOPE_NONE as it does what we need.
522 */
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);
527 }
528 break;
529
530 case RTAX_NETMASK: {
531 /*
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.
545 */
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);
553 }
554 break;
555 }
556 default:
557 break;
558 }
559
560 return (ret);
561 }
562
563 /*
564 * Callback leaf-matching routine for rn_matchaddr_args used
565 * for looking up an exact match for a scoped route entry.
566 */
567 static int
568 rn_match_ifscope(struct radix_node *rn, void *arg)
569 {
570 struct rtentry *rt = (struct rtentry *)rn;
571 struct matchleaf_arg *ma = arg;
572
573 if (!(rt->rt_flags & RTF_IFSCOPE) || rt_key(rt)->sa_family != AF_INET)
574 return (0);
575
576 return (SINIFSCOPE(rt_key(rt))->sin_ifscope == ma->ifscope);
577 }
578
579 static void
580 rtable_init(void **table)
581 {
582 struct domain *dom;
583 for (dom = domains; dom; dom = dom->dom_next)
584 if (dom->dom_rtattach)
585 dom->dom_rtattach(&table[dom->dom_family],
586 dom->dom_rtoffset);
587 }
588
589 void
590 route_init(void)
591 {
592 int size;
593
594 PE_parse_boot_argn("rte_debug", &rte_debug, sizeof (rte_debug));
595 if (rte_debug != 0)
596 rte_debug |= RTD_DEBUG;
597
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");
604 return;
605 }
606
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();
610
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;
616
617 if (rte_debug & RTD_DEBUG)
618 size = sizeof (struct rtentry_dbg);
619 else
620 size = sizeof (struct rtentry);
621
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");
625
626 zone_change(rte_zone, Z_EXPAND, TRUE);
627
628 TAILQ_INIT(&rttrash_head);
629 }
630
631 /*
632 * Atomically increment route generation counter
633 */
634 void
635 routegenid_update(void)
636 {
637 (void) atomic_add_32_ov(&route_generation, 1);
638 }
639
640 /*
641 * Packet routing routines.
642 */
643 void
644 rtalloc(struct route *ro)
645 {
646 rtalloc_ign(ro, 0);
647 }
648
649 void
650 rtalloc_ign_locked(struct route *ro, uint32_t ignore)
651 {
652 return (rtalloc_ign_common_locked(ro, ignore, IFSCOPE_NONE));
653 }
654
655 void
656 rtalloc_scoped_ign_locked(struct route *ro, uint32_t ignore,
657 unsigned int ifscope)
658 {
659 return (rtalloc_ign_common_locked(ro, ignore, ifscope));
660 }
661
662 static void
663 rtalloc_ign_common_locked(struct route *ro, uint32_t ignore,
664 unsigned int ifscope)
665 {
666 struct rtentry *rt;
667
668 if ((rt = ro->ro_rt) != NULL) {
669 RT_LOCK_SPIN(rt);
670 if (rt->rt_ifp != NULL && (rt->rt_flags & RTF_UP) &&
671 rt->generation_id == route_generation) {
672 RT_UNLOCK(rt);
673 return;
674 }
675 RT_UNLOCK(rt);
676 rtfree_locked(rt);
677 ro->ro_rt = NULL;
678 }
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);
683 }
684 }
685
686 void
687 rtalloc_ign(struct route *ro, uint32_t ignore)
688 {
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);
693 }
694
695 void
696 rtalloc_scoped_ign(struct route *ro, uint32_t ignore, unsigned int ifscope)
697 {
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);
702 }
703
704 struct rtentry *
705 rtalloc1_locked(struct sockaddr *dst, int report, uint32_t ignflags)
706 {
707 return (rtalloc1_common_locked(dst, report, ignflags, IFSCOPE_NONE));
708 }
709
710 struct rtentry *
711 rtalloc1_scoped_locked(struct sockaddr *dst, int report, uint32_t ignflags,
712 unsigned int ifscope)
713 {
714 return (rtalloc1_common_locked(dst, report, ignflags, ifscope));
715 }
716
717 /*
718 * Look up the route that matches the address given
719 * Or, at least try.. Create a cloned route if needed.
720 */
721 static struct rtentry *
722 rtalloc1_common_locked(struct sockaddr *dst, int report, uint32_t ignflags,
723 unsigned int ifscope)
724 {
725 struct radix_node_head *rnh = rt_tables[dst->sa_family];
726 struct rtentry *rt, *newrt = NULL;
727 struct rt_addrinfo info;
728 uint32_t nflags;
729 int err = 0, msgtype = RTM_MISS;
730
731 if (rnh == NULL)
732 goto unreachable;
733
734 /*
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
737 */
738 rt = rt_lookup(FALSE, dst, NULL, rnh, ifscope);
739 if (rt == NULL)
740 goto unreachable;
741
742 RT_LOCK_SPIN(rt);
743 newrt = rt;
744 nflags = rt->rt_flags & ~ignflags;
745 RT_UNLOCK(rt);
746 if (report && (nflags & (RTF_CLONING | RTF_PRCLONING))) {
747 /*
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.)
751 */
752 err = rtrequest_locked(RTM_RESOLVE, dst, NULL, NULL, 0, &newrt);
753 if (err) {
754 /*
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
758 * already done.
759 */
760 newrt = rt;
761 goto miss;
762 }
763
764 /*
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.
768 */
769 rtfree_locked(rt);
770 if ((rt = newrt) && (rt->rt_flags & RTF_XRESOLVE)) {
771 /*
772 * If the new route specifies it be
773 * externally resolved, then go do that.
774 */
775 msgtype = RTM_RESOLVE;
776 goto miss;
777 }
778 }
779 goto done;
780
781 unreachable:
782 /*
783 * Either we hit the root or couldn't find any match,
784 * Which basically means "cant get there from here"
785 */
786 rtstat.rts_unreach++;
787 miss:
788 if (report) {
789 /*
790 * If required, report the failure to the supervising
791 * Authorities.
792 * For a delete, this is not an error. (report == 0)
793 */
794 bzero((caddr_t)&info, sizeof(info));
795 info.rti_info[RTAX_DST] = dst;
796 rt_missmsg(msgtype, &info, 0, err);
797 }
798 done:
799 return (newrt);
800 }
801
802 struct rtentry *
803 rtalloc1(struct sockaddr *dst, int report, uint32_t ignflags)
804 {
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);
810 return (entry);
811 }
812
813 struct rtentry *
814 rtalloc1_scoped(struct sockaddr *dst, int report, uint32_t ignflags,
815 unsigned int ifscope)
816 {
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);
822 return (entry);
823 }
824
825 /*
826 * Remove a reference count from an rtentry.
827 * If the count gets low enough, take it out of the routing table
828 */
829 void
830 rtfree_locked(struct rtentry *rt)
831 {
832 rtfree_common(rt, TRUE);
833 }
834
835 static void
836 rtfree_common(struct rtentry *rt, boolean_t locked)
837 {
838 struct radix_node_head *rnh;
839
840 /*
841 * Atomically decrement the reference count and if it reaches 0,
842 * and there is a close function defined, call the close function.
843 */
844 RT_LOCK_SPIN(rt);
845 if (rtunref(rt) > 0) {
846 RT_UNLOCK(rt);
847 return;
848 }
849
850 /*
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.
855 */
856 if (!locked) {
857 /*
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.
865 */
866 RT_ADDREF_LOCKED(rt);
867 RT_UNLOCK(rt);
868 lck_mtx_lock(rnh_lock);
869 RT_LOCK_SPIN(rt);
870 RT_REMREF_LOCKED(rt);
871 if (rt->rt_refcnt > 0) {
872 /* We've lost the race, so abort */
873 RT_UNLOCK(rt);
874 goto done;
875 }
876 }
877
878 /*
879 * We may be blocked on other lock(s) as part of freeing
880 * the entry below, so convert from spin to full mutex.
881 */
882 RT_CONVERT_LOCK(rt);
883
884 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
885
886 /* Negative refcnt must never happen */
887 if (rt->rt_refcnt != 0)
888 panic("rt %p invalid refcnt %d", rt, rt->rt_refcnt);
889
890 /*
891 * find the tree for that address family
892 * Note: in the case of igmp packets, there might not be an rnh
893 */
894 rnh = rt_tables[rt_key(rt)->sa_family];
895
896 /*
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.
903 */
904 if (rnh != NULL && rnh->rnh_close != NULL)
905 rnh->rnh_close((struct radix_node *)rt, rnh);
906
907 /*
908 * If we are no longer "up" (and ref == 0) then we can free the
909 * resources associated with the route.
910 */
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);
914 /*
915 * the rtentry must have been removed from the routing table
916 * so it is represented in rttrash; remove that now.
917 */
918 (void) OSDecrementAtomic(&rttrash);
919 if (rte_debug & RTD_DEBUG) {
920 TAILQ_REMOVE(&rttrash_head, (struct rtentry_dbg *)rt,
921 rtd_trash_link);
922 }
923
924 /*
925 * Route is no longer in the tree and refcnt is 0;
926 * we have exclusive access, so destroy it.
927 */
928 RT_UNLOCK(rt);
929
930 /*
931 * release references on items we hold them on..
932 * e.g other routes and ifaddrs.
933 */
934 if (rt->rt_parent != NULL) {
935 rtfree_locked(rt->rt_parent);
936 rt->rt_parent = NULL;
937 }
938
939 if (rt->rt_ifa != NULL) {
940 ifafree(rt->rt_ifa);
941 rt->rt_ifa = NULL;
942 }
943
944 /*
945 * Now free any attached link-layer info.
946 */
947 if (rt->rt_llinfo != NULL) {
948 if (rt->rt_llinfo_free != NULL)
949 (*rt->rt_llinfo_free)(rt->rt_llinfo);
950 else
951 R_Free(rt->rt_llinfo);
952 rt->rt_llinfo = NULL;
953 }
954
955 /*
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
958 * together.
959 */
960 R_Free(rt_key(rt));
961
962 /*
963 * and the rtentry itself of course
964 */
965 rte_lock_destroy(rt);
966 rte_free(rt);
967 } else {
968 /*
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.
972 */
973 RT_UNLOCK(rt);
974 }
975 done:
976 if (!locked)
977 lck_mtx_unlock(rnh_lock);
978 }
979
980 void
981 rtfree(struct rtentry *rt)
982 {
983 rtfree_common(rt, FALSE);
984 }
985
986 /*
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.
990 */
991 int
992 rtunref(struct rtentry *p)
993 {
994 RT_LOCK_ASSERT_HELD(p);
995
996 if (p->rt_refcnt == 0)
997 panic("%s(%p) bad refcnt\n", __func__, p);
998
999 --p->rt_refcnt;
1000
1001 if (rte_debug & RTD_DEBUG)
1002 rtunref_audit((struct rtentry_dbg *)p);
1003
1004 /* Return new value */
1005 return (p->rt_refcnt);
1006 }
1007
1008 static inline void
1009 rtunref_audit(struct rtentry_dbg *rte)
1010 {
1011 uint16_t idx;
1012
1013 if (rte->rtd_inuse != RTD_INUSE)
1014 panic("rtunref: on freed rte=%p\n", rte);
1015
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]);
1019 }
1020
1021 /*
1022 * Add a reference count from an rtentry.
1023 */
1024 void
1025 rtref(struct rtentry *p)
1026 {
1027 RT_LOCK_ASSERT_HELD(p);
1028
1029 if (++p->rt_refcnt == 0)
1030 panic("%s(%p) bad refcnt\n", __func__, p);
1031
1032 if (rte_debug & RTD_DEBUG)
1033 rtref_audit((struct rtentry_dbg *)p);
1034 }
1035
1036 static inline void
1037 rtref_audit(struct rtentry_dbg *rte)
1038 {
1039 uint16_t idx;
1040
1041 if (rte->rtd_inuse != RTD_INUSE)
1042 panic("rtref_audit: on freed rte=%p\n", rte);
1043
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]);
1047 }
1048
1049 void
1050 rtsetifa(struct rtentry *rt, struct ifaddr* ifa)
1051 {
1052 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1053
1054 RT_LOCK_ASSERT_HELD(rt);
1055
1056 if (rt->rt_ifa == ifa)
1057 return;
1058
1059 /* Release the old ifa */
1060 if (rt->rt_ifa)
1061 ifafree(rt->rt_ifa);
1062
1063 /* Set rt_ifa */
1064 rt->rt_ifa = ifa;
1065
1066 /* Take a reference to the ifa */
1067 if (rt->rt_ifa)
1068 ifaref(rt->rt_ifa);
1069 }
1070
1071 /*
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.
1076 */
1077 void
1078 rtredirect(struct ifnet *ifp, struct sockaddr *dst, struct sockaddr *gateway,
1079 struct sockaddr *netmask, int flags, struct sockaddr *src,
1080 struct rtentry **rtp)
1081 {
1082 struct rtentry *rt = NULL;
1083 int error = 0;
1084 short *stat = 0;
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;
1089
1090 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1091 lck_mtx_lock(rnh_lock);
1092
1093 /*
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.
1097 */
1098 if ((ifa = ifa_ifwithnet_scoped(gateway, ifscope)) == NULL) {
1099 error = ENETUNREACH;
1100 goto out;
1101 }
1102
1103 /* Lookup route to the destination (from the original IP header) */
1104 rt = rtalloc1_scoped_locked(dst, 0, RTF_CLONING|RTF_PRCLONING, ifscope);
1105 if (rt != NULL)
1106 RT_LOCK(rt);
1107
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);
1111
1112 /*
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.
1117 */
1118 if (!(flags & RTF_DONE) && rt != NULL &&
1119 (!equal(src, rt->rt_gateway) || !equal(rt->rt_ifa->ifa_addr,
1120 ifa->ifa_addr))) {
1121 error = EINVAL;
1122 } else {
1123 ifafree(ifa);
1124 if ((ifa = ifa_ifwithaddr(gateway))) {
1125 ifafree(ifa);
1126 ifa = NULL;
1127 error = EHOSTUNREACH;
1128 }
1129 }
1130
1131 if (ifa) {
1132 ifafree(ifa);
1133 ifa = NULL;
1134 }
1135
1136 if (error) {
1137 if (rt != NULL)
1138 RT_UNLOCK(rt);
1139 goto done;
1140 }
1141
1142 /*
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.
1147 */
1148 if ((rt == NULL) || (rt_mask(rt) != NULL && rt_mask(rt)->sa_len < 2))
1149 goto create;
1150 /*
1151 * Don't listen to the redirect if it's
1152 * for a route to an interface.
1153 */
1154 RT_LOCK_ASSERT_HELD(rt);
1155 if (rt->rt_flags & RTF_GATEWAY) {
1156 if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
1157 /*
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.
1162 */
1163 create:
1164 if (rt != NULL)
1165 RT_UNLOCK(rt);
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;
1170 } else {
1171 /*
1172 * Smash the current notion of the gateway to
1173 * this destination. Should check about netmask!!!
1174 */
1175 rt->rt_flags |= RTF_MODIFIED;
1176 flags |= RTF_MODIFIED;
1177 stat = &rtstat.rts_newgateway;
1178 /*
1179 * add the key and gateway (in one malloc'd chunk).
1180 */
1181 error = rt_setgate(rt, rt_key(rt), gateway);
1182 RT_UNLOCK(rt);
1183 }
1184 } else {
1185 RT_UNLOCK(rt);
1186 error = EHOSTUNREACH;
1187 }
1188 done:
1189 if (rt != NULL) {
1190 RT_LOCK_ASSERT_NOTHELD(rt);
1191 if (rtp && !error)
1192 *rtp = rt;
1193 else
1194 rtfree_locked(rt);
1195 }
1196 out:
1197 if (error) {
1198 rtstat.rts_badredirect++;
1199 } else {
1200 if (stat != NULL)
1201 (*stat)++;
1202 if (use_routegenid)
1203 routegenid_update();
1204 }
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);
1212 }
1213
1214 /*
1215 * Routing table ioctl interface.
1216 */
1217 int
1218 rtioctl(unsigned long req, caddr_t data, struct proc *p)
1219 {
1220 #pragma unused(p)
1221 #if INET && MROUTING
1222 return mrt_ioctl(req, data);
1223 #else
1224 #pragma unused(req)
1225 #pragma unused(data)
1226 return ENXIO;
1227 #endif
1228 }
1229
1230 struct ifaddr *
1231 ifa_ifwithroute(
1232 int flags,
1233 const struct sockaddr *dst,
1234 const struct sockaddr *gateway)
1235 {
1236 struct ifaddr *ifa;
1237
1238 lck_mtx_lock(rnh_lock);
1239 ifa = ifa_ifwithroute_locked(flags, dst, gateway);
1240 lck_mtx_unlock(rnh_lock);
1241
1242 return (ifa);
1243 }
1244
1245 struct ifaddr *
1246 ifa_ifwithroute_locked(int flags, const struct sockaddr *dst,
1247 const struct sockaddr *gateway)
1248 {
1249 return (ifa_ifwithroute_common_locked((flags & ~RTF_IFSCOPE), dst,
1250 gateway, IFSCOPE_NONE));
1251 }
1252
1253 struct ifaddr *
1254 ifa_ifwithroute_scoped_locked(int flags, const struct sockaddr *dst,
1255 const struct sockaddr *gateway, unsigned int ifscope)
1256 {
1257 if (ifscope != IFSCOPE_NONE)
1258 flags |= RTF_IFSCOPE;
1259 else
1260 flags &= ~RTF_IFSCOPE;
1261
1262 return (ifa_ifwithroute_common_locked(flags, dst, gateway, ifscope));
1263 }
1264
1265 static struct ifaddr *
1266 ifa_ifwithroute_common_locked(int flags, const struct sockaddr *dst,
1267 const struct sockaddr *gateway, unsigned int ifscope)
1268 {
1269 struct ifaddr *ifa = NULL;
1270 struct rtentry *rt = NULL;
1271 struct sockaddr_in dst_in, gw_in;
1272
1273 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1274
1275 if (ip_doscopedroute) {
1276 /*
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.
1280 */
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);
1285 }
1286
1287 if (!(flags & RTF_GATEWAY)) {
1288 /*
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.
1294 */
1295 if (flags & RTF_HOST) {
1296 ifa = ifa_ifwithdstaddr(dst);
1297 }
1298 if (ifa == NULL)
1299 ifa = ifa_ifwithaddr_scoped(gateway, ifscope);
1300 } else {
1301 /*
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.
1305 */
1306 ifa = ifa_ifwithdstaddr(gateway);
1307 }
1308 if (ifa == NULL)
1309 ifa = ifa_ifwithnet_scoped(gateway, ifscope);
1310 if (ifa == NULL) {
1311 /* Workaround to avoid gcc warning regarding const variable */
1312 rt = rtalloc1_scoped_locked((struct sockaddr *)(size_t)dst,
1313 0, 0, ifscope);
1314 if (rt != NULL) {
1315 RT_LOCK_SPIN(rt);
1316 ifa = rt->rt_ifa;
1317 if (ifa != NULL)
1318 ifaref(ifa);
1319 RT_REMREF_LOCKED(rt);
1320 RT_UNLOCK(rt);
1321 rt = NULL;
1322 }
1323 }
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) {
1329 ifafree(ifa);
1330 ifa = newifa;
1331 }
1332 }
1333 /*
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).
1340 */
1341 if ((ifa == NULL ||
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) {
1345 if (ifa != NULL)
1346 ifafree(ifa);
1347 RT_LOCK_SPIN(rt);
1348 ifa = rt->rt_ifa;
1349 if (ifa != NULL)
1350 ifaref(ifa);
1351 RT_REMREF_LOCKED(rt);
1352 RT_UNLOCK(rt);
1353 }
1354 /*
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.
1358 */
1359 if ((flags & RTF_IFSCOPE) &&
1360 ifa != NULL && ifa->ifa_ifp->if_index != ifscope) {
1361 ifafree(ifa);
1362 ifa = NULL;
1363 }
1364
1365 return (ifa);
1366 }
1367
1368 static int rt_fixdelete(struct radix_node *, void *);
1369 static int rt_fixchange(struct radix_node *, void *);
1370
1371 struct rtfc_arg {
1372 struct rtentry *rt0;
1373 struct radix_node_head *rnh;
1374 };
1375
1376 int
1377 rtrequest_locked(int req, struct sockaddr *dst, struct sockaddr *gateway,
1378 struct sockaddr *netmask, int flags, struct rtentry **ret_nrt)
1379 {
1380 return (rtrequest_common_locked(req, dst, gateway, netmask,
1381 (flags & ~RTF_IFSCOPE), ret_nrt, IFSCOPE_NONE));
1382 }
1383
1384 int
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)
1388 {
1389 if (ifscope != IFSCOPE_NONE)
1390 flags |= RTF_IFSCOPE;
1391 else
1392 flags &= ~RTF_IFSCOPE;
1393
1394 return (rtrequest_common_locked(req, dst, gateway, netmask,
1395 flags, ret_nrt, ifscope));
1396 }
1397
1398 /*
1399 * Do appropriate manipulations of a routing tree given all the bits of
1400 * info needed.
1401 *
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.
1412 */
1413 static int
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)
1417 {
1418 int error = 0;
1419 struct rtentry *rt;
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; }
1426
1427 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1428 /*
1429 * Find the correct routing tree to use for this Address Family
1430 */
1431 if ((rnh = rt_tables[dst->sa_family]) == 0)
1432 senderr(ESRCH);
1433 /*
1434 * If we are adding a host route then we don't want to put
1435 * a netmask in the tree
1436 */
1437 if (flags & RTF_HOST)
1438 netmask = 0;
1439
1440 /*
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.
1451 */
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))
1456 senderr(EINVAL);
1457
1458 if (ifscope == IFSCOPE_NONE) {
1459 flags &= ~RTF_IFSCOPE;
1460 } else {
1461 /* Embed ifscope into the key (local copy) */
1462 dst = sin_copy(SIN(dst), &sin, ifscope);
1463
1464 /* Embed ifscope into netmask (local copy) */
1465 if (netmask != NULL)
1466 netmask = mask_copy(netmask, &mask, ifscope);
1467 }
1468 }
1469
1470 switch (req) {
1471 case RTM_DELETE:
1472 /*
1473 * Remove the item from the tree and return it.
1474 * Complain if it is not there and do no more processing.
1475 */
1476 if ((rn = rnh->rnh_deladdr(dst, netmask, rnh)) == 0)
1477 senderr(ESRCH);
1478 if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1479 panic ("rtrequest delete");
1480 rt = (struct rtentry *)rn;
1481
1482 /*
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.
1490 */
1491 RT_LOCK(rt);
1492 RT_ADDREF_LOCKED(rt);
1493 rt->rt_flags &= ~RTF_UP;
1494
1495 /*
1496 * For consistency, in case the caller didn't set the flag.
1497 */
1498 rt->rt_flags |= RTF_CONDEMNED;
1499
1500 /*
1501 * Now search what's left of the subtree for any cloned
1502 * routes which might have been formed from this node.
1503 */
1504 if ((rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) &&
1505 rt_mask(rt)) {
1506 RT_UNLOCK(rt);
1507 rnh->rnh_walktree_from(rnh, dst, rt_mask(rt),
1508 rt_fixdelete, rt);
1509 RT_LOCK(rt);
1510 }
1511
1512 /*
1513 * Remove any external references we may have.
1514 * This might result in another rtentry being freed if
1515 * we held its last reference.
1516 */
1517 if (rt->rt_gwroute != NULL) {
1518 rtfree_locked(rt->rt_gwroute);
1519 rt->rt_gwroute = NULL;
1520 }
1521
1522 /*
1523 * give the protocol a chance to keep things in sync.
1524 */
1525 if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
1526 ifa->ifa_rtrequest(RTM_DELETE, rt, SA(0));
1527 ifa = NULL;
1528
1529 /*
1530 * one more rtentry floating around that is not
1531 * linked to the routing table.
1532 */
1533 (void) OSIncrementAtomic(&rttrash);
1534 if (rte_debug & RTD_DEBUG) {
1535 TAILQ_INSERT_TAIL(&rttrash_head,
1536 (struct rtentry_dbg *)rt, rtd_trash_link);
1537 }
1538
1539 /*
1540 * If this is the (non-scoped) default route, clear
1541 * the interface index used for the primary ifscope.
1542 */
1543 if (rt_inet_default(rt, rt_key(rt)))
1544 set_primary_ifscope(IFSCOPE_NONE);
1545
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;
1550 }
1551 #endif /* IFNET_ROUTE_REFCNT */
1552
1553 RT_UNLOCK(rt);
1554
1555 /*
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
1558 * doing it.
1559 */
1560 if (ret_nrt != NULL) {
1561 /* Return the route to caller with reference intact */
1562 *ret_nrt = rt;
1563 } else {
1564 /* Dereference or deallocate the route */
1565 rtfree_locked(rt);
1566 }
1567 break;
1568
1569 case RTM_RESOLVE:
1570 if (ret_nrt == 0 || (rt = *ret_nrt) == 0)
1571 senderr(EINVAL);
1572 /*
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
1580 * of rt_rmx.
1581 */
1582 ifa = rt->rt_ifa;
1583 ifaref(ifa);
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)
1589 flags |= RTF_HOST;
1590
1591 if (!ip_doscopedroute || dst->sa_family != AF_INET)
1592 goto makeroute;
1593 /*
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.
1598 */
1599 if (!IN_LINKLOCAL(ntohl(SIN(dst)->sin_addr.s_addr))) {
1600 if (flags & RTF_IFSCOPE) {
1601 ifscope = sa_get_ifscope(rt_key(rt));
1602 } else {
1603 ifscope = rt->rt_ifp->if_index;
1604 flags |= RTF_IFSCOPE;
1605 }
1606 } else {
1607 ifscope = IFSCOPE_NONE;
1608 flags &= ~RTF_IFSCOPE;
1609 }
1610
1611 /* Embed or clear ifscope into/from the key (local copy) */
1612 dst = sin_copy(SIN(dst), &sin, ifscope);
1613
1614 /* Embed or clear ifscope into/from netmask (local copy) */
1615 if (netmask != NULL)
1616 netmask = mask_copy(netmask, &mask, ifscope);
1617
1618 goto makeroute;
1619
1620 case RTM_ADD:
1621 if ((flags & RTF_GATEWAY) && !gateway)
1622 panic("rtrequest: RTF_GATEWAY but no gateway");
1623
1624 if (flags & RTF_IFSCOPE) {
1625 ifa = ifa_ifwithroute_scoped_locked(flags, dst0,
1626 gateway, ifscope);
1627 } else {
1628 ifa = ifa_ifwithroute_locked(flags, dst0, gateway);
1629 }
1630 if (ifa == NULL)
1631 senderr(ENETUNREACH);
1632 makeroute:
1633 if ((rt = rte_alloc()) == NULL)
1634 senderr(ENOBUFS);
1635 Bzero(rt, sizeof(*rt));
1636 rte_lock_init(rt);
1637 RT_LOCK(rt);
1638 rt->rt_flags = RTF_UP | flags;
1639
1640 /*
1641 * Add the gateway. Possibly re-malloc-ing the storage for it
1642 * also add the rt_gwroute if possible.
1643 */
1644 if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1645 RT_UNLOCK(rt);
1646 rte_lock_destroy(rt);
1647 rte_free(rt);
1648 senderr(error);
1649 }
1650
1651 /*
1652 * point to the (possibly newly malloc'd) dest address.
1653 */
1654 ndst = rt_key(rt);
1655
1656 /*
1657 * make sure it contains the value we want (masked if needed).
1658 */
1659 if (netmask)
1660 rt_maskedcopy(dst, ndst, netmask);
1661 else
1662 Bcopy(dst, ndst, dst->sa_len);
1663
1664 /*
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.
1668 */
1669 rtsetifa(rt, ifa);
1670 rt->rt_ifp = rt->rt_ifa->ifa_ifp;
1671
1672 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1673
1674 rn = rnh->rnh_addaddr((caddr_t)ndst, (caddr_t)netmask,
1675 rnh, rt->rt_nodes);
1676 if (rn == 0) {
1677 struct rtentry *rt2;
1678 /*
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.
1684 */
1685 if (flags & RTF_IFSCOPE) {
1686 rt2 = rtalloc1_scoped_locked(dst0, 0,
1687 RTF_CLONING | RTF_PRCLONING, ifscope);
1688 } else {
1689 rt2 = rtalloc1_locked(dst, 0,
1690 RTF_CLONING | RTF_PRCLONING);
1691 }
1692 if (rt2 && rt2->rt_parent) {
1693 /*
1694 * rnh_lock is held here, so rt_key and
1695 * rt_gateway of rt2 will not change.
1696 */
1697 (void) rtrequest_locked(RTM_DELETE, rt_key(rt2),
1698 rt2->rt_gateway, rt_mask(rt2),
1699 rt2->rt_flags, 0);
1700 rtfree_locked(rt2);
1701 rn = rnh->rnh_addaddr((caddr_t)ndst,
1702 (caddr_t)netmask,
1703 rnh, rt->rt_nodes);
1704 } else if (rt2) {
1705 /* undo the extra ref we got */
1706 rtfree_locked(rt2);
1707 }
1708 }
1709
1710 /*
1711 * If it still failed to go into the tree,
1712 * then un-make it (this should be a function)
1713 */
1714 if (rn == 0) {
1715 if (rt->rt_gwroute) {
1716 rtfree_locked(rt->rt_gwroute);
1717 rt->rt_gwroute = NULL;
1718 }
1719 if (rt->rt_ifa) {
1720 ifafree(rt->rt_ifa);
1721 rt->rt_ifa = NULL;
1722 }
1723 R_Free(rt_key(rt));
1724 RT_UNLOCK(rt);
1725 rte_lock_destroy(rt);
1726 rte_free(rt);
1727 senderr(EEXIST);
1728 }
1729
1730 rt->rt_parent = 0;
1731
1732 /*
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.
1740 */
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);
1747 }
1748 RT_UNLOCK(*ret_nrt);
1749
1750 #if IFNET_ROUTE_REFCNT
1751 /*
1752 * Enable interface reference counting for unicast
1753 * cloned routes and bump up the reference count.
1754 */
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;
1760 }
1761 #endif /* IFNET_ROUTE_REFCNT */
1762 }
1763
1764 /*
1765 * if this protocol has something to add to this then
1766 * allow it to do that as well.
1767 */
1768 if (ifa->ifa_rtrequest)
1769 ifa->ifa_rtrequest(req, rt, SA(ret_nrt ? *ret_nrt : 0));
1770 ifafree(ifa);
1771 ifa = 0;
1772
1773 /*
1774 * If this is the (non-scoped) default route, record
1775 * the interface index used for the primary ifscope.
1776 */
1777 if (rt_inet_default(rt, rt_key(rt)))
1778 set_primary_ifscope(rt->rt_ifp->if_index);
1779
1780 /*
1781 * actually return a resultant rtentry and
1782 * give the caller a single reference.
1783 */
1784 if (ret_nrt) {
1785 *ret_nrt = rt;
1786 RT_ADDREF_LOCKED(rt);
1787 }
1788
1789 /*
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.
1793 */
1794 if (req == RTM_ADD &&
1795 !(rt->rt_flags & RTF_HOST) && rt_mask(rt) != 0) {
1796 struct rtfc_arg arg;
1797 arg.rnh = rnh;
1798 arg.rt0 = rt;
1799 RT_UNLOCK(rt);
1800 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
1801 rt_fixchange, &arg);
1802 } else {
1803 RT_UNLOCK(rt);
1804 }
1805 break;
1806 }
1807 bad:
1808 if (ifa)
1809 ifafree(ifa);
1810 return (error);
1811 }
1812
1813 int
1814 rtrequest(
1815 int req,
1816 struct sockaddr *dst,
1817 struct sockaddr *gateway,
1818 struct sockaddr *netmask,
1819 int flags,
1820 struct rtentry **ret_nrt)
1821 {
1822 int error;
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);
1827 return (error);
1828 }
1829 /*
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.
1835 */
1836 static int
1837 rt_fixdelete(struct radix_node *rn, void *vp)
1838 {
1839 struct rtentry *rt = (struct rtentry *)rn;
1840 struct rtentry *rt0 = vp;
1841
1842 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1843
1844 RT_LOCK(rt);
1845 if (rt->rt_parent == rt0 &&
1846 !(rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1847 /*
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.
1851 */
1852 RT_UNLOCK(rt);
1853 return (rtrequest_locked(RTM_DELETE, rt_key(rt), NULL,
1854 rt_mask(rt), rt->rt_flags, NULL));
1855 }
1856 RT_UNLOCK(rt);
1857 return 0;
1858 }
1859
1860 /*
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.
1868 *
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
1871 * changes this way.
1872 */
1873 static int
1874 rt_fixchange(struct radix_node *rn, void *vp)
1875 {
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;
1881 int i, len;
1882
1883 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1884
1885 RT_LOCK(rt);
1886
1887 if (!rt->rt_parent ||
1888 (rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1889 RT_UNLOCK(rt);
1890 return (0);
1891 }
1892
1893 if (rt->rt_parent == rt0)
1894 goto delete_rt;
1895
1896 /*
1897 * There probably is a function somewhere which does this...
1898 * if not, there should be.
1899 */
1900 len = imin(rt_key(rt0)->sa_len, rt_key(rt)->sa_len);
1901
1902 xk1 = (u_char *)rt_key(rt0);
1903 xm1 = (u_char *)rt_mask(rt0);
1904 xk2 = (u_char *)rt_key(rt);
1905
1906 /*
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.
1910 */
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) {
1914 RT_UNLOCK(rt);
1915 return (0);
1916 }
1917
1918 for (i = rnh->rnh_treetop->rn_offset; i < mlen; i++) {
1919 if ((xmp[i] & ~(xmp[i] ^ xm1[i])) != xmp[i]) {
1920 RT_UNLOCK(rt);
1921 return (0);
1922 }
1923 }
1924 }
1925
1926 for (i = rnh->rnh_treetop->rn_offset; i < len; i++) {
1927 if ((xk2[i] & xm1[i]) != xk1[i]) {
1928 RT_UNLOCK(rt);
1929 return (0);
1930 }
1931 }
1932
1933 /*
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.
1936 */
1937 delete_rt:
1938 /*
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.
1941 */
1942 RT_UNLOCK(rt);
1943 return (rtrequest_locked(RTM_DELETE, rt_key(rt), NULL,
1944 rt_mask(rt), rt->rt_flags, NULL));
1945 }
1946
1947 /*
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.
1955 */
1956 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
1957
1958 /*
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.
1964 */
1965 int
1966 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1967 {
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];
1970
1971 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1972 RT_LOCK_ASSERT_HELD(rt);
1973
1974 /*
1975 * If this is for a route that is on its way of being removed,
1976 * or is temporarily frozen, reject the modification request.
1977 */
1978 if (rt->rt_flags & RTF_CONDEMNED)
1979 return (EBUSY);
1980
1981 /* Add an extra ref for ourselves */
1982 RT_ADDREF_LOCKED(rt);
1983
1984 /*
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.
1988 */
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)) {
1992 /*
1993 * The route might already exist if this is an RTM_CHANGE
1994 * or a routing redirect, so try to delete it.
1995 */
1996 if (rt_key(rt) != NULL) {
1997 /*
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.
2001 */
2002 RT_UNLOCK(rt);
2003 (void) rtrequest_locked(RTM_DELETE, rt_key(rt),
2004 rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
2005 RT_LOCK(rt);
2006 }
2007 /* Release extra ref */
2008 RT_REMREF_LOCKED(rt);
2009 return (EADDRNOTAVAIL);
2010 }
2011
2012 /*
2013 * The destination is not directly reachable. Get a route
2014 * to the next-hop gateway and store it in rt_gwroute.
2015 */
2016 if (rt->rt_flags & RTF_GATEWAY) {
2017 struct rtentry *gwrt;
2018 unsigned int ifscope;
2019
2020 ifscope = (dst->sa_family == AF_INET) ?
2021 sa_get_ifscope(dst) : IFSCOPE_NONE;
2022
2023 RT_UNLOCK(rt);
2024 gwrt = rtalloc1_scoped_locked(gate, 1, RTF_PRCLONING, ifscope);
2025 if (gwrt != NULL)
2026 RT_LOCK_ASSERT_NOTHELD(gwrt);
2027 RT_LOCK(rt);
2028
2029 /*
2030 * Cloning loop avoidance:
2031 *
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.
2042 */
2043 if (gwrt == rt) {
2044 RT_REMREF_LOCKED(gwrt);
2045 /* Release extra ref */
2046 RT_REMREF_LOCKED(rt);
2047 return (EADDRINUSE); /* failure */
2048 }
2049
2050 /*
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.
2054 */
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);
2063 }
2064
2065 /* Check again since we dropped the lock above */
2066 if (rt->rt_flags & RTF_CONDEMNED) {
2067 if (gwrt != NULL)
2068 rtfree_locked(gwrt);
2069 /* Release extra ref */
2070 RT_REMREF_LOCKED(rt);
2071 return (EBUSY);
2072 }
2073
2074 if (rt->rt_gwroute != NULL)
2075 rtfree_locked(rt->rt_gwroute);
2076 rt->rt_gwroute = gwrt;
2077
2078 /*
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.
2083 */
2084 if (rt_inet_default(rt, dst) && rt->rt_ifp != NULL)
2085 set_primary_ifscope(rt->rt_ifp->if_index);
2086
2087 /*
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.
2094 */
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);
2100 }
2101
2102 /*
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.
2108 */
2109 if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway->sa_len)) {
2110 caddr_t new;
2111
2112 /* The underlying allocation is done with M_WAITOK set */
2113 R_Malloc(new, caddr_t, dlen + glen);
2114 if (new == NULL) {
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);
2120 return (ENOBUFS);
2121 }
2122
2123 /*
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).
2127 */
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);
2133 }
2134
2135 /*
2136 * Copy the new gateway value into the memory chunk.
2137 */
2138 Bcopy(gate, rt->rt_gateway, gate->sa_len);
2139
2140 /*
2141 * For consistency between rt_gateway and rt_key(gwrt).
2142 */
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)));
2149 }
2150
2151 /*
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).
2155 */
2156 if (!(rt->rt_flags & RTF_HOST) && rt_mask(rt) != 0) {
2157 struct rtfc_arg arg;
2158 arg.rnh = rnh;
2159 arg.rt0 = rt;
2160 RT_UNLOCK(rt);
2161 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
2162 rt_fixchange, &arg);
2163 RT_LOCK(rt);
2164 }
2165
2166 /* Release extra ref */
2167 RT_REMREF_LOCKED(rt);
2168 return (0);
2169 }
2170
2171 #undef SA_SIZE
2172
2173 static void
2174 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst,
2175 struct sockaddr *netmask)
2176 {
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;
2182
2183 *cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
2184 cp3 += 2;
2185 if (cplim > cplim2)
2186 cplim = cplim2;
2187 while (cp2 < cplim)
2188 *cp2++ = *cp1++ & *cp3++;
2189 if (cp2 < cplim2)
2190 bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
2191 }
2192
2193 /*
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).
2196 */
2197 static struct radix_node *
2198 node_lookup(struct sockaddr *dst, struct sockaddr *netmask,
2199 unsigned int ifscope)
2200 {
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;
2206 void *w = &ma;
2207
2208 if (dst->sa_family != AF_INET)
2209 return (NULL);
2210
2211 /*
2212 * Embed ifscope into the search key; for a non-scoped
2213 * search this will clear out any embedded scope value.
2214 */
2215 dst = sin_copy(SIN(dst), &sin, ifscope);
2216
2217 /* Embed (or clear) ifscope into netmask */
2218 if (netmask != NULL)
2219 netmask = mask_copy(netmask, &mask, ifscope);
2220
2221 if (ifscope == IFSCOPE_NONE)
2222 f = w = NULL;
2223
2224 rn = rnh->rnh_lookup_args(dst, netmask, rnh, f, w);
2225 if (rn != NULL && (rn->rn_flags & RNF_ROOT))
2226 rn = NULL;
2227
2228 return (rn);
2229 }
2230
2231 /*
2232 * Lookup the AF_INET non-scoped default route.
2233 */
2234 static struct radix_node *
2235 node_lookup_default(void)
2236 {
2237 struct radix_node_head *rnh = rt_tables[AF_INET];
2238 return (rnh->rnh_lookup(&sin_def, NULL, rnh));
2239 }
2240
2241 /*
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.
2247 *
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.
2257 *
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.
2263 */
2264 struct rtentry *
2265 rt_lookup(boolean_t lookup_only, struct sockaddr *dst, struct sockaddr *netmask,
2266 struct radix_node_head *rnh, unsigned int ifscope)
2267 {
2268 struct radix_node *rn0, *rn;
2269 boolean_t dontcare = (ifscope == IFSCOPE_NONE);
2270
2271 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
2272
2273 if (!lookup_only)
2274 netmask = NULL;
2275
2276 /*
2277 * Non-scoped route lookup.
2278 */
2279 if (!ip_doscopedroute || dst->sa_family != AF_INET) {
2280 if (lookup_only)
2281 rn = rnh->rnh_lookup(dst, netmask, rnh);
2282 else
2283 rn = rnh->rnh_matchaddr(dst, rnh);
2284
2285 /*
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.
2289 */
2290 if (rn != NULL && (rn->rn_flags & RNF_ROOT))
2291 rn = NULL;
2292 if (rn != NULL) {
2293 RT_LOCK_SPIN(RT(rn));
2294 if (!(RT(rn)->rt_flags & RTF_CONDEMNED)) {
2295 RT_ADDREF_LOCKED(RT(rn));
2296 RT_UNLOCK(RT(rn));
2297 } else {
2298 RT_UNLOCK(RT(rn));
2299 rn = NULL;
2300 }
2301 }
2302 return (RT(rn));
2303 }
2304
2305 /*
2306 * Scoped route lookup:
2307 *
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.
2312 */
2313 rn0 = rn = node_lookup(dst, netmask, IFSCOPE_NONE);
2314
2315 /*
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.
2319 */
2320 if (dontcare && (ifscope = get_primary_ifscope()) == IFSCOPE_NONE)
2321 goto done;
2322
2323 /*
2324 * Keep the original result if either of the following is true:
2325 *
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.
2330 *
2331 * Otherwise, do a more specified search using the scope;
2332 * we're holding rnh_lock now, so rt_ifp should not change.
2333 */
2334 if (rn != NULL) {
2335 struct rtentry *rt = RT(rn);
2336 if (rt->rt_ifp != lo_ifp) {
2337 if (rt->rt_ifp->if_index != ifscope) {
2338 /*
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.
2344 */
2345 rn = NULL;
2346 if (dontcare)
2347 ifscope = rt->rt_ifp->if_index;
2348 else
2349 rn0 = NULL;
2350 } else if (!(rt->rt_flags & RTF_IFSCOPE)) {
2351 /*
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
2356 * search fails.
2357 */
2358 rn = NULL;
2359 }
2360 }
2361 }
2362
2363 /*
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.
2367 */
2368 if (rn == NULL)
2369 rn = node_lookup(dst, netmask, ifscope);
2370
2371 /*
2372 * Use the original result if either of the following is true:
2373 *
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.
2381 */
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)))))
2385 rn = rn0;
2386
2387 /*
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.
2390 */
2391 if (rn == NULL && (rn = node_lookup_default()) != NULL &&
2392 RT(rn)->rt_ifp->if_index != ifscope)
2393 rn = NULL;
2394
2395 done:
2396 if (rn != NULL) {
2397 /*
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.
2403 */
2404 RT_LOCK_SPIN(RT(rn));
2405 if (!(RT(rn)->rt_flags & RTF_CONDEMNED)) {
2406 if (!lookup_only)
2407 (void) in_validate(rn);
2408 RT_ADDREF_LOCKED(RT(rn));
2409 RT_UNLOCK(RT(rn));
2410 } else {
2411 RT_UNLOCK(RT(rn));
2412 rn = NULL;
2413 }
2414 }
2415
2416 return (RT(rn));
2417 }
2418
2419 /*
2420 * Set up a routing table entry, normally
2421 * for an interface.
2422 */
2423 int
2424 rtinit(struct ifaddr *ifa, int cmd, int flags)
2425 {
2426 int error;
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);
2431 return (error);
2432 }
2433
2434 int
2435 rtinit_locked(struct ifaddr *ifa, int cmd, int flags)
2436 {
2437 struct rtentry *rt;
2438 struct sockaddr *dst;
2439 struct sockaddr *deldst;
2440 struct mbuf *m = 0;
2441 struct rtentry *nrt = 0;
2442 int error;
2443
2444 dst = flags & RTF_HOST ? ifa->ifa_dstaddr : ifa->ifa_addr;
2445 /*
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.
2449 */
2450 if (cmd == RTM_DELETE) {
2451 /*
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)
2455 */
2456 if ((flags & RTF_HOST) == 0 && ifa->ifa_netmask) {
2457 m = m_get(M_DONTWAIT, MT_SONAME);
2458 if (m == NULL) {
2459 return(ENOBUFS);
2460 }
2461 deldst = mtod(m, struct sockaddr *);
2462 rt_maskedcopy(dst, deldst, ifa->ifa_netmask);
2463 dst = deldst;
2464 }
2465 /*
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.
2470 */
2471 rt = rtalloc1_locked(dst, 0, 0);
2472 if (rt) {
2473 /*
2474 * Ok so we found the rtentry. it has an extra reference
2475 * for us at this stage. we won't need that so
2476 * lop that off now.
2477 */
2478 RT_LOCK_SPIN(rt);
2479 if (rt->rt_ifa != ifa) {
2480 RT_REMREF_LOCKED(rt);
2481 RT_UNLOCK(rt);
2482 /*
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.
2488 */
2489 if (m)
2490 (void) m_free(m);
2491 return (flags & RTF_HOST ? EHOSTUNREACH
2492 : ENETUNREACH);
2493 } else {
2494 RT_REMREF_LOCKED(rt);
2495 RT_UNLOCK(rt);
2496 }
2497 }
2498 /* XXX */
2499 #if 0
2500 else {
2501 /*
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..
2505 */
2506 lck_mtx_unlock(rnh_lock);
2507 return (flags & RTF_HOST ? EHOSTUNREACH
2508 : ENETUNREACH);
2509 }
2510 #endif
2511 }
2512 /*
2513 * Do the actual request
2514 */
2515 error = rtrequest_locked(cmd, dst, ifa->ifa_addr, ifa->ifa_netmask,
2516 flags | ifa->ifa_flags, &nrt);
2517 if (m)
2518 (void) m_free(m);
2519 /*
2520 * If we are deleting, and we found an entry, then
2521 * it's been removed from the tree.. now throw it away.
2522 */
2523 if (cmd == RTM_DELETE && error == 0 && (rt = nrt)) {
2524 /*
2525 * notify any listening routing agents of the change
2526 */
2527 RT_LOCK(rt);
2528 rt_newaddrmsg(cmd, ifa, error, nrt);
2529 if (use_routegenid)
2530 routegenid_update();
2531 RT_UNLOCK(rt);
2532 rtfree_locked(rt);
2533 }
2534
2535 /*
2536 * We are adding, and we have a returned routing entry.
2537 * We need to sanity check the result.
2538 */
2539 if (cmd == RTM_ADD && error == 0 && (rt = nrt)) {
2540 RT_LOCK(rt);
2541 /*
2542 * If it came back with an unexpected interface, then it must
2543 * have already existed or something. (XXX)
2544 */
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",
2549 ifa, rt->rt_ifa);
2550 /*
2551 * Ask that the protocol in question
2552 * remove anything it has associated with
2553 * this route and ifaddr.
2554 */
2555 if (rt->rt_ifa->ifa_rtrequest)
2556 rt->rt_ifa->ifa_rtrequest(RTM_DELETE, rt, SA(0));
2557 /*
2558 * Set the route's ifa.
2559 */
2560 rtsetifa(rt, ifa);
2561 #if IFNET_ROUTE_REFCNT
2562 /*
2563 * Adjust route ref count for the interfaces.
2564 */
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);
2569 }
2570 #endif /* IFNET_ROUTE_REFCNT */
2571 /*
2572 * And substitute in references to the ifaddr
2573 * we are adding.
2574 */
2575 rt->rt_ifp = ifa->ifa_ifp;
2576 rt->rt_rmx.rmx_mtu = ifa->ifa_ifp->if_mtu; /*XXX*/
2577 /*
2578 * Now ask the protocol to check if it needs
2579 * any special processing in its new form.
2580 */
2581 if (ifa->ifa_rtrequest)
2582 ifa->ifa_rtrequest(RTM_ADD, rt, SA(0));
2583 }
2584 /*
2585 * notify any listenning routing agents of the change
2586 */
2587 rt_newaddrmsg(cmd, ifa, error, nrt);
2588 if (use_routegenid)
2589 routegenid_update();
2590 /*
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.
2596 */
2597 RT_REMREF_LOCKED(rt);
2598 RT_UNLOCK(rt);
2599 }
2600 return (error);
2601 }
2602
2603 u_int64_t
2604 rt_expiry(struct rtentry *rt, u_int64_t base, u_int32_t delta)
2605 {
2606 #if IFNET_ROUTE_REFCNT
2607 u_int64_t retval;
2608
2609 /*
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.)
2614 */
2615 if (rt->rt_ifp == NULL || rt->rt_ifp->if_want_aggressive_drain == 0)
2616 retval = base + delta;
2617 else
2618 retval = base + MIN(rt_if_idle_expire_timeout, delta);
2619
2620 return (retval);
2621 #else
2622 #pragma unused(rt)
2623 return (base + delta);
2624 #endif /* IFNET_ROUTE_REFCNT */
2625 }
2626
2627 static void
2628 rte_lock_init(struct rtentry *rt)
2629 {
2630 lck_mtx_init(&rt->rt_lock, rte_mtx_grp, rte_mtx_attr);
2631 }
2632
2633 static void
2634 rte_lock_destroy(struct rtentry *rt)
2635 {
2636 RT_LOCK_ASSERT_NOTHELD(rt);
2637 lck_mtx_destroy(&rt->rt_lock, rte_mtx_grp);
2638 }
2639
2640 void
2641 rt_lock(struct rtentry *rt, boolean_t spin)
2642 {
2643 RT_LOCK_ASSERT_NOTHELD(rt);
2644 if (spin)
2645 lck_mtx_lock_spin(&rt->rt_lock);
2646 else
2647 lck_mtx_lock(&rt->rt_lock);
2648 if (rte_debug & RTD_DEBUG)
2649 rte_lock_debug((struct rtentry_dbg *)rt);
2650 }
2651
2652 void
2653 rt_unlock(struct rtentry *rt)
2654 {
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);
2659
2660 }
2661
2662 static inline void
2663 rte_lock_debug(struct rtentry_dbg *rte)
2664 {
2665 uint32_t idx;
2666
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]);
2670 }
2671
2672 static inline void
2673 rte_unlock_debug(struct rtentry_dbg *rte)
2674 {
2675 uint32_t idx;
2676
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]);
2680 }
2681
2682 static struct rtentry *
2683 rte_alloc(void)
2684 {
2685 if (rte_debug & RTD_DEBUG)
2686 return (rte_alloc_debug());
2687
2688 return ((struct rtentry *)zalloc(rte_zone));
2689 }
2690
2691 static void
2692 rte_free(struct rtentry *p)
2693 {
2694 if (rte_debug & RTD_DEBUG) {
2695 rte_free_debug(p);
2696 return;
2697 }
2698
2699 if (p->rt_refcnt != 0)
2700 panic("rte_free: rte=%p refcnt=%d non-zero\n", p, p->rt_refcnt);
2701
2702 zfree(rte_zone, p);
2703 }
2704
2705 #if IFNET_ROUTE_REFCNT
2706 static void
2707 rte_if_ref(struct ifnet *ifp, int cnt)
2708 {
2709 struct kev_msg ev_msg;
2710 struct net_event_data ev_data;
2711 uint32_t old;
2712
2713 /* Force cnt to 1 increment/decrement */
2714 if (cnt < -1 || cnt > 1)
2715 panic("%s: invalid count argument (%d)", __func__, cnt);
2716
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);
2720
2721 /*
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.
2731 */
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));
2735
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;
2740
2741 strlcpy(&ev_data.if_name[0], ifp->if_name, IFNAMSIZ);
2742
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;
2747
2748 kev_post_msg(&ev_msg);
2749 }
2750 }
2751 #endif /* IFNET_ROUTE_REFCNT */
2752
2753 static inline struct rtentry *
2754 rte_alloc_debug(void)
2755 {
2756 struct rtentry_dbg *rte;
2757
2758 rte = ((struct rtentry_dbg *)zalloc(rte_zone));
2759 if (rte != NULL) {
2760 bzero(rte, sizeof (*rte));
2761 if (rte_debug & RTD_TRACE)
2762 ctrace_record(&rte->rtd_alloc);
2763 rte->rtd_inuse = RTD_INUSE;
2764 }
2765 return ((struct rtentry *)rte);
2766 }
2767
2768 static inline void
2769 rte_free_debug(struct rtentry *p)
2770 {
2771 struct rtentry_dbg *rte = (struct rtentry_dbg *)p;
2772
2773 if (p->rt_refcnt != 0)
2774 panic("rte_free: rte=%p refcnt=%d\n", p, p->rt_refcnt);
2775
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);
2780
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));
2784
2785 rte->rtd_inuse = RTD_FREED;
2786
2787 if (rte_debug & RTD_TRACE)
2788 ctrace_record(&rte->rtd_free);
2789
2790 if (!(rte_debug & RTD_NO_FREE))
2791 zfree(rte_zone, p);
2792 }
2793
2794 void
2795 ctrace_record(ctrace_t *tr)
2796 {
2797 tr->th = current_thread();
2798 bzero(tr->pc, sizeof (tr->pc));
2799 (void) OSBacktrace(tr->pc, CTRACE_STACK_SIZE);
2800 }