]> git.saurik.com Git - apple/xnu.git/blob - bsd/net/route.c
xnu-1504.3.12.tar.gz
[apple/xnu.git] / bsd / net / route.c
1 /*
2 * Copyright (c) 2000-2008 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/systm.h>
66 #include <sys/malloc.h>
67 #include <sys/mbuf.h>
68 #include <sys/socket.h>
69 #include <sys/domain.h>
70 #include <sys/syslog.h>
71 #include <sys/queue.h>
72 #include <kern/lock.h>
73 #include <kern/zalloc.h>
74
75 #include <net/if.h>
76 #include <net/route.h>
77
78 #include <netinet/in.h>
79 #include <netinet/in_var.h>
80 #include <netinet/ip_mroute.h>
81 #include <netinet/ip_var.h>
82
83 #include <net/if_dl.h>
84
85 #include <libkern/OSAtomic.h>
86 #include <libkern/OSDebug.h>
87
88 #include <pexpert/pexpert.h>
89
90 /*
91 * Synchronization notes:
92 *
93 * Routing entries fall under two locking domains: the global routing table
94 * lock (rnh_lock) and the per-entry lock (rt_lock); the latter is a mutex that
95 * resides (statically defined) in the rtentry structure.
96 *
97 * The locking domains for routing are defined as follows:
98 *
99 * The global routing lock is used to serialize all accesses to the radix
100 * trees defined by rt_tables[], as well as the tree of masks. This includes
101 * lookups, insertions and removals of nodes to/from the respective tree.
102 * It is also used to protect certain fields in the route entry that aren't
103 * often modified and/or require global serialization (more details below.)
104 *
105 * The per-route entry lock is used to serialize accesses to several routing
106 * entry fields (more details below.) Acquiring and releasing this lock is
107 * done via RT_LOCK() and RT_UNLOCK() routines.
108 *
109 * In cases where both rnh_lock and rt_lock must be held, the former must be
110 * acquired first in order to maintain lock ordering. It is not a requirement
111 * that rnh_lock be acquired first before rt_lock, but in case both must be
112 * acquired in succession, the correct lock ordering must be followed.
113 *
114 * The fields of the rtentry structure are protected in the following way:
115 *
116 * rt_nodes[]
117 *
118 * - Routing table lock (rnh_lock).
119 *
120 * rt_parent, rt_mask, rt_llinfo_free
121 *
122 * - Set once during creation and never changes; no locks to read.
123 *
124 * rt_flags, rt_genmask, rt_llinfo, rt_rmx, rt_refcnt, rt_gwroute
125 *
126 * - Routing entry lock (rt_lock) for read/write access.
127 *
128 * - Some values of rt_flags are either set once at creation time,
129 * or aren't currently used, and thus checking against them can
130 * be done without rt_lock: RTF_GATEWAY, RTF_HOST, RTF_DYNAMIC,
131 * RTF_DONE, RTF_XRESOLVE, RTF_STATIC, RTF_BLACKHOLE, RTF_ANNOUNCE,
132 * RTF_USETRAILERS, RTF_WASCLONED, RTF_PINNED, RTF_LOCAL,
133 * RTF_BROADCAST, RTF_MULTICAST, RTF_IFSCOPE.
134 *
135 * rt_key, rt_gateway, rt_ifp, rt_ifa
136 *
137 * - Always written/modified with both rnh_lock and rt_lock held.
138 *
139 * - May be read freely with rnh_lock held, else must hold rt_lock
140 * for read access; holding both locks for read is also okay.
141 *
142 * - In the event rnh_lock is not acquired, or is not possible to be
143 * acquired across the operation, setting RTF_CONDEMNED on a route
144 * entry will prevent its rt_key, rt_gateway, rt_ifp and rt_ifa
145 * from being modified. This is typically done on a route that
146 * has been chosen for a removal (from the tree) prior to dropping
147 * the rt_lock, so that those values will remain the same until
148 * the route is freed.
149 *
150 * When rnh_lock is held rt_setgate(), rt_setif(), and rtsetifa() are
151 * single-threaded, thus exclusive. This flag will also prevent the
152 * route from being looked up via rt_lookup().
153 *
154 * generation_id
155 *
156 * - Assumes that 32-bit writes are atomic; no locks.
157 *
158 * rt_dlt, rt_output
159 *
160 * - Currently unused; no locks.
161 *
162 * Operations on a route entry can be described as follows:
163 *
164 * CREATE an entry with reference count set to 0 as part of RTM_ADD/RESOLVE.
165 *
166 * INSERTION of an entry into the radix tree holds the rnh_lock, checks
167 * for duplicates and then adds the entry. rtrequest returns the entry
168 * after bumping up the reference count to 1 (for the caller).
169 *
170 * LOOKUP of an entry holds the rnh_lock and bumps up the reference count
171 * before returning; it is valid to also bump up the reference count using
172 * RT_ADDREF after the lookup has returned an entry.
173 *
174 * REMOVAL of an entry from the radix tree holds the rnh_lock, removes the
175 * entry but does not decrement the reference count. Removal happens when
176 * the route is explicitly deleted (RTM_DELETE) or when it is in the cached
177 * state and it expires. The route is said to be "down" when it is no
178 * longer present in the tree. Freeing the entry will happen on the last
179 * reference release of such a "down" route.
180 *
181 * RT_ADDREF/RT_REMREF operates on the routing entry which increments/
182 * decrements the reference count, rt_refcnt, atomically on the rtentry.
183 * rt_refcnt is modified only using this routine. The general rule is to
184 * do RT_ADDREF in the function that is passing the entry as an argument,
185 * in order to prevent the entry from being freed by the callee.
186 */
187
188 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
189 #define SA(p) ((struct sockaddr *)(p))
190
191 extern void kdp_set_gateway_mac (void *gatewaymac);
192
193 extern struct domain routedomain;
194 struct route_cb route_cb;
195 __private_extern__ struct rtstat rtstat = { 0, 0, 0, 0, 0 };
196 struct radix_node_head *rt_tables[AF_MAX+1];
197
198 lck_mtx_t *rnh_lock; /* global routing tables mutex */
199 static lck_attr_t *rnh_lock_attr;
200 static lck_grp_t *rnh_lock_grp;
201 static lck_grp_attr_t *rnh_lock_grp_attr;
202
203 /* Lock group and attribute for routing entry locks */
204 static lck_attr_t *rte_mtx_attr;
205 static lck_grp_t *rte_mtx_grp;
206 static lck_grp_attr_t *rte_mtx_grp_attr;
207
208 lck_mtx_t *route_domain_mtx; /*### global routing tables mutex for now */
209 int rttrash = 0; /* routes not in table but not freed */
210
211 unsigned int rte_debug;
212
213 /* Possible flags for rte_debug */
214 #define RTD_DEBUG 0x1 /* enable or disable rtentry debug facility */
215 #define RTD_TRACE 0x2 /* trace alloc, free, refcnt and lock */
216 #define RTD_NO_FREE 0x4 /* don't free (good to catch corruptions) */
217
218 #define RTE_NAME "rtentry" /* name for zone and rt_lock */
219
220 static struct zone *rte_zone; /* special zone for rtentry */
221 #define RTE_ZONE_MAX 65536 /* maximum elements in zone */
222 #define RTE_ZONE_NAME RTE_NAME /* name of rtentry zone */
223
224 #define RTD_INUSE 0xFEEDFACE /* entry is in use */
225 #define RTD_FREED 0xDEADBEEF /* entry is freed */
226
227 /* For gdb */
228 __private_extern__ unsigned int ctrace_stack_size = CTRACE_STACK_SIZE;
229 __private_extern__ unsigned int ctrace_hist_size = CTRACE_HIST_SIZE;
230
231 /*
232 * Debug variant of rtentry structure.
233 */
234 struct rtentry_dbg {
235 struct rtentry rtd_entry; /* rtentry */
236 struct rtentry rtd_entry_saved; /* saved rtentry */
237 uint32_t rtd_inuse; /* in use pattern */
238 uint16_t rtd_refhold_cnt; /* # of rtref */
239 uint16_t rtd_refrele_cnt; /* # of rtunref */
240 uint32_t rtd_lock_cnt; /* # of locks */
241 uint32_t rtd_unlock_cnt; /* # of unlocks */
242 /*
243 * Alloc and free callers.
244 */
245 ctrace_t rtd_alloc;
246 ctrace_t rtd_free;
247 /*
248 * Circular lists of rtref and rtunref callers.
249 */
250 ctrace_t rtd_refhold[CTRACE_HIST_SIZE];
251 ctrace_t rtd_refrele[CTRACE_HIST_SIZE];
252 /*
253 * Circular lists of locks and unlocks.
254 */
255 ctrace_t rtd_lock[CTRACE_HIST_SIZE];
256 ctrace_t rtd_unlock[CTRACE_HIST_SIZE];
257 /*
258 * Trash list linkage
259 */
260 TAILQ_ENTRY(rtentry_dbg) rtd_trash_link;
261 };
262
263 #define atomic_add_16_ov(a, n) \
264 ((uint16_t) OSAddAtomic16(n, (volatile SInt16 *)a))
265 #define atomic_add_32_ov(a, n) \
266 ((uint32_t) OSAddAtomic(n, a))
267
268 /* List of trash route entries protected by rnh_lock */
269 static TAILQ_HEAD(, rtentry_dbg) rttrash_head;
270
271 static void rte_lock_init(struct rtentry *);
272 static void rte_lock_destroy(struct rtentry *);
273 static inline struct rtentry *rte_alloc_debug(void);
274 static inline void rte_free_debug(struct rtentry *);
275 static inline void rte_lock_debug(struct rtentry_dbg *);
276 static inline void rte_unlock_debug(struct rtentry_dbg *);
277 static void rt_maskedcopy(struct sockaddr *,
278 struct sockaddr *, struct sockaddr *);
279 static void rtable_init(void **);
280 static inline void rtref_audit(struct rtentry_dbg *);
281 static inline void rtunref_audit(struct rtentry_dbg *);
282 static struct rtentry *rtalloc1_common_locked(struct sockaddr *, int, uint32_t,
283 unsigned int);
284 static int rtrequest_common_locked(int, struct sockaddr *,
285 struct sockaddr *, struct sockaddr *, int, struct rtentry **,
286 unsigned int);
287 static void rtalloc_ign_common_locked(struct route *, uint32_t, unsigned int);
288 static inline void sa_set_ifscope(struct sockaddr *, unsigned int);
289 static struct sockaddr *sin_copy(struct sockaddr_in *, struct sockaddr_in *,
290 unsigned int);
291 static struct sockaddr *mask_copy(struct sockaddr *, struct sockaddr_in *,
292 unsigned int);
293 static struct sockaddr *sa_trim(struct sockaddr *, int);
294 static struct radix_node *node_lookup(struct sockaddr *, struct sockaddr *,
295 unsigned int);
296 static struct radix_node *node_lookup_default(void);
297 static int rn_match_ifscope(struct radix_node *, void *);
298 static struct ifaddr *ifa_ifwithroute_common_locked(int,
299 const struct sockaddr *, const struct sockaddr *, unsigned int);
300 static struct rtentry *rte_alloc(void);
301 static void rte_free(struct rtentry *);
302 static void rtfree_common(struct rtentry *, boolean_t);
303
304 uint32_t route_generation = 0;
305
306 /*
307 * sockaddr_in with embedded interface scope; this is used internally
308 * to keep track of scoped route entries in the routing table. The
309 * fact that such a scope is embedded in the structure is an artifact
310 * of the current implementation which could change in future.
311 */
312 struct sockaddr_inifscope {
313 __uint8_t sin_len;
314 sa_family_t sin_family;
315 in_port_t sin_port;
316 struct in_addr sin_addr;
317 /*
318 * To avoid possible conflict with an overlaid sockaddr_inarp
319 * having sin_other set to SIN_PROXY, we use the first 4-bytes
320 * of sin_zero since sin_srcaddr is one of the unused fields
321 * in sockaddr_inarp.
322 */
323 union {
324 char sin_zero[8];
325 struct {
326 __uint32_t ifscope;
327 } _in_index;
328 } un;
329 #define sin_ifscope un._in_index.ifscope
330 };
331
332 #define SIN(sa) ((struct sockaddr_in *)(size_t)(sa))
333 #define SINIFSCOPE(sa) ((struct sockaddr_inifscope *)(size_t)(sa))
334
335 #define ASSERT_SINIFSCOPE(sa) { \
336 if ((sa)->sa_family != AF_INET || \
337 (sa)->sa_len < sizeof (struct sockaddr_in)) \
338 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
339 }
340
341 /*
342 * Argument to leaf-matching routine; at present it is scoped routing
343 * specific but can be expanded in future to include other search filters.
344 */
345 struct matchleaf_arg {
346 unsigned int ifscope; /* interface scope */
347 };
348
349 /*
350 * For looking up the non-scoped default route (sockaddr instead
351 * of sockaddr_in for convenience).
352 */
353 static struct sockaddr sin_def = {
354 sizeof (struct sockaddr_in), AF_INET, { 0, }
355 };
356
357 /*
358 * Interface index (scope) of the primary interface; determined at
359 * the time when the default, non-scoped route gets added, changed
360 * or deleted. Protected by rnh_lock.
361 */
362 static unsigned int primary_ifscope = IFSCOPE_NONE;
363
364 #define INET_DEFAULT(dst) \
365 ((dst)->sa_family == AF_INET && SIN(dst)->sin_addr.s_addr == 0)
366
367 #define RT(r) ((struct rtentry *)r)
368 #define RT_HOST(r) (RT(r)->rt_flags & RTF_HOST)
369
370 /*
371 * Given a route, determine whether or not it is the non-scoped default
372 * route; dst typically comes from rt_key(rt) but may be coming from
373 * a separate place when rt is in the process of being created.
374 */
375 boolean_t
376 rt_inet_default(struct rtentry *rt, struct sockaddr *dst)
377 {
378 return (INET_DEFAULT(dst) && !(rt->rt_flags & RTF_IFSCOPE));
379 }
380
381 /*
382 * Set the ifscope of the primary interface; caller holds rnh_lock.
383 */
384 void
385 set_primary_ifscope(unsigned int ifscope)
386 {
387 primary_ifscope = ifscope;
388 }
389
390 /*
391 * Return the ifscope of the primary interface; caller holds rnh_lock.
392 */
393 unsigned int
394 get_primary_ifscope(void)
395 {
396 return (primary_ifscope);
397 }
398
399 /*
400 * Embed ifscope into a given a sockaddr_in.
401 */
402 static inline void
403 sa_set_ifscope(struct sockaddr *sa, unsigned int ifscope)
404 {
405 /* Caller must pass in sockaddr_in */
406 ASSERT_SINIFSCOPE(sa);
407
408 SINIFSCOPE(sa)->sin_ifscope = ifscope;
409 }
410
411 /*
412 * Given a sockaddr_in, return the embedded ifscope to the caller.
413 */
414 unsigned int
415 sa_get_ifscope(struct sockaddr *sa)
416 {
417 /* Caller must pass in sockaddr_in */
418 ASSERT_SINIFSCOPE(sa);
419
420 return (SINIFSCOPE(sa)->sin_ifscope);
421 }
422
423 /*
424 * Copy a sockaddr_in src to dst and embed ifscope into dst.
425 */
426 static struct sockaddr *
427 sin_copy(struct sockaddr_in *src, struct sockaddr_in *dst, unsigned int ifscope)
428 {
429 *dst = *src;
430 sa_set_ifscope(SA(dst), ifscope);
431
432 return (SA(dst));
433 }
434
435 /*
436 * Copy a mask from src to a sockaddr_in dst and embed ifscope into dst.
437 */
438 static struct sockaddr *
439 mask_copy(struct sockaddr *src, struct sockaddr_in *dst, unsigned int ifscope)
440 {
441 /* We know dst is at least the size of sockaddr{_in} */
442 bzero(dst, sizeof (*dst));
443 rt_maskedcopy(src, SA(dst), src);
444
445 /*
446 * The length of the mask sockaddr would need to be adjusted
447 * to cover the additional sin_ifscope field; when ifscope is
448 * IFSCOPE_NONE, we'd end up clearing the embedded ifscope on
449 * the destination mask in addition to extending the length
450 * of the sockaddr, as a side effect. This is okay, as any
451 * trailing zeroes would be skipped by rn_addmask prior to
452 * inserting or looking up the mask in the mask tree.
453 */
454 SINIFSCOPE(dst)->sin_ifscope = ifscope;
455 SINIFSCOPE(dst)->sin_len =
456 offsetof(struct sockaddr_inifscope, sin_ifscope) +
457 sizeof (SINIFSCOPE(dst)->sin_ifscope);
458
459 return (SA(dst));
460 }
461
462 /*
463 * Trim trailing zeroes on a sockaddr and update its length.
464 */
465 static struct sockaddr *
466 sa_trim(struct sockaddr *sa, int skip)
467 {
468 caddr_t cp, base = (caddr_t)sa + skip;
469
470 if (sa->sa_len <= skip)
471 return (sa);
472
473 for (cp = base + (sa->sa_len - skip); cp > base && cp[-1] == 0;)
474 cp--;
475
476 sa->sa_len = (cp - base) + skip;
477 if (sa->sa_len < skip) {
478 /* Must not happen, and if so, panic */
479 panic("%s: broken logic (sa_len %d < skip %d )", __func__,
480 sa->sa_len, skip);
481 /* NOTREACHED */
482 } else if (sa->sa_len == skip) {
483 /* If we end up with all zeroes, then there's no mask */
484 sa->sa_len = 0;
485 }
486
487 return (sa);
488 }
489
490 /*
491 * Called by rtm_msg{1,2} routines to "scrub" the embedded interface scope
492 * away from the socket address structure, so that clients of the routing
493 * socket will not be confused by the presence of the embedded scope, or the
494 * side effect of the increased length due to that. The source sockaddr is
495 * not modified; instead, the scrubbing happens on the destination sockaddr
496 * storage that is passed in by the caller.
497 */
498 struct sockaddr *
499 rtm_scrub_ifscope(int idx, struct sockaddr *hint, struct sockaddr *sa,
500 struct sockaddr_storage *ss)
501 {
502 struct sockaddr *ret = sa;
503
504 switch (idx) {
505 case RTAX_DST:
506 /*
507 * If this is for an AF_INET destination address, call
508 * sin_copy() with IFSCOPE_NONE as it does what we need.
509 */
510 if (sa->sa_family == AF_INET &&
511 SINIFSCOPE(sa)->sin_ifscope != IFSCOPE_NONE) {
512 bzero(ss, sizeof (*ss));
513 ret = sin_copy(SIN(sa), SIN(ss), IFSCOPE_NONE);
514 }
515 break;
516
517 case RTAX_NETMASK: {
518 /*
519 * If this is for a mask, we can't tell whether or not
520 * there is an embedded interface scope, as the span of
521 * bytes between sa_len and the beginning of the mask
522 * (offset of sin_addr in the case of AF_INET) may be
523 * filled with all-ones by rn_addmask(), and hence we
524 * cannot rely on sa_family. Because of this, we use
525 * the sa_family of the hint sockaddr (RTAX_{DST,IFA})
526 * as indicator as to whether or not the mask is to be
527 * treated as one for AF_INET. Clearing the embedded
528 * scope involves setting it to IFSCOPE_NONE followed
529 * by calling sa_trim() to trim trailing zeroes from
530 * the storage sockaddr, which reverses what was done
531 * earlier by mask_copy() on the source sockaddr.
532 */
533 int skip = offsetof(struct sockaddr_in, sin_addr);
534 if (sa->sa_len > skip && sa->sa_len <= sizeof (*ss) &&
535 hint != NULL && hint->sa_family == AF_INET) {
536 bzero(ss, sizeof (*ss));
537 bcopy(sa, ss, sa->sa_len);
538 SINIFSCOPE(ss)->sin_ifscope = IFSCOPE_NONE;
539 ret = sa_trim(SA(ss), skip);
540 }
541 break;
542 }
543 default:
544 break;
545 }
546
547 return (ret);
548 }
549
550 /*
551 * Callback leaf-matching routine for rn_matchaddr_args used
552 * for looking up an exact match for a scoped route entry.
553 */
554 static int
555 rn_match_ifscope(struct radix_node *rn, void *arg)
556 {
557 struct rtentry *rt = (struct rtentry *)rn;
558 struct matchleaf_arg *ma = arg;
559
560 if (!(rt->rt_flags & RTF_IFSCOPE) || rt_key(rt)->sa_family != AF_INET)
561 return (0);
562
563 return (SINIFSCOPE(rt_key(rt))->sin_ifscope == ma->ifscope);
564 }
565
566 static void
567 rtable_init(void **table)
568 {
569 struct domain *dom;
570 for (dom = domains; dom; dom = dom->dom_next)
571 if (dom->dom_rtattach)
572 dom->dom_rtattach(&table[dom->dom_family],
573 dom->dom_rtoffset);
574 }
575
576 void
577 route_init(void)
578 {
579 int size;
580
581 PE_parse_boot_argn("rte_debug", &rte_debug, sizeof (rte_debug));
582 if (rte_debug != 0)
583 rte_debug |= RTD_DEBUG;
584
585 rnh_lock_grp_attr = lck_grp_attr_alloc_init();
586 rnh_lock_grp = lck_grp_alloc_init("route", rnh_lock_grp_attr);
587 rnh_lock_attr = lck_attr_alloc_init();
588 if ((rnh_lock = lck_mtx_alloc_init(rnh_lock_grp,
589 rnh_lock_attr)) == NULL) {
590 printf("route_init: can't alloc rnh_lock\n");
591 return;
592 }
593
594 rte_mtx_grp_attr = lck_grp_attr_alloc_init();
595 rte_mtx_grp = lck_grp_alloc_init(RTE_NAME, rte_mtx_grp_attr);
596 rte_mtx_attr = lck_attr_alloc_init();
597
598 lck_mtx_lock(rnh_lock);
599 rn_init(); /* initialize all zeroes, all ones, mask table */
600 lck_mtx_unlock(rnh_lock);
601 rtable_init((void **)rt_tables);
602 route_domain_mtx = routedomain.dom_mtx;
603
604 if (rte_debug & RTD_DEBUG)
605 size = sizeof (struct rtentry_dbg);
606 else
607 size = sizeof (struct rtentry);
608
609 rte_zone = zinit(size, RTE_ZONE_MAX * size, 0, RTE_ZONE_NAME);
610 if (rte_zone == NULL)
611 panic("route_init: failed allocating rte_zone");
612
613 zone_change(rte_zone, Z_EXPAND, TRUE);
614
615 TAILQ_INIT(&rttrash_head);
616 }
617
618 /*
619 * Atomically increment route generation counter
620 */
621 void
622 routegenid_update(void)
623 {
624 (void) atomic_add_32_ov(&route_generation, 1);
625 }
626
627 /*
628 * Packet routing routines.
629 */
630 void
631 rtalloc(struct route *ro)
632 {
633 rtalloc_ign(ro, 0);
634 }
635
636 void
637 rtalloc_ign_locked(struct route *ro, uint32_t ignore)
638 {
639 return (rtalloc_ign_common_locked(ro, ignore, IFSCOPE_NONE));
640 }
641
642 void
643 rtalloc_scoped_ign_locked(struct route *ro, uint32_t ignore,
644 unsigned int ifscope)
645 {
646 return (rtalloc_ign_common_locked(ro, ignore, ifscope));
647 }
648
649 static void
650 rtalloc_ign_common_locked(struct route *ro, uint32_t ignore,
651 unsigned int ifscope)
652 {
653 struct rtentry *rt;
654
655 if ((rt = ro->ro_rt) != NULL) {
656 RT_LOCK_SPIN(rt);
657 if (rt->rt_ifp != NULL && (rt->rt_flags & RTF_UP) &&
658 rt->generation_id == route_generation) {
659 RT_UNLOCK(rt);
660 return;
661 }
662 RT_UNLOCK(rt);
663 rtfree_locked(rt);
664 ro->ro_rt = NULL;
665 }
666 ro->ro_rt = rtalloc1_common_locked(&ro->ro_dst, 1, ignore, ifscope);
667 if (ro->ro_rt != NULL) {
668 ro->ro_rt->generation_id = route_generation;
669 RT_LOCK_ASSERT_NOTHELD(ro->ro_rt);
670 }
671 }
672
673 void
674 rtalloc_ign(struct route *ro, uint32_t ignore)
675 {
676 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
677 lck_mtx_lock(rnh_lock);
678 rtalloc_ign_locked(ro, ignore);
679 lck_mtx_unlock(rnh_lock);
680 }
681
682 void
683 rtalloc_scoped_ign(struct route *ro, uint32_t ignore, unsigned int ifscope)
684 {
685 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
686 lck_mtx_lock(rnh_lock);
687 rtalloc_scoped_ign_locked(ro, ignore, ifscope);
688 lck_mtx_unlock(rnh_lock);
689 }
690
691 struct rtentry *
692 rtalloc1_locked(struct sockaddr *dst, int report, uint32_t ignflags)
693 {
694 return (rtalloc1_common_locked(dst, report, ignflags, IFSCOPE_NONE));
695 }
696
697 struct rtentry *
698 rtalloc1_scoped_locked(struct sockaddr *dst, int report, uint32_t ignflags,
699 unsigned int ifscope)
700 {
701 return (rtalloc1_common_locked(dst, report, ignflags, ifscope));
702 }
703
704 /*
705 * Look up the route that matches the address given
706 * Or, at least try.. Create a cloned route if needed.
707 */
708 static struct rtentry *
709 rtalloc1_common_locked(struct sockaddr *dst, int report, uint32_t ignflags,
710 unsigned int ifscope)
711 {
712 struct radix_node_head *rnh = rt_tables[dst->sa_family];
713 struct rtentry *rt, *newrt = NULL;
714 struct rt_addrinfo info;
715 uint32_t nflags;
716 int err = 0, msgtype = RTM_MISS;
717
718 if (rnh == NULL)
719 goto unreachable;
720
721 /*
722 * Find the longest prefix or exact (in the scoped case) address match;
723 * callee adds a reference to entry and checks for root node as well
724 */
725 rt = rt_lookup(FALSE, dst, NULL, rnh, ifscope);
726 if (rt == NULL)
727 goto unreachable;
728
729 RT_LOCK_SPIN(rt);
730 newrt = rt;
731 nflags = rt->rt_flags & ~ignflags;
732 RT_UNLOCK(rt);
733 if (report && (nflags & (RTF_CLONING | RTF_PRCLONING))) {
734 /*
735 * We are apparently adding (report = 0 in delete).
736 * If it requires that it be cloned, do so.
737 * (This implies it wasn't a HOST route.)
738 */
739 err = rtrequest_locked(RTM_RESOLVE, dst, NULL, NULL, 0, &newrt);
740 if (err) {
741 /*
742 * If the cloning didn't succeed, maybe what we
743 * have from lookup above will do. Return that;
744 * no need to hold another reference since it's
745 * already done.
746 */
747 newrt = rt;
748 goto miss;
749 }
750
751 /*
752 * We cloned it; drop the original route found during lookup.
753 * The resulted cloned route (newrt) would now have an extra
754 * reference held during rtrequest.
755 */
756 rtfree_locked(rt);
757 if ((rt = newrt) && (rt->rt_flags & RTF_XRESOLVE)) {
758 /*
759 * If the new route specifies it be
760 * externally resolved, then go do that.
761 */
762 msgtype = RTM_RESOLVE;
763 goto miss;
764 }
765 }
766 goto done;
767
768 unreachable:
769 /*
770 * Either we hit the root or couldn't find any match,
771 * Which basically means "cant get there from here"
772 */
773 rtstat.rts_unreach++;
774 miss:
775 if (report) {
776 /*
777 * If required, report the failure to the supervising
778 * Authorities.
779 * For a delete, this is not an error. (report == 0)
780 */
781 bzero((caddr_t)&info, sizeof(info));
782 info.rti_info[RTAX_DST] = dst;
783 rt_missmsg(msgtype, &info, 0, err);
784 }
785 done:
786 return (newrt);
787 }
788
789 struct rtentry *
790 rtalloc1(struct sockaddr *dst, int report, uint32_t ignflags)
791 {
792 struct rtentry * entry;
793 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
794 lck_mtx_lock(rnh_lock);
795 entry = rtalloc1_locked(dst, report, ignflags);
796 lck_mtx_unlock(rnh_lock);
797 return (entry);
798 }
799
800 struct rtentry *
801 rtalloc1_scoped(struct sockaddr *dst, int report, uint32_t ignflags,
802 unsigned int ifscope)
803 {
804 struct rtentry * entry;
805 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
806 lck_mtx_lock(rnh_lock);
807 entry = rtalloc1_scoped_locked(dst, report, ignflags, ifscope);
808 lck_mtx_unlock(rnh_lock);
809 return (entry);
810 }
811
812 /*
813 * Remove a reference count from an rtentry.
814 * If the count gets low enough, take it out of the routing table
815 */
816 void
817 rtfree_locked(struct rtentry *rt)
818 {
819 rtfree_common(rt, TRUE);
820 }
821
822 static void
823 rtfree_common(struct rtentry *rt, boolean_t locked)
824 {
825 struct radix_node_head *rnh;
826
827 /*
828 * Atomically decrement the reference count and if it reaches 0,
829 * and there is a close function defined, call the close function.
830 */
831 RT_LOCK_SPIN(rt);
832 if (rtunref(rt) > 0) {
833 RT_UNLOCK(rt);
834 return;
835 }
836
837 /*
838 * To avoid violating lock ordering, we must drop rt_lock before
839 * trying to acquire the global rnh_lock. If we are called with
840 * rnh_lock held, then we already have exclusive access; otherwise
841 * we do the lock dance.
842 */
843 if (!locked) {
844 /*
845 * Note that we check it again below after grabbing rnh_lock,
846 * since it is possible that another thread doing a lookup wins
847 * the race, grabs the rnh_lock first, and bumps up the reference
848 * count in which case the route should be left alone as it is
849 * still in use. It's also possible that another thread frees
850 * the route after we drop rt_lock; to prevent the route from
851 * being freed, we hold an extra reference.
852 */
853 RT_ADDREF_LOCKED(rt);
854 RT_UNLOCK(rt);
855 lck_mtx_lock(rnh_lock);
856 RT_LOCK_SPIN(rt);
857 RT_REMREF_LOCKED(rt);
858 if (rt->rt_refcnt > 0) {
859 /* We've lost the race, so abort */
860 RT_UNLOCK(rt);
861 goto done;
862 }
863 }
864
865 /*
866 * We may be blocked on other lock(s) as part of freeing
867 * the entry below, so convert from spin to full mutex.
868 */
869 RT_CONVERT_LOCK(rt);
870
871 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
872
873 /* Negative refcnt must never happen */
874 if (rt->rt_refcnt != 0)
875 panic("rt %p invalid refcnt %d", rt, rt->rt_refcnt);
876
877 /*
878 * find the tree for that address family
879 * Note: in the case of igmp packets, there might not be an rnh
880 */
881 rnh = rt_tables[rt_key(rt)->sa_family];
882
883 /*
884 * On last reference give the "close method" a chance to cleanup
885 * private state. This also permits (for IPv4 and IPv6) a chance
886 * to decide if the routing table entry should be purged immediately
887 * or at a later time. When an immediate purge is to happen the
888 * close routine typically issues RTM_DELETE which clears the RTF_UP
889 * flag on the entry so that the code below reclaims the storage.
890 */
891 if (rnh != NULL && rnh->rnh_close != NULL)
892 rnh->rnh_close((struct radix_node *)rt, rnh);
893
894 /*
895 * If we are no longer "up" (and ref == 0) then we can free the
896 * resources associated with the route.
897 */
898 if (!(rt->rt_flags & RTF_UP)) {
899 if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
900 panic("rt %p freed while in radix tree\n", rt);
901 /*
902 * the rtentry must have been removed from the routing table
903 * so it is represented in rttrash; remove that now.
904 */
905 (void) OSDecrementAtomic(&rttrash);
906 if (rte_debug & RTD_DEBUG) {
907 TAILQ_REMOVE(&rttrash_head, (struct rtentry_dbg *)rt,
908 rtd_trash_link);
909 }
910
911 /*
912 * Route is no longer in the tree and refcnt is 0;
913 * we have exclusive access, so destroy it.
914 */
915 RT_UNLOCK(rt);
916
917 /*
918 * release references on items we hold them on..
919 * e.g other routes and ifaddrs.
920 */
921 if (rt->rt_parent != NULL) {
922 rtfree_locked(rt->rt_parent);
923 rt->rt_parent = NULL;
924 }
925
926 if (rt->rt_ifa != NULL) {
927 ifafree(rt->rt_ifa);
928 rt->rt_ifa = NULL;
929 }
930
931 /*
932 * Now free any attached link-layer info.
933 */
934 if (rt->rt_llinfo != NULL) {
935 if (rt->rt_llinfo_free != NULL)
936 (*rt->rt_llinfo_free)(rt->rt_llinfo);
937 else
938 R_Free(rt->rt_llinfo);
939 rt->rt_llinfo = NULL;
940 }
941
942 /*
943 * The key is separately alloc'd so free it (see rt_setgate()).
944 * This also frees the gateway, as they are always malloc'd
945 * together.
946 */
947 R_Free(rt_key(rt));
948
949 /*
950 * and the rtentry itself of course
951 */
952 rte_lock_destroy(rt);
953 rte_free(rt);
954 } else {
955 /*
956 * The "close method" has been called, but the route is
957 * still in the radix tree with zero refcnt, i.e. "up"
958 * and in the cached state.
959 */
960 RT_UNLOCK(rt);
961 }
962 done:
963 if (!locked)
964 lck_mtx_unlock(rnh_lock);
965 }
966
967 void
968 rtfree(struct rtentry *rt)
969 {
970 rtfree_common(rt, FALSE);
971 }
972
973 /*
974 * Decrements the refcount but does not free the route when
975 * the refcount reaches zero. Unless you have really good reason,
976 * use rtfree not rtunref.
977 */
978 int
979 rtunref(struct rtentry *p)
980 {
981 RT_LOCK_ASSERT_HELD(p);
982
983 if (p->rt_refcnt == 0)
984 panic("%s(%p) bad refcnt\n", __func__, p);
985
986 --p->rt_refcnt;
987
988 if (rte_debug & RTD_DEBUG)
989 rtunref_audit((struct rtentry_dbg *)p);
990
991 /* Return new value */
992 return (p->rt_refcnt);
993 }
994
995 static inline void
996 rtunref_audit(struct rtentry_dbg *rte)
997 {
998 uint16_t idx;
999
1000 if (rte->rtd_inuse != RTD_INUSE)
1001 panic("rtunref: on freed rte=%p\n", rte);
1002
1003 idx = atomic_add_16_ov(&rte->rtd_refrele_cnt, 1) % CTRACE_HIST_SIZE;
1004 if (rte_debug & RTD_TRACE)
1005 ctrace_record(&rte->rtd_refrele[idx]);
1006 }
1007
1008 /*
1009 * Add a reference count from an rtentry.
1010 */
1011 void
1012 rtref(struct rtentry *p)
1013 {
1014 RT_LOCK_ASSERT_HELD(p);
1015
1016 if (++p->rt_refcnt == 0)
1017 panic("%s(%p) bad refcnt\n", __func__, p);
1018
1019 if (rte_debug & RTD_DEBUG)
1020 rtref_audit((struct rtentry_dbg *)p);
1021 }
1022
1023 static inline void
1024 rtref_audit(struct rtentry_dbg *rte)
1025 {
1026 uint16_t idx;
1027
1028 if (rte->rtd_inuse != RTD_INUSE)
1029 panic("rtref_audit: on freed rte=%p\n", rte);
1030
1031 idx = atomic_add_16_ov(&rte->rtd_refhold_cnt, 1) % CTRACE_HIST_SIZE;
1032 if (rte_debug & RTD_TRACE)
1033 ctrace_record(&rte->rtd_refhold[idx]);
1034 }
1035
1036 void
1037 rtsetifa(struct rtentry *rt, struct ifaddr* ifa)
1038 {
1039 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1040
1041 RT_LOCK_ASSERT_HELD(rt);
1042
1043 if (rt->rt_ifa == ifa)
1044 return;
1045
1046 /* Release the old ifa */
1047 if (rt->rt_ifa)
1048 ifafree(rt->rt_ifa);
1049
1050 /* Set rt_ifa */
1051 rt->rt_ifa = ifa;
1052
1053 /* Take a reference to the ifa */
1054 if (rt->rt_ifa)
1055 ifaref(rt->rt_ifa);
1056 }
1057
1058 /*
1059 * Force a routing table entry to the specified
1060 * destination to go through the given gateway.
1061 * Normally called as a result of a routing redirect
1062 * message from the network layer.
1063 */
1064 void
1065 rtredirect(struct ifnet *ifp, struct sockaddr *dst, struct sockaddr *gateway,
1066 struct sockaddr *netmask, int flags, struct sockaddr *src,
1067 struct rtentry **rtp)
1068 {
1069 struct rtentry *rt = NULL;
1070 int error = 0;
1071 short *stat = 0;
1072 struct rt_addrinfo info;
1073 struct ifaddr *ifa = NULL;
1074 unsigned int ifscope = (ifp != NULL) ? ifp->if_index : IFSCOPE_NONE;
1075 struct sockaddr_in sin;
1076
1077 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1078 lck_mtx_lock(rnh_lock);
1079
1080 /*
1081 * Verify the gateway is directly reachable; if scoped routing
1082 * is enabled, verify that it is reachable from the interface
1083 * where the ICMP redirect arrived on.
1084 */
1085 if ((ifa = ifa_ifwithnet_scoped(gateway, ifscope)) == NULL) {
1086 error = ENETUNREACH;
1087 goto out;
1088 }
1089
1090 /* Lookup route to the destination (from the original IP header) */
1091 rt = rtalloc1_scoped_locked(dst, 0, RTF_CLONING|RTF_PRCLONING, ifscope);
1092 if (rt != NULL)
1093 RT_LOCK(rt);
1094
1095 /* Embed scope in src for comparison against rt_gateway below */
1096 if (ip_doscopedroute && src->sa_family == AF_INET)
1097 src = sin_copy(SIN(src), &sin, ifscope);
1098
1099 /*
1100 * If the redirect isn't from our current router for this dst,
1101 * it's either old or wrong. If it redirects us to ourselves,
1102 * we have a routing loop, perhaps as a result of an interface
1103 * going down recently.
1104 */
1105 if (!(flags & RTF_DONE) && rt != NULL &&
1106 (!equal(src, rt->rt_gateway) || !equal(rt->rt_ifa->ifa_addr,
1107 ifa->ifa_addr))) {
1108 error = EINVAL;
1109 } else {
1110 ifafree(ifa);
1111 if ((ifa = ifa_ifwithaddr(gateway))) {
1112 ifafree(ifa);
1113 ifa = NULL;
1114 error = EHOSTUNREACH;
1115 }
1116 }
1117
1118 if (ifa) {
1119 ifafree(ifa);
1120 ifa = NULL;
1121 }
1122
1123 if (error) {
1124 if (rt != NULL)
1125 RT_UNLOCK(rt);
1126 goto done;
1127 }
1128
1129 /*
1130 * Create a new entry if we just got back a wildcard entry
1131 * or the the lookup failed. This is necessary for hosts
1132 * which use routing redirects generated by smart gateways
1133 * to dynamically build the routing tables.
1134 */
1135 if ((rt == NULL) || (rt_mask(rt) != NULL && rt_mask(rt)->sa_len < 2))
1136 goto create;
1137 /*
1138 * Don't listen to the redirect if it's
1139 * for a route to an interface.
1140 */
1141 RT_LOCK_ASSERT_HELD(rt);
1142 if (rt->rt_flags & RTF_GATEWAY) {
1143 if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
1144 /*
1145 * Changing from route to net => route to host.
1146 * Create new route, rather than smashing route
1147 * to net; similar to cloned routes, the newly
1148 * created host route is scoped as well.
1149 */
1150 create:
1151 if (rt != NULL)
1152 RT_UNLOCK(rt);
1153 flags |= RTF_GATEWAY | RTF_DYNAMIC;
1154 error = rtrequest_scoped_locked(RTM_ADD, dst,
1155 gateway, netmask, flags, NULL, ifscope);
1156 stat = &rtstat.rts_dynamic;
1157 } else {
1158 /*
1159 * Smash the current notion of the gateway to
1160 * this destination. Should check about netmask!!!
1161 */
1162 rt->rt_flags |= RTF_MODIFIED;
1163 flags |= RTF_MODIFIED;
1164 stat = &rtstat.rts_newgateway;
1165 /*
1166 * add the key and gateway (in one malloc'd chunk).
1167 */
1168 error = rt_setgate(rt, rt_key(rt), gateway);
1169 RT_UNLOCK(rt);
1170 }
1171 } else {
1172 RT_UNLOCK(rt);
1173 error = EHOSTUNREACH;
1174 }
1175 done:
1176 if (rt != NULL) {
1177 RT_LOCK_ASSERT_NOTHELD(rt);
1178 if (rtp && !error)
1179 *rtp = rt;
1180 else
1181 rtfree_locked(rt);
1182 }
1183 out:
1184 if (error) {
1185 rtstat.rts_badredirect++;
1186 } else {
1187 if (stat != NULL)
1188 (*stat)++;
1189 if (use_routegenid)
1190 routegenid_update();
1191 }
1192 lck_mtx_unlock(rnh_lock);
1193 bzero((caddr_t)&info, sizeof(info));
1194 info.rti_info[RTAX_DST] = dst;
1195 info.rti_info[RTAX_GATEWAY] = gateway;
1196 info.rti_info[RTAX_NETMASK] = netmask;
1197 info.rti_info[RTAX_AUTHOR] = src;
1198 rt_missmsg(RTM_REDIRECT, &info, flags, error);
1199 }
1200
1201 /*
1202 * Routing table ioctl interface.
1203 */
1204 int
1205 rtioctl(unsigned long req, caddr_t data, struct proc *p)
1206 {
1207 #pragma unused(p)
1208 #if INET && MROUTING
1209 return mrt_ioctl(req, data);
1210 #else
1211 #pragma unused(req)
1212 #pragma unused(data)
1213 return ENXIO;
1214 #endif
1215 }
1216
1217 struct ifaddr *
1218 ifa_ifwithroute(
1219 int flags,
1220 const struct sockaddr *dst,
1221 const struct sockaddr *gateway)
1222 {
1223 struct ifaddr *ifa;
1224
1225 lck_mtx_lock(rnh_lock);
1226 ifa = ifa_ifwithroute_locked(flags, dst, gateway);
1227 lck_mtx_unlock(rnh_lock);
1228
1229 return (ifa);
1230 }
1231
1232 struct ifaddr *
1233 ifa_ifwithroute_locked(int flags, const struct sockaddr *dst,
1234 const struct sockaddr *gateway)
1235 {
1236 return (ifa_ifwithroute_common_locked((flags & ~RTF_IFSCOPE), dst,
1237 gateway, IFSCOPE_NONE));
1238 }
1239
1240 struct ifaddr *
1241 ifa_ifwithroute_scoped_locked(int flags, const struct sockaddr *dst,
1242 const struct sockaddr *gateway, unsigned int ifscope)
1243 {
1244 if (ifscope != IFSCOPE_NONE)
1245 flags |= RTF_IFSCOPE;
1246 else
1247 flags &= ~RTF_IFSCOPE;
1248
1249 return (ifa_ifwithroute_common_locked(flags, dst, gateway, ifscope));
1250 }
1251
1252 static struct ifaddr *
1253 ifa_ifwithroute_common_locked(int flags, const struct sockaddr *dst,
1254 const struct sockaddr *gateway, unsigned int ifscope)
1255 {
1256 struct ifaddr *ifa = NULL;
1257 struct rtentry *rt = NULL;
1258 struct sockaddr_in dst_in, gw_in;
1259
1260 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1261
1262 if (ip_doscopedroute) {
1263 /*
1264 * Just in case the sockaddr passed in by the caller
1265 * contains embedded scope, make sure to clear it since
1266 * IPv4 interface addresses aren't scoped.
1267 */
1268 if (dst != NULL && dst->sa_family == AF_INET)
1269 dst = sin_copy(SIN(dst), &dst_in, IFSCOPE_NONE);
1270 if (gateway != NULL && gateway->sa_family == AF_INET)
1271 gateway = sin_copy(SIN(gateway), &gw_in, IFSCOPE_NONE);
1272 }
1273
1274 if (!(flags & RTF_GATEWAY)) {
1275 /*
1276 * If we are adding a route to an interface,
1277 * and the interface is a pt to pt link
1278 * we should search for the destination
1279 * as our clue to the interface. Otherwise
1280 * we can use the local address.
1281 */
1282 if (flags & RTF_HOST) {
1283 ifa = ifa_ifwithdstaddr(dst);
1284 }
1285 if (ifa == NULL)
1286 ifa = ifa_ifwithaddr_scoped(gateway, ifscope);
1287 } else {
1288 /*
1289 * If we are adding a route to a remote net
1290 * or host, the gateway may still be on the
1291 * other end of a pt to pt link.
1292 */
1293 ifa = ifa_ifwithdstaddr(gateway);
1294 }
1295 if (ifa == NULL)
1296 ifa = ifa_ifwithnet_scoped(gateway, ifscope);
1297 if (ifa == NULL) {
1298 /* Workaround to avoid gcc warning regarding const variable */
1299 rt = rtalloc1_scoped_locked((struct sockaddr *)(size_t)dst,
1300 0, 0, ifscope);
1301 if (rt != NULL) {
1302 RT_LOCK_SPIN(rt);
1303 ifa = rt->rt_ifa;
1304 if (ifa != NULL)
1305 ifaref(ifa);
1306 RT_REMREF_LOCKED(rt);
1307 RT_UNLOCK(rt);
1308 rt = NULL;
1309 }
1310 }
1311 if (ifa != NULL && ifa->ifa_addr->sa_family != dst->sa_family) {
1312 struct ifaddr *newifa;
1313 /* Callee adds reference to newifa upon success */
1314 newifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
1315 if (newifa != NULL) {
1316 ifafree(ifa);
1317 ifa = newifa;
1318 }
1319 }
1320 /*
1321 * If we are adding a gateway, it is quite possible that the
1322 * routing table has a static entry in place for the gateway,
1323 * that may not agree with info garnered from the interfaces.
1324 * The routing table should carry more precedence than the
1325 * interfaces in this matter. Must be careful not to stomp
1326 * on new entries from rtinit, hence (ifa->ifa_addr != gateway).
1327 */
1328 if ((ifa == NULL ||
1329 !equal(ifa->ifa_addr, (struct sockaddr *)(size_t)gateway)) &&
1330 (rt = rtalloc1_scoped_locked((struct sockaddr *)(size_t)gateway,
1331 0, 0, ifscope)) != NULL) {
1332 if (ifa != NULL)
1333 ifafree(ifa);
1334 RT_LOCK_SPIN(rt);
1335 ifa = rt->rt_ifa;
1336 if (ifa != NULL)
1337 ifaref(ifa);
1338 RT_REMREF_LOCKED(rt);
1339 RT_UNLOCK(rt);
1340 }
1341 /*
1342 * If an interface scope was specified, the interface index of
1343 * the found ifaddr must be equivalent to that of the scope;
1344 * otherwise there is no match.
1345 */
1346 if ((flags & RTF_IFSCOPE) &&
1347 ifa != NULL && ifa->ifa_ifp->if_index != ifscope) {
1348 ifafree(ifa);
1349 ifa = NULL;
1350 }
1351
1352 return (ifa);
1353 }
1354
1355 static int rt_fixdelete(struct radix_node *, void *);
1356 static int rt_fixchange(struct radix_node *, void *);
1357
1358 struct rtfc_arg {
1359 struct rtentry *rt0;
1360 struct radix_node_head *rnh;
1361 };
1362
1363 int
1364 rtrequest_locked(int req, struct sockaddr *dst, struct sockaddr *gateway,
1365 struct sockaddr *netmask, int flags, struct rtentry **ret_nrt)
1366 {
1367 return (rtrequest_common_locked(req, dst, gateway, netmask,
1368 (flags & ~RTF_IFSCOPE), ret_nrt, IFSCOPE_NONE));
1369 }
1370
1371 int
1372 rtrequest_scoped_locked(int req, struct sockaddr *dst,
1373 struct sockaddr *gateway, struct sockaddr *netmask, int flags,
1374 struct rtentry **ret_nrt, unsigned int ifscope)
1375 {
1376 if (ifscope != IFSCOPE_NONE)
1377 flags |= RTF_IFSCOPE;
1378 else
1379 flags &= ~RTF_IFSCOPE;
1380
1381 return (rtrequest_common_locked(req, dst, gateway, netmask,
1382 flags, ret_nrt, ifscope));
1383 }
1384
1385 /*
1386 * Do appropriate manipulations of a routing tree given all the bits of
1387 * info needed.
1388 *
1389 * Embedding the scope in the radix key is an internal job that should be
1390 * left to routines in this module. Callers should specify the scope value
1391 * to the "scoped" variants of route routines instead of manipulating the
1392 * key itself. This is typically done when creating a scoped route, e.g.
1393 * rtrequest(RTM_ADD). Once such a route is created and marked with the
1394 * RTF_IFSCOPE flag, callers can simply use its rt_key(rt) to clone it
1395 * (RTM_RESOLVE) or to remove it (RTM_DELETE). An exception to this is
1396 * during certain routing socket operations where the search key might be
1397 * derived from the routing message itself, in which case the caller must
1398 * specify the destination address and scope value for RTM_ADD/RTM_DELETE.
1399 */
1400 static int
1401 rtrequest_common_locked(int req, struct sockaddr *dst0,
1402 struct sockaddr *gateway, struct sockaddr *netmask, int flags,
1403 struct rtentry **ret_nrt, unsigned int ifscope)
1404 {
1405 int error = 0;
1406 struct rtentry *rt;
1407 struct radix_node *rn;
1408 struct radix_node_head *rnh;
1409 struct ifaddr *ifa = NULL;
1410 struct sockaddr *ndst, *dst = dst0;
1411 struct sockaddr_in sin, mask;
1412 #define senderr(x) { error = x ; goto bad; }
1413
1414 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1415 /*
1416 * Find the correct routing tree to use for this Address Family
1417 */
1418 if ((rnh = rt_tables[dst->sa_family]) == 0)
1419 senderr(ESRCH);
1420 /*
1421 * If we are adding a host route then we don't want to put
1422 * a netmask in the tree
1423 */
1424 if (flags & RTF_HOST)
1425 netmask = 0;
1426
1427 /*
1428 * If RTF_IFSCOPE is specified, use a local copy of the destination
1429 * address to embed the scope into. This logic is repeated below
1430 * in the RTM_RESOLVE handler since the caller does not normally
1431 * specify such a flag during a resolve; instead it passes in the
1432 * route used for cloning for which the scope info is derived from.
1433 * Note also that in the case of RTM_DELETE, the address passed in
1434 * by the caller might already contain the embedded scope info when
1435 * it is the key itself, thus making RTF_IFSCOPE unnecessary; one
1436 * instance where it is explicitly set is inside route_output()
1437 * as part of handling a routing socket request.
1438 */
1439 if (req != RTM_RESOLVE && (flags & RTF_IFSCOPE)) {
1440 /* Scoped routing is for AF_INET only */
1441 if (dst->sa_family != AF_INET ||
1442 (req == RTM_ADD && !ip_doscopedroute))
1443 senderr(EINVAL);
1444
1445 if (ifscope == IFSCOPE_NONE) {
1446 flags &= ~RTF_IFSCOPE;
1447 } else {
1448 /* Embed ifscope into the key (local copy) */
1449 dst = sin_copy(SIN(dst), &sin, ifscope);
1450
1451 /* Embed ifscope into netmask (local copy) */
1452 if (netmask != NULL)
1453 netmask = mask_copy(netmask, &mask, ifscope);
1454 }
1455 }
1456
1457 switch (req) {
1458 case RTM_DELETE:
1459 /*
1460 * Remove the item from the tree and return it.
1461 * Complain if it is not there and do no more processing.
1462 */
1463 if ((rn = rnh->rnh_deladdr(dst, netmask, rnh)) == 0)
1464 senderr(ESRCH);
1465 if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1466 panic ("rtrequest delete");
1467 rt = (struct rtentry *)rn;
1468
1469 /*
1470 * Take an extra reference to handle the deletion of a route
1471 * entry whose reference count is already 0; e.g. an expiring
1472 * cloned route entry or an entry that was added to the table
1473 * with 0 reference. If the caller is interested in this route,
1474 * we will return it with the reference intact. Otherwise we
1475 * will decrement the reference via rtfree_locked() and then
1476 * possibly deallocate it.
1477 */
1478 RT_LOCK(rt);
1479 RT_ADDREF_LOCKED(rt);
1480 rt->rt_flags &= ~RTF_UP;
1481
1482 /*
1483 * For consistency, in case the caller didn't set the flag.
1484 */
1485 rt->rt_flags |= RTF_CONDEMNED;
1486
1487 /*
1488 * Now search what's left of the subtree for any cloned
1489 * routes which might have been formed from this node.
1490 */
1491 if ((rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) &&
1492 rt_mask(rt)) {
1493 RT_UNLOCK(rt);
1494 rnh->rnh_walktree_from(rnh, dst, rt_mask(rt),
1495 rt_fixdelete, rt);
1496 RT_LOCK(rt);
1497 }
1498
1499 /*
1500 * Remove any external references we may have.
1501 * This might result in another rtentry being freed if
1502 * we held its last reference.
1503 */
1504 if (rt->rt_gwroute != NULL) {
1505 rtfree_locked(rt->rt_gwroute);
1506 rt->rt_gwroute = NULL;
1507 }
1508
1509 /*
1510 * give the protocol a chance to keep things in sync.
1511 */
1512 if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
1513 ifa->ifa_rtrequest(RTM_DELETE, rt, SA(0));
1514 ifa = NULL;
1515
1516 /*
1517 * one more rtentry floating around that is not
1518 * linked to the routing table.
1519 */
1520 (void) OSIncrementAtomic(&rttrash);
1521 if (rte_debug & RTD_DEBUG) {
1522 TAILQ_INSERT_TAIL(&rttrash_head,
1523 (struct rtentry_dbg *)rt, rtd_trash_link);
1524 }
1525
1526 /*
1527 * If this is the (non-scoped) default route, clear
1528 * the interface index used for the primary ifscope.
1529 */
1530 if (rt_inet_default(rt, rt_key(rt)))
1531 set_primary_ifscope(IFSCOPE_NONE);
1532
1533 RT_UNLOCK(rt);
1534
1535 /*
1536 * If the caller wants it, then it can have it,
1537 * but it's up to it to free the rtentry as we won't be
1538 * doing it.
1539 */
1540 if (ret_nrt != NULL) {
1541 /* Return the route to caller with reference intact */
1542 *ret_nrt = rt;
1543 } else {
1544 /* Dereference or deallocate the route */
1545 rtfree_locked(rt);
1546 }
1547 break;
1548
1549 case RTM_RESOLVE:
1550 if (ret_nrt == 0 || (rt = *ret_nrt) == 0)
1551 senderr(EINVAL);
1552 /*
1553 * If cloning, we have the parent route given by the caller
1554 * and will use its rt_gateway, rt_rmx as part of the cloning
1555 * process below. Since rnh_lock is held at this point, the
1556 * parent's rt_ifa and rt_gateway will not change, and its
1557 * relevant rt_flags will not change as well. The only thing
1558 * that could change are the metrics, and thus we hold the
1559 * parent route's rt_lock later on during the actual copying
1560 * of rt_rmx.
1561 */
1562 ifa = rt->rt_ifa;
1563 ifaref(ifa);
1564 flags = rt->rt_flags &
1565 ~(RTF_CLONING | RTF_PRCLONING | RTF_STATIC);
1566 flags |= RTF_WASCLONED;
1567 gateway = rt->rt_gateway;
1568 if ((netmask = rt->rt_genmask) == 0)
1569 flags |= RTF_HOST;
1570
1571 if (!ip_doscopedroute || dst->sa_family != AF_INET)
1572 goto makeroute;
1573 /*
1574 * When scoped routing is enabled, cloned entries are
1575 * always scoped according to the interface portion of
1576 * the parent route. The exception to this are IPv4
1577 * link local addresses.
1578 */
1579 if (!IN_LINKLOCAL(ntohl(SIN(dst)->sin_addr.s_addr))) {
1580 if (flags & RTF_IFSCOPE) {
1581 ifscope = sa_get_ifscope(rt_key(rt));
1582 } else {
1583 ifscope = rt->rt_ifp->if_index;
1584 flags |= RTF_IFSCOPE;
1585 }
1586 } else {
1587 ifscope = IFSCOPE_NONE;
1588 flags &= ~RTF_IFSCOPE;
1589 }
1590
1591 /* Embed or clear ifscope into/from the key (local copy) */
1592 dst = sin_copy(SIN(dst), &sin, ifscope);
1593
1594 /* Embed or clear ifscope into/from netmask (local copy) */
1595 if (netmask != NULL)
1596 netmask = mask_copy(netmask, &mask, ifscope);
1597
1598 goto makeroute;
1599
1600 case RTM_ADD:
1601 if ((flags & RTF_GATEWAY) && !gateway)
1602 panic("rtrequest: RTF_GATEWAY but no gateway");
1603
1604 if (flags & RTF_IFSCOPE) {
1605 ifa = ifa_ifwithroute_scoped_locked(flags, dst0,
1606 gateway, ifscope);
1607 } else {
1608 ifa = ifa_ifwithroute_locked(flags, dst0, gateway);
1609 }
1610 if (ifa == NULL)
1611 senderr(ENETUNREACH);
1612 makeroute:
1613 if ((rt = rte_alloc()) == NULL)
1614 senderr(ENOBUFS);
1615 Bzero(rt, sizeof(*rt));
1616 rte_lock_init(rt);
1617 RT_LOCK(rt);
1618 rt->rt_flags = RTF_UP | flags;
1619
1620 /*
1621 * Add the gateway. Possibly re-malloc-ing the storage for it
1622 * also add the rt_gwroute if possible.
1623 */
1624 if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1625 RT_UNLOCK(rt);
1626 rte_lock_destroy(rt);
1627 rte_free(rt);
1628 senderr(error);
1629 }
1630
1631 /*
1632 * point to the (possibly newly malloc'd) dest address.
1633 */
1634 ndst = rt_key(rt);
1635
1636 /*
1637 * make sure it contains the value we want (masked if needed).
1638 */
1639 if (netmask)
1640 rt_maskedcopy(dst, ndst, netmask);
1641 else
1642 Bcopy(dst, ndst, dst->sa_len);
1643
1644 /*
1645 * Note that we now have a reference to the ifa.
1646 * This moved from below so that rnh->rnh_addaddr() can
1647 * examine the ifa and ifa->ifa_ifp if it so desires.
1648 */
1649 rtsetifa(rt, ifa);
1650 rt->rt_ifp = rt->rt_ifa->ifa_ifp;
1651
1652 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1653
1654 rn = rnh->rnh_addaddr((caddr_t)ndst, (caddr_t)netmask,
1655 rnh, rt->rt_nodes);
1656 if (rn == 0) {
1657 struct rtentry *rt2;
1658 /*
1659 * Uh-oh, we already have one of these in the tree.
1660 * We do a special hack: if the route that's already
1661 * there was generated by the protocol-cloning
1662 * mechanism, then we just blow it away and retry
1663 * the insertion of the new one.
1664 */
1665 if (flags & RTF_IFSCOPE) {
1666 rt2 = rtalloc1_scoped_locked(dst0, 0,
1667 RTF_CLONING | RTF_PRCLONING, ifscope);
1668 } else {
1669 rt2 = rtalloc1_locked(dst, 0,
1670 RTF_CLONING | RTF_PRCLONING);
1671 }
1672 if (rt2 && rt2->rt_parent) {
1673 /*
1674 * rnh_lock is held here, so rt_key and
1675 * rt_gateway of rt2 will not change.
1676 */
1677 (void) rtrequest_locked(RTM_DELETE, rt_key(rt2),
1678 rt2->rt_gateway, rt_mask(rt2),
1679 rt2->rt_flags, 0);
1680 rtfree_locked(rt2);
1681 rn = rnh->rnh_addaddr((caddr_t)ndst,
1682 (caddr_t)netmask,
1683 rnh, rt->rt_nodes);
1684 } else if (rt2) {
1685 /* undo the extra ref we got */
1686 rtfree_locked(rt2);
1687 }
1688 }
1689
1690 /*
1691 * If it still failed to go into the tree,
1692 * then un-make it (this should be a function)
1693 */
1694 if (rn == 0) {
1695 if (rt->rt_gwroute) {
1696 rtfree_locked(rt->rt_gwroute);
1697 rt->rt_gwroute = NULL;
1698 }
1699 if (rt->rt_ifa) {
1700 ifafree(rt->rt_ifa);
1701 rt->rt_ifa = NULL;
1702 }
1703 R_Free(rt_key(rt));
1704 RT_UNLOCK(rt);
1705 rte_lock_destroy(rt);
1706 rte_free(rt);
1707 senderr(EEXIST);
1708 }
1709
1710 rt->rt_parent = 0;
1711
1712 /*
1713 * If we got here from RESOLVE, then we are cloning so clone
1714 * the rest, and note that we are a clone (and increment the
1715 * parent's references). rnh_lock is still held, which prevents
1716 * a lookup from returning the newly-created route. Hence
1717 * holding and releasing the parent's rt_lock while still
1718 * holding the route's rt_lock is safe since the new route
1719 * is not yet externally visible.
1720 */
1721 if (req == RTM_RESOLVE) {
1722 RT_LOCK_SPIN(*ret_nrt);
1723 rt->rt_rmx = (*ret_nrt)->rt_rmx; /* copy metrics */
1724 if ((*ret_nrt)->rt_flags & (RTF_CLONING | RTF_PRCLONING)) {
1725 rt->rt_parent = (*ret_nrt);
1726 RT_ADDREF_LOCKED(*ret_nrt);
1727 }
1728 RT_UNLOCK(*ret_nrt);
1729 }
1730
1731 /*
1732 * if this protocol has something to add to this then
1733 * allow it to do that as well.
1734 */
1735 if (ifa->ifa_rtrequest)
1736 ifa->ifa_rtrequest(req, rt, SA(ret_nrt ? *ret_nrt : 0));
1737 ifafree(ifa);
1738 ifa = 0;
1739
1740 /*
1741 * If this is the (non-scoped) default route, record
1742 * the interface index used for the primary ifscope.
1743 */
1744 if (rt_inet_default(rt, rt_key(rt)))
1745 set_primary_ifscope(rt->rt_ifp->if_index);
1746
1747 /*
1748 * actually return a resultant rtentry and
1749 * give the caller a single reference.
1750 */
1751 if (ret_nrt) {
1752 *ret_nrt = rt;
1753 RT_ADDREF_LOCKED(rt);
1754 }
1755
1756 /*
1757 * We repeat the same procedure from rt_setgate() here because
1758 * it doesn't fire when we call it there because the node
1759 * hasn't been added to the tree yet.
1760 */
1761 if (req == RTM_ADD &&
1762 !(rt->rt_flags & RTF_HOST) && rt_mask(rt) != 0) {
1763 struct rtfc_arg arg;
1764 arg.rnh = rnh;
1765 arg.rt0 = rt;
1766 RT_UNLOCK(rt);
1767 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
1768 rt_fixchange, &arg);
1769 } else {
1770 RT_UNLOCK(rt);
1771 }
1772 break;
1773 }
1774 bad:
1775 if (ifa)
1776 ifafree(ifa);
1777 return (error);
1778 }
1779
1780 int
1781 rtrequest(
1782 int req,
1783 struct sockaddr *dst,
1784 struct sockaddr *gateway,
1785 struct sockaddr *netmask,
1786 int flags,
1787 struct rtentry **ret_nrt)
1788 {
1789 int error;
1790 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1791 lck_mtx_lock(rnh_lock);
1792 error = rtrequest_locked(req, dst, gateway, netmask, flags, ret_nrt);
1793 lck_mtx_unlock(rnh_lock);
1794 return (error);
1795 }
1796 /*
1797 * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
1798 * (i.e., the routes related to it by the operation of cloning). This
1799 * routine is iterated over all potential former-child-routes by way of
1800 * rnh->rnh_walktree_from() above, and those that actually are children of
1801 * the late parent (passed in as VP here) are themselves deleted.
1802 */
1803 static int
1804 rt_fixdelete(struct radix_node *rn, void *vp)
1805 {
1806 struct rtentry *rt = (struct rtentry *)rn;
1807 struct rtentry *rt0 = vp;
1808
1809 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1810
1811 RT_LOCK(rt);
1812 if (rt->rt_parent == rt0 &&
1813 !(rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1814 /*
1815 * Safe to drop rt_lock and use rt_key, since holding
1816 * rnh_lock here prevents another thread from calling
1817 * rt_setgate() on this route.
1818 */
1819 RT_UNLOCK(rt);
1820 return (rtrequest_locked(RTM_DELETE, rt_key(rt), NULL,
1821 rt_mask(rt), rt->rt_flags, NULL));
1822 }
1823 RT_UNLOCK(rt);
1824 return 0;
1825 }
1826
1827 /*
1828 * This routine is called from rt_setgate() to do the analogous thing for
1829 * adds and changes. There is the added complication in this case of a
1830 * middle insert; i.e., insertion of a new network route between an older
1831 * network route and (cloned) host routes. For this reason, a simple check
1832 * of rt->rt_parent is insufficient; each candidate route must be tested
1833 * against the (mask, value) of the new route (passed as before in vp)
1834 * to see if the new route matches it.
1835 *
1836 * XXX - it may be possible to do fixdelete() for changes and reserve this
1837 * routine just for adds. I'm not sure why I thought it was necessary to do
1838 * changes this way.
1839 */
1840 static int
1841 rt_fixchange(struct radix_node *rn, void *vp)
1842 {
1843 struct rtentry *rt = (struct rtentry *)rn;
1844 struct rtfc_arg *ap = vp;
1845 struct rtentry *rt0 = ap->rt0;
1846 struct radix_node_head *rnh = ap->rnh;
1847 u_char *xk1, *xm1, *xk2, *xmp;
1848 int i, len;
1849
1850 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1851
1852 RT_LOCK(rt);
1853
1854 if (!rt->rt_parent ||
1855 (rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1856 RT_UNLOCK(rt);
1857 return (0);
1858 }
1859
1860 if (rt->rt_parent == rt0)
1861 goto delete_rt;
1862
1863 /*
1864 * There probably is a function somewhere which does this...
1865 * if not, there should be.
1866 */
1867 len = imin(rt_key(rt0)->sa_len, rt_key(rt)->sa_len);
1868
1869 xk1 = (u_char *)rt_key(rt0);
1870 xm1 = (u_char *)rt_mask(rt0);
1871 xk2 = (u_char *)rt_key(rt);
1872
1873 /*
1874 * Avoid applying a less specific route; do this only if the parent
1875 * route (rt->rt_parent) is a network route, since otherwise its mask
1876 * will be NULL if it is a cloning host route.
1877 */
1878 if ((xmp = (u_char *)rt_mask(rt->rt_parent)) != NULL) {
1879 int mlen = rt_mask(rt->rt_parent)->sa_len;
1880 if (mlen > rt_mask(rt0)->sa_len) {
1881 RT_UNLOCK(rt);
1882 return (0);
1883 }
1884
1885 for (i = rnh->rnh_treetop->rn_offset; i < mlen; i++) {
1886 if ((xmp[i] & ~(xmp[i] ^ xm1[i])) != xmp[i]) {
1887 RT_UNLOCK(rt);
1888 return (0);
1889 }
1890 }
1891 }
1892
1893 for (i = rnh->rnh_treetop->rn_offset; i < len; i++) {
1894 if ((xk2[i] & xm1[i]) != xk1[i]) {
1895 RT_UNLOCK(rt);
1896 return (0);
1897 }
1898 }
1899
1900 /*
1901 * OK, this node is a clone, and matches the node currently being
1902 * changed/added under the node's mask. So, get rid of it.
1903 */
1904 delete_rt:
1905 /*
1906 * Safe to drop rt_lock and use rt_key, since holding rnh_lock here
1907 * prevents another thread from calling rt_setgate() on this route.
1908 */
1909 RT_UNLOCK(rt);
1910 return (rtrequest_locked(RTM_DELETE, rt_key(rt), NULL,
1911 rt_mask(rt), rt->rt_flags, NULL));
1912 }
1913
1914 /*
1915 * Round up sockaddr len to multiples of 32-bytes. This will reduce
1916 * or even eliminate the need to re-allocate the chunk of memory used
1917 * for rt_key and rt_gateway in the event the gateway portion changes.
1918 * Certain code paths (e.g. IPSec) are notorious for caching the address
1919 * of rt_gateway; this rounding-up would help ensure that the gateway
1920 * portion never gets deallocated (though it may change contents) and
1921 * thus greatly simplifies things.
1922 */
1923 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
1924
1925 /*
1926 * Sets the gateway and/or gateway route portion of a route; may be
1927 * called on an existing route to modify the gateway portion. Both
1928 * rt_key and rt_gateway are allocated out of the same memory chunk.
1929 * Route entry lock must be held by caller; this routine will return
1930 * with the lock held.
1931 */
1932 int
1933 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1934 {
1935 int dlen = SA_SIZE(dst->sa_len), glen = SA_SIZE(gate->sa_len);
1936 struct radix_node_head *rnh = rt_tables[dst->sa_family];
1937
1938 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
1939 RT_LOCK_ASSERT_HELD(rt);
1940
1941 /*
1942 * If this is for a route that is on its way of being removed,
1943 * or is temporarily frozen, reject the modification request.
1944 */
1945 if (rt->rt_flags & RTF_CONDEMNED)
1946 return (EBUSY);
1947
1948 /* Add an extra ref for ourselves */
1949 RT_ADDREF_LOCKED(rt);
1950
1951 /*
1952 * A host route with the destination equal to the gateway
1953 * will interfere with keeping LLINFO in the routing
1954 * table, so disallow it.
1955 */
1956 if (((rt->rt_flags & (RTF_HOST|RTF_GATEWAY|RTF_LLINFO)) ==
1957 (RTF_HOST|RTF_GATEWAY)) && (dst->sa_len == gate->sa_len) &&
1958 (bcmp(dst, gate, dst->sa_len) == 0)) {
1959 /*
1960 * The route might already exist if this is an RTM_CHANGE
1961 * or a routing redirect, so try to delete it.
1962 */
1963 if (rt_key(rt) != NULL) {
1964 /*
1965 * Safe to drop rt_lock and use rt_key, rt_gateway,
1966 * since holding rnh_lock here prevents another thread
1967 * from calling rt_setgate() on this route.
1968 */
1969 RT_UNLOCK(rt);
1970 (void) rtrequest_locked(RTM_DELETE, rt_key(rt),
1971 rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
1972 RT_LOCK(rt);
1973 }
1974 /* Release extra ref */
1975 RT_REMREF_LOCKED(rt);
1976 return (EADDRNOTAVAIL);
1977 }
1978
1979 /*
1980 * The destination is not directly reachable. Get a route
1981 * to the next-hop gateway and store it in rt_gwroute.
1982 */
1983 if (rt->rt_flags & RTF_GATEWAY) {
1984 struct rtentry *gwrt;
1985 unsigned int ifscope;
1986
1987 ifscope = (dst->sa_family == AF_INET) ?
1988 sa_get_ifscope(dst) : IFSCOPE_NONE;
1989
1990 RT_UNLOCK(rt);
1991 gwrt = rtalloc1_scoped_locked(gate, 1, RTF_PRCLONING, ifscope);
1992 if (gwrt != NULL)
1993 RT_LOCK_ASSERT_NOTHELD(gwrt);
1994 RT_LOCK(rt);
1995
1996 /*
1997 * Cloning loop avoidance:
1998 *
1999 * In the presence of protocol-cloning and bad configuration,
2000 * it is possible to get stuck in bottomless mutual recursion
2001 * (rtrequest rt_setgate rtalloc1). We avoid this by not
2002 * allowing protocol-cloning to operate for gateways (which
2003 * is probably the correct choice anyway), and avoid the
2004 * resulting reference loops by disallowing any route to run
2005 * through itself as a gateway. This is obviously mandatory
2006 * when we get rt->rt_output(). It implies that a route to
2007 * the gateway must already be present in the system in order
2008 * for the gateway to be referred to by another route.
2009 */
2010 if (gwrt == rt) {
2011 RT_REMREF_LOCKED(gwrt);
2012 /* Release extra ref */
2013 RT_REMREF_LOCKED(rt);
2014 return (EADDRINUSE); /* failure */
2015 }
2016
2017 /*
2018 * If scoped, the gateway route must use the same interface;
2019 * we're holding rnh_lock now, so rt_gateway and rt_ifp of gwrt
2020 * should not change and are freely accessible.
2021 */
2022 if (ifscope != IFSCOPE_NONE && (rt->rt_flags & RTF_IFSCOPE) &&
2023 gwrt != NULL && gwrt->rt_ifp != NULL &&
2024 gwrt->rt_ifp->if_index != ifscope) {
2025 rtfree_locked(gwrt); /* rt != gwrt, no deadlock */
2026 /* Release extra ref */
2027 RT_REMREF_LOCKED(rt);
2028 return ((rt->rt_flags & RTF_HOST) ?
2029 EHOSTUNREACH : ENETUNREACH);
2030 }
2031
2032 /* Check again since we dropped the lock above */
2033 if (rt->rt_flags & RTF_CONDEMNED) {
2034 if (gwrt != NULL)
2035 rtfree_locked(gwrt);
2036 /* Release extra ref */
2037 RT_REMREF_LOCKED(rt);
2038 return (EBUSY);
2039 }
2040
2041 if (rt->rt_gwroute != NULL)
2042 rtfree_locked(rt->rt_gwroute);
2043 rt->rt_gwroute = gwrt;
2044
2045 /*
2046 * In case the (non-scoped) default route gets modified via
2047 * an ICMP redirect, record the interface index used for the
2048 * primary ifscope. Also done in rt_setif() to take care
2049 * of the non-redirect cases.
2050 */
2051 if (rt_inet_default(rt, dst) && rt->rt_ifp != NULL)
2052 set_primary_ifscope(rt->rt_ifp->if_index);
2053
2054 /*
2055 * Tell the kernel debugger about the new default gateway
2056 * if the gateway route uses the primary interface, or
2057 * if we are in a transient state before the non-scoped
2058 * default gateway is installed (similar to how the system
2059 * was behaving in the past). In future, it would be good
2060 * to do all this only when KDP is enabled.
2061 */
2062 if ((dst->sa_family == AF_INET) &&
2063 gwrt != NULL && gwrt->rt_gateway->sa_family == AF_LINK &&
2064 (gwrt->rt_ifp->if_index == get_primary_ifscope() ||
2065 get_primary_ifscope() == IFSCOPE_NONE))
2066 kdp_set_gateway_mac(SDL(gwrt->rt_gateway)->sdl_data);
2067 }
2068
2069 /*
2070 * Prepare to store the gateway in rt_gateway. Both dst and gateway
2071 * are stored one after the other in the same malloc'd chunk. If we
2072 * have room, reuse the old buffer since rt_gateway already points
2073 * to the right place. Otherwise, malloc a new block and update
2074 * the 'dst' address and point rt_gateway to the right place.
2075 */
2076 if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway->sa_len)) {
2077 caddr_t new;
2078
2079 /* The underlying allocation is done with M_WAITOK set */
2080 R_Malloc(new, caddr_t, dlen + glen);
2081 if (new == NULL) {
2082 if (rt->rt_gwroute != NULL)
2083 rtfree_locked(rt->rt_gwroute);
2084 rt->rt_gwroute = NULL;
2085 /* Release extra ref */
2086 RT_REMREF_LOCKED(rt);
2087 return (ENOBUFS);
2088 }
2089
2090 /*
2091 * Copy from 'dst' and not rt_key(rt) because we can get
2092 * here to initialize a newly allocated route entry, in
2093 * which case rt_key(rt) is NULL (and so does rt_gateway).
2094 */
2095 bzero(new, dlen + glen);
2096 Bcopy(dst, new, dst->sa_len);
2097 R_Free(rt_key(rt)); /* free old block; NULL is okay */
2098 rt->rt_nodes->rn_key = new;
2099 rt->rt_gateway = (struct sockaddr *)(new + dlen);
2100 }
2101
2102 /*
2103 * Copy the new gateway value into the memory chunk.
2104 */
2105 Bcopy(gate, rt->rt_gateway, gate->sa_len);
2106
2107 /*
2108 * For consistency between rt_gateway and rt_key(gwrt).
2109 */
2110 if ((rt->rt_flags & RTF_GATEWAY) && rt->rt_gwroute != NULL &&
2111 (rt->rt_gwroute->rt_flags & RTF_IFSCOPE) &&
2112 rt->rt_gateway->sa_family == AF_INET &&
2113 rt_key(rt->rt_gwroute)->sa_family == AF_INET) {
2114 sa_set_ifscope(rt->rt_gateway,
2115 sa_get_ifscope(rt_key(rt->rt_gwroute)));
2116 }
2117
2118 /*
2119 * This isn't going to do anything useful for host routes, so
2120 * don't bother. Also make sure we have a reasonable mask
2121 * (we don't yet have one during adds).
2122 */
2123 if (!(rt->rt_flags & RTF_HOST) && rt_mask(rt) != 0) {
2124 struct rtfc_arg arg;
2125 arg.rnh = rnh;
2126 arg.rt0 = rt;
2127 RT_UNLOCK(rt);
2128 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
2129 rt_fixchange, &arg);
2130 RT_LOCK(rt);
2131 }
2132
2133 /* Release extra ref */
2134 RT_REMREF_LOCKED(rt);
2135 return (0);
2136 }
2137
2138 #undef SA_SIZE
2139
2140 static void
2141 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst,
2142 struct sockaddr *netmask)
2143 {
2144 u_char *cp1 = (u_char *)src;
2145 u_char *cp2 = (u_char *)dst;
2146 u_char *cp3 = (u_char *)netmask;
2147 u_char *cplim = cp2 + *cp3;
2148 u_char *cplim2 = cp2 + *cp1;
2149
2150 *cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
2151 cp3 += 2;
2152 if (cplim > cplim2)
2153 cplim = cplim2;
2154 while (cp2 < cplim)
2155 *cp2++ = *cp1++ & *cp3++;
2156 if (cp2 < cplim2)
2157 bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
2158 }
2159
2160 /*
2161 * Lookup an AF_INET scoped or non-scoped route depending on the ifscope
2162 * value passed in by the caller (IFSCOPE_NONE implies non-scoped).
2163 */
2164 static struct radix_node *
2165 node_lookup(struct sockaddr *dst, struct sockaddr *netmask,
2166 unsigned int ifscope)
2167 {
2168 struct radix_node_head *rnh = rt_tables[AF_INET];
2169 struct radix_node *rn;
2170 struct sockaddr_in sin, mask;
2171 struct matchleaf_arg ma = { ifscope };
2172 rn_matchf_t *f = rn_match_ifscope;
2173 void *w = &ma;
2174
2175 if (dst->sa_family != AF_INET)
2176 return (NULL);
2177
2178 /*
2179 * Embed ifscope into the search key; for a non-scoped
2180 * search this will clear out any embedded scope value.
2181 */
2182 dst = sin_copy(SIN(dst), &sin, ifscope);
2183
2184 /* Embed (or clear) ifscope into netmask */
2185 if (netmask != NULL)
2186 netmask = mask_copy(netmask, &mask, ifscope);
2187
2188 if (ifscope == IFSCOPE_NONE)
2189 f = w = NULL;
2190
2191 rn = rnh->rnh_lookup_args(dst, netmask, rnh, f, w);
2192 if (rn != NULL && (rn->rn_flags & RNF_ROOT))
2193 rn = NULL;
2194
2195 return (rn);
2196 }
2197
2198 /*
2199 * Lookup the AF_INET non-scoped default route.
2200 */
2201 static struct radix_node *
2202 node_lookup_default(void)
2203 {
2204 struct radix_node_head *rnh = rt_tables[AF_INET];
2205 return (rnh->rnh_lookup(&sin_def, NULL, rnh));
2206 }
2207
2208 /*
2209 * Common routine to lookup/match a route. It invokes the lookup/matchaddr
2210 * callback which could be address family-specific. The main difference
2211 * between the two (at least for AF_INET/AF_INET6) is that a lookup does
2212 * not alter the expiring state of a route, whereas a match would unexpire
2213 * or revalidate the route.
2214 *
2215 * The optional scope or interface index property of a route allows for a
2216 * per-interface route instance. This permits multiple route entries having
2217 * the same destination (but not necessarily the same gateway) to exist in
2218 * the routing table; each of these entries is specific to the corresponding
2219 * interface. This is made possible by embedding the scope value into the
2220 * radix key, thus making each route entry unique. These scoped entries
2221 * exist along with the regular, non-scoped entries in the same radix tree
2222 * for a given address family (currently AF_INET only); the scope logically
2223 * partitions it into multiple per-interface sub-trees.
2224 *
2225 * When a scoped route lookup is performed, the routing table is searched for
2226 * the best match that would result in a route using the same interface as the
2227 * one associated with the scope (the exception to this are routes that point
2228 * to the loopback interface). The search rule follows the longest matching
2229 * prefix with the additional interface constraint.
2230 */
2231 struct rtentry *
2232 rt_lookup(boolean_t lookup_only, struct sockaddr *dst, struct sockaddr *netmask,
2233 struct radix_node_head *rnh, unsigned int ifscope)
2234 {
2235 struct radix_node *rn0, *rn;
2236 boolean_t dontcare = (ifscope == IFSCOPE_NONE);
2237
2238 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_OWNED);
2239
2240 if (!lookup_only)
2241 netmask = NULL;
2242
2243 /*
2244 * Non-scoped route lookup.
2245 */
2246 if (!ip_doscopedroute || dst->sa_family != AF_INET) {
2247 if (lookup_only)
2248 rn = rnh->rnh_lookup(dst, netmask, rnh);
2249 else
2250 rn = rnh->rnh_matchaddr(dst, rnh);
2251
2252 /*
2253 * Don't return a root node; also, rnh_matchaddr callback
2254 * would have done the necessary work to clear RTPRF_OURS
2255 * for certain protocol families.
2256 */
2257 if (rn != NULL && (rn->rn_flags & RNF_ROOT))
2258 rn = NULL;
2259 if (rn != NULL) {
2260 RT_LOCK_SPIN(RT(rn));
2261 if (!(RT(rn)->rt_flags & RTF_CONDEMNED)) {
2262 RT_ADDREF_LOCKED(RT(rn));
2263 RT_UNLOCK(RT(rn));
2264 } else {
2265 RT_UNLOCK(RT(rn));
2266 rn = NULL;
2267 }
2268 }
2269 return (RT(rn));
2270 }
2271
2272 /*
2273 * Scoped route lookup:
2274 *
2275 * We first perform a non-scoped lookup for the original result.
2276 * Afterwards, depending on whether or not the caller has specified
2277 * a scope, we perform a more specific scoped search and fallback
2278 * to this original result upon failure.
2279 */
2280 rn0 = rn = node_lookup(dst, netmask, IFSCOPE_NONE);
2281
2282 /*
2283 * If the caller did not specify a scope, use the primary scope
2284 * derived from the system's non-scoped default route. If, for
2285 * any reason, there is no primary interface, return what we have.
2286 */
2287 if (dontcare && (ifscope = get_primary_ifscope()) == IFSCOPE_NONE)
2288 goto done;
2289
2290 /*
2291 * Keep the original result if either of the following is true:
2292 *
2293 * 1) The interface portion of the route has the same interface
2294 * index as the scope value and it is marked with RTF_IFSCOPE.
2295 * 2) The route uses the loopback interface, in which case the
2296 * destination (host/net) is local/loopback.
2297 *
2298 * Otherwise, do a more specified search using the scope;
2299 * we're holding rnh_lock now, so rt_ifp should not change.
2300 */
2301 if (rn != NULL) {
2302 struct rtentry *rt = RT(rn);
2303 if (rt->rt_ifp != lo_ifp) {
2304 if (rt->rt_ifp->if_index != ifscope) {
2305 /*
2306 * Wrong interface; keep the original result
2307 * only if the caller did not specify a scope,
2308 * and do a more specific scoped search using
2309 * the scope of the found route. Otherwise,
2310 * start again from scratch.
2311 */
2312 rn = NULL;
2313 if (dontcare)
2314 ifscope = rt->rt_ifp->if_index;
2315 else
2316 rn0 = NULL;
2317 } else if (!(rt->rt_flags & RTF_IFSCOPE)) {
2318 /*
2319 * Right interface, except that this route
2320 * isn't marked with RTF_IFSCOPE. Do a more
2321 * specific scoped search. Keep the original
2322 * result and return it it in case the scoped
2323 * search fails.
2324 */
2325 rn = NULL;
2326 }
2327 }
2328 }
2329
2330 /*
2331 * Scoped search. Find the most specific entry having the same
2332 * interface scope as the one requested. The following will result
2333 * in searching for the longest prefix scoped match.
2334 */
2335 if (rn == NULL)
2336 rn = node_lookup(dst, netmask, ifscope);
2337
2338 /*
2339 * Use the original result if either of the following is true:
2340 *
2341 * 1) The scoped search did not yield any result.
2342 * 2) The result from the scoped search is a scoped default route,
2343 * and the original (non-scoped) result is not a default route,
2344 * i.e. the original result is a more specific host/net route.
2345 * 3) The scoped search yielded a net route but the original
2346 * result is a host route, i.e. the original result is treated
2347 * as a more specific route.
2348 */
2349 if (rn == NULL || (rn0 != NULL &&
2350 ((INET_DEFAULT(rt_key(RT(rn))) && !INET_DEFAULT(rt_key(RT(rn0)))) ||
2351 (!RT_HOST(rn) && RT_HOST(rn0)))))
2352 rn = rn0;
2353
2354 /*
2355 * If we still don't have a route, use the non-scoped default
2356 * route as long as the interface portion satistifes the scope.
2357 */
2358 if (rn == NULL && (rn = node_lookup_default()) != NULL &&
2359 RT(rn)->rt_ifp->if_index != ifscope)
2360 rn = NULL;
2361
2362 done:
2363 if (rn != NULL) {
2364 /*
2365 * Manually clear RTPRF_OURS using in_validate() and
2366 * bump up the reference count after, and not before;
2367 * we only get here for AF_INET. node_lookup() has
2368 * done the check against RNF_ROOT, so we can be sure
2369 * that we're not returning a root node here.
2370 */
2371 RT_LOCK_SPIN(RT(rn));
2372 if (!(RT(rn)->rt_flags & RTF_CONDEMNED)) {
2373 if (!lookup_only)
2374 (void) in_validate(rn);
2375 RT_ADDREF_LOCKED(RT(rn));
2376 RT_UNLOCK(RT(rn));
2377 } else {
2378 RT_UNLOCK(RT(rn));
2379 rn = NULL;
2380 }
2381 }
2382
2383 return (RT(rn));
2384 }
2385
2386 /*
2387 * Set up a routing table entry, normally
2388 * for an interface.
2389 */
2390 int
2391 rtinit(struct ifaddr *ifa, int cmd, int flags)
2392 {
2393 int error;
2394 lck_mtx_assert(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2395 lck_mtx_lock(rnh_lock);
2396 error = rtinit_locked(ifa, cmd, flags);
2397 lck_mtx_unlock(rnh_lock);
2398 return (error);
2399 }
2400
2401 int
2402 rtinit_locked(struct ifaddr *ifa, int cmd, int flags)
2403 {
2404 struct rtentry *rt;
2405 struct sockaddr *dst;
2406 struct sockaddr *deldst;
2407 struct mbuf *m = 0;
2408 struct rtentry *nrt = 0;
2409 int error;
2410
2411 dst = flags & RTF_HOST ? ifa->ifa_dstaddr : ifa->ifa_addr;
2412 /*
2413 * If it's a delete, check that if it exists, it's on the correct
2414 * interface or we might scrub a route to another ifa which would
2415 * be confusing at best and possibly worse.
2416 */
2417 if (cmd == RTM_DELETE) {
2418 /*
2419 * It's a delete, so it should already exist..
2420 * If it's a net, mask off the host bits
2421 * (Assuming we have a mask)
2422 */
2423 if ((flags & RTF_HOST) == 0 && ifa->ifa_netmask) {
2424 m = m_get(M_DONTWAIT, MT_SONAME);
2425 if (m == NULL) {
2426 return(ENOBUFS);
2427 }
2428 deldst = mtod(m, struct sockaddr *);
2429 rt_maskedcopy(dst, deldst, ifa->ifa_netmask);
2430 dst = deldst;
2431 }
2432 /*
2433 * Get an rtentry that is in the routing tree and
2434 * contains the correct info. (if this fails, can't get there).
2435 * We set "report" to FALSE so that if it doesn't exist,
2436 * it doesn't report an error or clone a route, etc. etc.
2437 */
2438 rt = rtalloc1_locked(dst, 0, 0);
2439 if (rt) {
2440 /*
2441 * Ok so we found the rtentry. it has an extra reference
2442 * for us at this stage. we won't need that so
2443 * lop that off now.
2444 */
2445 RT_LOCK_SPIN(rt);
2446 if (rt->rt_ifa != ifa) {
2447 RT_REMREF_LOCKED(rt);
2448 RT_UNLOCK(rt);
2449 /*
2450 * If the interface in the rtentry doesn't match
2451 * the interface we are using, then we don't
2452 * want to delete it, so return an error.
2453 * This seems to be the only point of
2454 * this whole RTM_DELETE clause.
2455 */
2456 if (m)
2457 (void) m_free(m);
2458 return (flags & RTF_HOST ? EHOSTUNREACH
2459 : ENETUNREACH);
2460 } else {
2461 RT_REMREF_LOCKED(rt);
2462 RT_UNLOCK(rt);
2463 }
2464 }
2465 /* XXX */
2466 #if 0
2467 else {
2468 /*
2469 * One would think that as we are deleting, and we know
2470 * it doesn't exist, we could just return at this point
2471 * with an "ELSE" clause, but apparently not..
2472 */
2473 lck_mtx_unlock(rnh_lock);
2474 return (flags & RTF_HOST ? EHOSTUNREACH
2475 : ENETUNREACH);
2476 }
2477 #endif
2478 }
2479 /*
2480 * Do the actual request
2481 */
2482 error = rtrequest_locked(cmd, dst, ifa->ifa_addr, ifa->ifa_netmask,
2483 flags | ifa->ifa_flags, &nrt);
2484 if (m)
2485 (void) m_free(m);
2486 /*
2487 * If we are deleting, and we found an entry, then
2488 * it's been removed from the tree.. now throw it away.
2489 */
2490 if (cmd == RTM_DELETE && error == 0 && (rt = nrt)) {
2491 /*
2492 * notify any listening routing agents of the change
2493 */
2494 RT_LOCK(rt);
2495 rt_newaddrmsg(cmd, ifa, error, nrt);
2496 if (use_routegenid)
2497 routegenid_update();
2498 RT_UNLOCK(rt);
2499 rtfree_locked(rt);
2500 }
2501
2502 /*
2503 * We are adding, and we have a returned routing entry.
2504 * We need to sanity check the result.
2505 */
2506 if (cmd == RTM_ADD && error == 0 && (rt = nrt)) {
2507 RT_LOCK(rt);
2508 /*
2509 * If it came back with an unexpected interface, then it must
2510 * have already existed or something. (XXX)
2511 */
2512 if (rt->rt_ifa != ifa) {
2513 if (!(rt->rt_ifa->ifa_ifp->if_flags &
2514 (IFF_POINTOPOINT|IFF_LOOPBACK)))
2515 printf("rtinit: wrong ifa (%p) was (%p)\n",
2516 ifa, rt->rt_ifa);
2517 /*
2518 * Ask that the protocol in question
2519 * remove anything it has associated with
2520 * this route and ifaddr.
2521 */
2522 if (rt->rt_ifa->ifa_rtrequest)
2523 rt->rt_ifa->ifa_rtrequest(RTM_DELETE, rt, SA(0));
2524 /*
2525 * Set the route's ifa.
2526 */
2527 rtsetifa(rt, ifa);
2528 /*
2529 * And substitute in references to the ifaddr
2530 * we are adding.
2531 */
2532 rt->rt_ifp = ifa->ifa_ifp;
2533 rt->rt_rmx.rmx_mtu = ifa->ifa_ifp->if_mtu; /*XXX*/
2534 /*
2535 * Now ask the protocol to check if it needs
2536 * any special processing in its new form.
2537 */
2538 if (ifa->ifa_rtrequest)
2539 ifa->ifa_rtrequest(RTM_ADD, rt, SA(0));
2540 }
2541 /*
2542 * notify any listenning routing agents of the change
2543 */
2544 rt_newaddrmsg(cmd, ifa, error, nrt);
2545 if (use_routegenid)
2546 routegenid_update();
2547 /*
2548 * We just wanted to add it; we don't actually need a
2549 * reference. This will result in a route that's added
2550 * to the routing table without a reference count. The
2551 * RTM_DELETE code will do the necessary step to adjust
2552 * the reference count at deletion time.
2553 */
2554 RT_REMREF_LOCKED(rt);
2555 RT_UNLOCK(rt);
2556 }
2557 return (error);
2558 }
2559
2560 static void
2561 rte_lock_init(struct rtentry *rt)
2562 {
2563 lck_mtx_init(&rt->rt_lock, rte_mtx_grp, rte_mtx_attr);
2564 }
2565
2566 static void
2567 rte_lock_destroy(struct rtentry *rt)
2568 {
2569 RT_LOCK_ASSERT_NOTHELD(rt);
2570 lck_mtx_destroy(&rt->rt_lock, rte_mtx_grp);
2571 }
2572
2573 void
2574 rt_lock(struct rtentry *rt, boolean_t spin)
2575 {
2576 RT_LOCK_ASSERT_NOTHELD(rt);
2577 if (spin)
2578 lck_mtx_lock_spin(&rt->rt_lock);
2579 else
2580 lck_mtx_lock(&rt->rt_lock);
2581 if (rte_debug & RTD_DEBUG)
2582 rte_lock_debug((struct rtentry_dbg *)rt);
2583 }
2584
2585 void
2586 rt_unlock(struct rtentry *rt)
2587 {
2588 RT_LOCK_ASSERT_HELD(rt);
2589 if (rte_debug & RTD_DEBUG)
2590 rte_unlock_debug((struct rtentry_dbg *)rt);
2591 lck_mtx_unlock(&rt->rt_lock);
2592
2593 }
2594
2595 static inline void
2596 rte_lock_debug(struct rtentry_dbg *rte)
2597 {
2598 uint32_t idx;
2599
2600 idx = atomic_add_32_ov(&rte->rtd_lock_cnt, 1) % CTRACE_HIST_SIZE;
2601 if (rte_debug & RTD_TRACE)
2602 ctrace_record(&rte->rtd_lock[idx]);
2603 }
2604
2605 static inline void
2606 rte_unlock_debug(struct rtentry_dbg *rte)
2607 {
2608 uint32_t idx;
2609
2610 idx = atomic_add_32_ov(&rte->rtd_unlock_cnt, 1) % CTRACE_HIST_SIZE;
2611 if (rte_debug & RTD_TRACE)
2612 ctrace_record(&rte->rtd_unlock[idx]);
2613 }
2614
2615 static struct rtentry *
2616 rte_alloc(void)
2617 {
2618 if (rte_debug & RTD_DEBUG)
2619 return (rte_alloc_debug());
2620
2621 return ((struct rtentry *)zalloc(rte_zone));
2622 }
2623
2624 static void
2625 rte_free(struct rtentry *p)
2626 {
2627 if (rte_debug & RTD_DEBUG) {
2628 rte_free_debug(p);
2629 return;
2630 }
2631
2632 if (p->rt_refcnt != 0)
2633 panic("rte_free: rte=%p refcnt=%d non-zero\n", p, p->rt_refcnt);
2634
2635 zfree(rte_zone, p);
2636 }
2637
2638 static inline struct rtentry *
2639 rte_alloc_debug(void)
2640 {
2641 struct rtentry_dbg *rte;
2642
2643 rte = ((struct rtentry_dbg *)zalloc(rte_zone));
2644 if (rte != NULL) {
2645 bzero(rte, sizeof (*rte));
2646 if (rte_debug & RTD_TRACE)
2647 ctrace_record(&rte->rtd_alloc);
2648 rte->rtd_inuse = RTD_INUSE;
2649 }
2650 return ((struct rtentry *)rte);
2651 }
2652
2653 static inline void
2654 rte_free_debug(struct rtentry *p)
2655 {
2656 struct rtentry_dbg *rte = (struct rtentry_dbg *)p;
2657
2658 if (p->rt_refcnt != 0)
2659 panic("rte_free: rte=%p refcnt=%d\n", p, p->rt_refcnt);
2660
2661 if (rte->rtd_inuse == RTD_FREED)
2662 panic("rte_free: double free rte=%p\n", rte);
2663 else if (rte->rtd_inuse != RTD_INUSE)
2664 panic("rte_free: corrupted rte=%p\n", rte);
2665
2666 bcopy((caddr_t)p, (caddr_t)&rte->rtd_entry_saved, sizeof (*p));
2667 /* Preserve rt_lock to help catch use-after-free cases */
2668 bzero((caddr_t)p, offsetof(struct rtentry, rt_lock));
2669
2670 rte->rtd_inuse = RTD_FREED;
2671
2672 if (rte_debug & RTD_TRACE)
2673 ctrace_record(&rte->rtd_free);
2674
2675 if (!(rte_debug & RTD_NO_FREE))
2676 zfree(rte_zone, p);
2677 }
2678
2679 void
2680 ctrace_record(ctrace_t *tr)
2681 {
2682 tr->th = current_thread();
2683 bzero(tr->pc, sizeof (tr->pc));
2684 (void) OSBacktrace(tr->pc, CTRACE_STACK_SIZE);
2685 }