1 /*
2 * Copyright (c) 2003-2021 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 /*
30 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31 * All rights reserved.
32 *
33 * Redistribution and use in source and binary forms, with or without
34 * modification, are permitted provided that the following conditions
35 * are met:
36 * 1. Redistributions of source code must retain the above copyright
37 * notice, this list of conditions and the following disclaimer.
38 * 2. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in the
40 * documentation and/or other materials provided with the distribution.
41 * 3. Neither the name of the project nor the names of its contributors
42 * may be used to endorse or promote products derived from this software
43 * without specific prior written permission.
44 *
45 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55 * SUCH DAMAGE.
56 */
57
58 /*
59 * Copyright 1994, 1995 Massachusetts Institute of Technology
60 *
61 * Permission to use, copy, modify, and distribute this software and
62 * its documentation for any purpose and without fee is hereby
63 * granted, provided that both the above copyright notice and this
64 * permission notice appear in all copies, that both the above
65 * copyright notice and this permission notice appear in all
66 * supporting documentation, and that the name of M.I.T. not be used
67 * in advertising or publicity pertaining to distribution of the
68 * software without specific, written prior permission. M.I.T. makes
69 * no representations about the suitability of this software for any
70 * purpose. It is provided "as is" without express or implied
71 * warranty.
72 *
73 * THIS SOFTWARE IS PROVIDED BY M.I.T. ``AS IS''. M.I.T. DISCLAIMS
74 * ALL EXPRESS OR IMPLIED WARRANTIES WITH REGARD TO THIS SOFTWARE,
75 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
76 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
77 * SHALL M.I.T. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
78 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
79 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
80 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
81 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
82 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
83 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
84 * SUCH DAMAGE.
85 *
86 */
87
88 /*
89 * This code does two things necessary for the enhanced TCP metrics to
90 * function in a useful manner:
91 * 1) It marks all non-host routes as `cloning', thus ensuring that
92 * every actual reference to such a route actually gets turned
93 * into a reference to a host route to the specific destination
94 * requested.
95 * 2) When such routes lose all their references, it arranges for them
96 * to be deleted in some random collection of circumstances, so that
97 * a large quantity of stale routing data is not kept in kernel memory
98 * indefinitely. See in6_rtqtimo() below for the exact mechanism.
99 */
100
101 #include <sys/param.h>
102 #include <sys/systm.h>
103 #include <sys/kernel.h>
104 #include <sys/sysctl.h>
105 #include <kern/queue.h>
106 #include <sys/socket.h>
107 #include <sys/socketvar.h>
108 #include <sys/protosw.h>
109 #include <sys/mbuf.h>
110 #include <sys/syslog.h>
111 #include <sys/mcache.h>
112 #include <kern/locks.h>
113
114 #include <net/if.h>
115 #include <net/route.h>
116 #include <netinet/in.h>
117 #include <netinet/ip_var.h>
118 #include <netinet/in_var.h>
119
120 #include <netinet/ip6.h>
121 #include <netinet6/ip6_var.h>
122
123 #include <netinet/icmp6.h>
124
125 #include <netinet/tcp.h>
126 #include <netinet/tcp_seq.h>
127 #include <netinet/tcp_timer.h>
128 #include <netinet/tcp_var.h>
129
130 #include <net/sockaddr_utils.h>
131
132 extern int tvtohz(struct timeval *);
133
134 static int in6_rtqtimo_run; /* in6_rtqtimo is scheduled to run */
135 static void in6_rtqtimo(void *);
136 static void in6_sched_rtqtimo(struct timeval *);
137
138 static struct radix_node *in6_addroute(void *, void *, struct radix_node_head *,
139 struct radix_node[2]);
140 static struct radix_node *in6_deleteroute(void *, void *,
141 struct radix_node_head *);
142 static struct radix_node *in6_matroute(void *, struct radix_node_head *);
143 static struct radix_node *in6_matroute_args(void *, struct radix_node_head *,
144 rn_matchf_t *, void *);
145 static void in6_clsroute(struct radix_node *, struct radix_node_head *);
146 static int in6_rtqkill(struct radix_node *, void *);
147
148 /*
149 * Accessed by in6_addroute(), in6_deleteroute() and in6_rtqkill(), during
150 * which the routing lock (rnh_lock) is held and thus protects the variable.
151 */
152 static int in6dynroutes;
153
154 /*
155 * Do what we need to do when inserting a route.
156 */
157 static struct radix_node *
in6_addroute(void * v_arg,void * n_arg,struct radix_node_head * head,struct radix_node treenodes[2])158 in6_addroute(void *v_arg, void *n_arg, struct radix_node_head *head,
159 struct radix_node treenodes[2])
160 {
161 rtentry_ref_t rt = RT(treenodes);
162 struct sockaddr_in6 *__single sin6 = SIN6(rt_key(rt));
163 struct radix_node *__single ret;
164 char dbuf[MAX_IPv6_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
165 uint32_t flags = rt->rt_flags;
166 boolean_t verbose = (rt_verbose > 0);
167
168 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
169 RT_LOCK_ASSERT_HELD(rt);
170
171 if (verbose) {
172 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
173 }
174
175 /*
176 * If this is a dynamic route (which is created via Redirect) and
177 * we already have the maximum acceptable number of such route entries,
178 * reject creating a new one. We could initiate garbage collection to
179 * make available space right now, but the benefit would probably not
180 * be worth the cleaning overhead; we only have to endure a slightly
181 * suboptimal path even without the redirected route.
182 */
183 if ((rt->rt_flags & RTF_DYNAMIC) &&
184 ip6_maxdynroutes >= 0 && in6dynroutes >= ip6_maxdynroutes) {
185 return NULL;
186 }
187
188 /*
189 * For IPv6, all unicast non-host routes are automatically cloning.
190 */
191 if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
192 rt->rt_flags |= RTF_MULTICAST;
193 }
194
195 if (!(rt->rt_flags & (RTF_HOST | RTF_CLONING | RTF_MULTICAST))) {
196 rt->rt_flags |= RTF_PRCLONING;
197 }
198
199 /*
200 * A little bit of help for both IPv6 output and input:
201 * For local addresses, we make sure that RTF_LOCAL is set,
202 * with the thought that this might one day be used to speed up
203 * ip_input().
204 *
205 * We also mark routes to multicast addresses as such, because
206 * it's easy to do and might be useful (but this is much more
207 * dubious since it's so easy to inspect the address). (This
208 * is done above.)
209 *
210 * XXX
211 * should elaborate the code.
212 */
213 if (rt->rt_flags & RTF_HOST) {
214 IFA_LOCK_SPIN(rt->rt_ifa);
215 if (in6_are_addr_equal_scoped(&satosin6(rt->rt_ifa->ifa_addr)->
216 sin6_addr, &sin6->sin6_addr, satosin6(rt->rt_ifa->ifa_addr)->sin6_scope_id, sin6->sin6_scope_id)) {
217 rt->rt_flags |= RTF_LOCAL;
218 }
219 IFA_UNLOCK(rt->rt_ifa);
220 }
221
222 if (!rt->rt_rmx.rmx_mtu && !(rt->rt_rmx.rmx_locks & RTV_MTU) &&
223 rt->rt_ifp) {
224 rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
225 }
226
227 /*
228 * rn_addroute route returns NULL if an exact entry is being attempted
229 * to be added again.
230 */
231 ret = rn_addroute(v_arg, n_arg, head, treenodes);
232 if (ret == NULL && (rt->rt_flags & RTF_HOST)) {
233 rtentry_ref_t rt2;
234 /*
235 * We are trying to add a host route, but can't.
236 * Find out if it is because of an
237 * ND6 entry and delete it if so.
238 */
239 rt2 = rtalloc1_scoped_locked(SA(sin6), 0,
240 RTF_CLONING | RTF_PRCLONING, sin6_get_ifscope(rt_key(rt)));
241 if (rt2 != NULL) {
242 char dbufc[MAX_IPv6_STR_LEN];
243
244 RT_LOCK(rt2);
245 if (verbose) {
246 rt_str(rt2, dbufc, sizeof(dbufc), NULL, 0);
247 }
248
249 if ((rt2->rt_flags & RTF_LLINFO) &&
250 (rt2->rt_flags & RTF_HOST) &&
251 rt2->rt_gateway != NULL &&
252 rt2->rt_gateway->sa_family == AF_LINK) {
253 if (verbose) {
254 os_log_debug(OS_LOG_DEFAULT, "%s: unable to insert "
255 "route to %s:%s, flags=0x%x, due to "
256 "existing ND6 route %s->%s "
257 "flags=0x%x, attempting to delete\n",
258 __func__, dbuf,
259 (rt->rt_ifp != NULL) ?
260 rt->rt_ifp->if_xname : "",
261 rt->rt_flags,
262 dbufc, (rt2->rt_ifp != NULL) ?
263 rt2->rt_ifp->if_xname : "",
264 rt2->rt_flags);
265 }
266 /*
267 * Safe to drop rt_lock and use rt_key,
268 * rt_gateway, since holding rnh_lock here
269 * prevents another thread from calling
270 * rt_setgate() on this route.
271 */
272 RT_UNLOCK(rt2);
273 (void) rtrequest_locked(RTM_DELETE, rt_key(rt2),
274 rt2->rt_gateway, rt_mask(rt2),
275 rt2->rt_flags, NULL);
276 ret = rn_addroute(v_arg, n_arg, head, treenodes);
277 } else {
278 RT_UNLOCK(rt2);
279 }
280 rtfree_locked(rt2);
281 }
282 } else if (ret == NULL && (rt->rt_flags & RTF_CLONING)) {
283 rtentry_ref_t rt2;
284 /*
285 * We are trying to add a net route, but can't.
286 * The following case should be allowed, so we'll make a
287 * special check for this:
288 * Two IPv6 addresses with the same prefix is assigned
289 * to a single interrface.
290 * # ifconfig if0 inet6 3ffe:0501::1 prefix 64 alias (*1)
291 * # ifconfig if0 inet6 3ffe:0501::2 prefix 64 alias (*2)
292 * In this case, (*1) and (*2) want to add the same
293 * net route entry, 3ffe:0501:: -> if0.
294 * This case should not raise an error.
295 */
296 rt2 = rtalloc1_scoped_locked(SA(sin6), 0,
297 RTF_CLONING | RTF_PRCLONING, sin6_get_ifscope(rt_key(rt)));
298 if (rt2 != NULL) {
299 RT_LOCK(rt2);
300 if ((rt2->rt_flags & (RTF_CLONING | RTF_HOST |
301 RTF_GATEWAY)) == RTF_CLONING &&
302 rt2->rt_gateway &&
303 rt2->rt_gateway->sa_family == AF_LINK &&
304 rt2->rt_ifp == rt->rt_ifp) {
305 ret = rt2->rt_nodes;
306 }
307 RT_UNLOCK(rt2);
308 rtfree_locked(rt2);
309 }
310 }
311
312 if (ret != NULL && (rt->rt_flags & RTF_DYNAMIC)) {
313 in6dynroutes++;
314 }
315
316 if (!verbose) {
317 goto done;
318 }
319
320 if (ret != NULL) {
321 if (flags != rt->rt_flags) {
322 os_log(OS_LOG_DEFAULT, "%s: route to %s->%s->%s inserted, "
323 "oflags=0x%x, flags=0x%x\n", __func__,
324 dbuf, gbuf, (rt->rt_ifp != NULL) ?
325 rt->rt_ifp->if_xname : "", flags,
326 rt->rt_flags);
327 } else {
328 os_log(OS_LOG_DEFAULT, "%s: route to %s->%s->%s inserted, "
329 "flags=0x%x\n", __func__, dbuf, gbuf,
330 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
331 rt->rt_flags);
332 }
333 } else {
334 os_log_debug(OS_LOG_DEFAULT, "%s: unable to insert route to %s->%s->%s, "
335 "flags=0x%x, already exists\n", __func__, dbuf, gbuf,
336 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
337 rt->rt_flags);
338 }
339 done:
340 return ret;
341 }
342
343 static struct radix_node *
in6_deleteroute(void * v_arg,void * netmask_arg,struct radix_node_head * head)344 in6_deleteroute(void *v_arg, void *netmask_arg, struct radix_node_head *head)
345 {
346 struct radix_node *__single rn;
347
348 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
349
350 rn = rn_delete(v_arg, netmask_arg, head);
351 if (rn != NULL) {
352 rtentry_ref_t rt = RT(rn);
353
354 RT_LOCK(rt);
355 if (rt->rt_flags & RTF_DYNAMIC) {
356 in6dynroutes--;
357 }
358 if (rt_verbose) {
359 char dbuf[MAX_IPv6_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
360
361 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
362 os_log_debug(OS_LOG_DEFAULT, "%s: route to %s->%s->%s deleted, "
363 "flags=0x%x\n", __func__, dbuf, gbuf,
364 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
365 rt->rt_flags);
366 }
367 RT_UNLOCK(rt);
368 }
369 return rn;
370 }
371
372 /*
373 * Validate (unexpire) an expiring AF_INET6 route.
374 */
375 struct radix_node *
in6_validate(struct radix_node * rn)376 in6_validate(struct radix_node *rn)
377 {
378 rtentry_ref_t rt = RT(rn);
379
380 RT_LOCK_ASSERT_HELD(rt);
381
382 /* This is first reference? */
383 if (rt->rt_refcnt == 0) {
384 if (rt_verbose > 2) {
385 char dbuf[MAX_IPv6_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
386
387 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
388 os_log_debug(OS_LOG_DEFAULT, "%s: route to %s->%s->%s validated, "
389 "flags=0x%x\n", __func__, dbuf, gbuf,
390 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
391 rt->rt_flags);
392 }
393
394 /*
395 * It's one of ours; unexpire it. If the timer is already
396 * scheduled, let it run later as it won't re-arm itself
397 * if there's nothing to do.
398 */
399 if (rt->rt_flags & RTPRF_OURS) {
400 rt->rt_flags &= ~RTPRF_OURS;
401 rt_setexpire(rt, 0);
402 }
403 }
404 return rn;
405 }
406
407 /*
408 * Similar to in6_matroute_args except without the leaf-matching parameters.
409 */
410 static struct radix_node *
in6_matroute(void * v_arg,struct radix_node_head * head)411 in6_matroute(void *v_arg, struct radix_node_head *head)
412 {
413 return in6_matroute_args(v_arg, head, NULL, NULL);
414 }
415
416 /*
417 * This code is the inverse of in6_clsroute: on first reference, if we
418 * were managing the route, stop doing so and set the expiration timer
419 * back off again.
420 */
421 static struct radix_node *
in6_matroute_args(void * v_arg,struct radix_node_head * head,rn_matchf_t * f,void * w)422 in6_matroute_args(void *v_arg, struct radix_node_head *head,
423 rn_matchf_t *f, void *w)
424 {
425 struct radix_node *__single rn = rn_match_args(v_arg, head, f, w);
426
427 if (rn != NULL) {
428 rtentry_ref_t rt = RT(rn);
429
430 RT_LOCK_SPIN(rt);
431 in6_validate(rn);
432 RT_UNLOCK(rt);
433 }
434 return rn;
435 }
436
437 SYSCTL_DECL(_net_inet6_ip6);
438
439 /* one hour is ``really old'' */
440 static uint32_t rtq_reallyold = 60 * 60;
441 SYSCTL_UINT(_net_inet6_ip6, IPV6CTL_RTEXPIRE, rtexpire,
442 CTLFLAG_RW | CTLFLAG_LOCKED, &rtq_reallyold, 0, "");
443
444 /* never automatically crank down to less */
445 static uint32_t rtq_minreallyold = 10;
446 SYSCTL_UINT(_net_inet6_ip6, IPV6CTL_RTMINEXPIRE, rtminexpire,
447 CTLFLAG_RW | CTLFLAG_LOCKED, &rtq_minreallyold, 0, "");
448
449 /* 128 cached routes is ``too many'' */
450 static uint32_t rtq_toomany = 128;
451 SYSCTL_UINT(_net_inet6_ip6, IPV6CTL_RTMAXCACHE, rtmaxcache,
452 CTLFLAG_RW | CTLFLAG_LOCKED, &rtq_toomany, 0, "");
453
454 /*
455 * On last reference drop, mark the route as belong to us so that it can be
456 * timed out.
457 */
458 static void
in6_clsroute(struct radix_node * rn,struct radix_node_head * head)459 in6_clsroute(struct radix_node *rn, struct radix_node_head *head)
460 {
461 #pragma unused(head)
462 char dbuf[MAX_IPv6_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
463 rtentry_ref_t rt = RT(rn);
464 boolean_t verbose = (rt_verbose > 2);
465
466 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
467 RT_LOCK_ASSERT_HELD(rt);
468
469 if (!(rt->rt_flags & RTF_UP)) {
470 return; /* prophylactic measures */
471 }
472 if ((rt->rt_flags & (RTF_LLINFO | RTF_HOST)) != RTF_HOST) {
473 return;
474 }
475
476 if (rt->rt_flags & RTPRF_OURS) {
477 return;
478 }
479
480 if (!(rt->rt_flags & (RTF_WASCLONED | RTF_DYNAMIC))) {
481 return;
482 }
483
484 if (verbose) {
485 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
486 }
487
488 /*
489 * Delete the route immediately if RTF_DELCLONE is set or
490 * if route caching is disabled (rtq_reallyold set to 0).
491 * Otherwise, let it expire and be deleted by in6_rtqkill().
492 */
493 if ((rt->rt_flags & RTF_DELCLONE) || rtq_reallyold == 0) {
494 int err;
495
496 if (verbose) {
497 os_log_debug(OS_LOG_DEFAULT, "%s: deleting route to %s->%s->%s, "
498 "flags=0x%x\n", __func__, dbuf, gbuf,
499 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
500 rt->rt_flags);
501 }
502 /*
503 * Delete the route from the radix tree but since we are
504 * called when the route's reference count is 0, don't
505 * deallocate it until we return from this routine by
506 * telling rtrequest that we're interested in it.
507 * Safe to drop rt_lock and use rt_key, rt_gateway,
508 * since holding rnh_lock here prevents another thread
509 * from calling rt_setgate() on this route.
510 */
511 RT_UNLOCK(rt);
512 err = rtrequest_locked(RTM_DELETE, rt_key(rt),
513 rt->rt_gateway, rt_mask(rt), rt->rt_flags, &rt);
514 if (err == 0) {
515 /* Now let the caller free it */
516 RT_LOCK(rt);
517 RT_REMREF_LOCKED(rt);
518 } else {
519 RT_LOCK(rt);
520 if (!verbose) {
521 rt_str(rt, dbuf, sizeof(dbuf),
522 gbuf, sizeof(gbuf));
523 }
524 os_log_error(OS_LOG_DEFAULT, "%s: error deleting route to "
525 "%s->%s->%s, flags=0x%x, err=%d\n", __func__,
526 dbuf, gbuf, (rt->rt_ifp != NULL) ?
527 rt->rt_ifp->if_xname : "", rt->rt_flags,
528 err);
529 }
530 } else {
531 uint64_t timenow;
532
533 timenow = net_uptime();
534 rt->rt_flags |= RTPRF_OURS;
535 rt_setexpire(rt, timenow + rtq_reallyold);
536
537 if (verbose) {
538 os_log_debug(OS_LOG_DEFAULT, "%s: route to %s->%s->%s invalidated, "
539 "flags=0x%x, expire=T+%u\n", __func__, dbuf, gbuf,
540 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
541 rt->rt_flags, rt->rt_expire - timenow);
542 }
543
544 /* We have at least one entry; arm the timer if not already */
545 in6_sched_rtqtimo(NULL);
546 }
547 }
548
549 struct rtqk_arg {
550 struct radix_node_head *rnh;
551 int updating;
552 int draining;
553 uint32_t killed;
554 uint32_t found;
555 uint64_t nextstop;
556 };
557
558 /*
559 * Get rid of old routes. When draining, this deletes everything, even when
560 * the timeout is not expired yet. This also applies if the route is dynamic
561 * and there are sufficiently large number of such routes (more than a half of
562 * maximum). When updating, this makes sure that nothing has a timeout longer
563 * than the current value of rtq_reallyold.
564 */
565 static int
in6_rtqkill(struct radix_node * rn,void * rock)566 in6_rtqkill(struct radix_node *rn, void *rock)
567 {
568 struct rtqk_arg *__single ap = rock;
569 rtentry_ref_t rt = RT(rn);
570 boolean_t verbose = (rt_verbose > 1);
571 uint64_t timenow;
572 int err;
573
574 timenow = net_uptime();
575 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
576
577 RT_LOCK(rt);
578 if (rt->rt_flags & RTPRF_OURS) {
579 char dbuf[MAX_IPv6_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
580
581 if (verbose) {
582 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
583 }
584
585 ap->found++;
586 VERIFY(rt->rt_expire == 0 || rt->rt_rmx.rmx_expire != 0);
587 VERIFY(rt->rt_expire != 0 || rt->rt_rmx.rmx_expire == 0);
588 if (ap->draining || rt->rt_expire <= timenow ||
589 ((rt->rt_flags & RTF_DYNAMIC) && ip6_maxdynroutes >= 0 &&
590 in6dynroutes > ip6_maxdynroutes / 2)) {
591 if (rt->rt_refcnt > 0) {
592 panic("%s: route %p marked with RTPRF_OURS "
593 "with non-zero refcnt (%u)", __func__,
594 rt, rt->rt_refcnt);
595 /* NOTREACHED */
596 }
597
598 if (verbose) {
599 os_log_debug(OS_LOG_DEFAULT, "%s: deleting route to "
600 "%s->%s->%s, flags=0x%x, draining=%d\n",
601 __func__, dbuf, gbuf, (rt->rt_ifp != NULL) ?
602 rt->rt_ifp->if_xname : "", rt->rt_flags,
603 ap->draining);
604 }
605 RT_ADDREF_LOCKED(rt); /* for us to free below */
606 /*
607 * Delete this route since we're done with it;
608 * the route may be freed afterwards, so we
609 * can no longer refer to 'rt' upon returning
610 * from rtrequest(). Safe to drop rt_lock and
611 * use rt_key, rt_gateway, since holding rnh_lock
612 * here prevents another thread from calling
613 * rt_setgate() on this route.
614 */
615 RT_UNLOCK(rt);
616 err = rtrequest_locked(RTM_DELETE, rt_key(rt),
617 rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
618 if (err != 0) {
619 RT_LOCK(rt);
620 if (!verbose) {
621 rt_str(rt, dbuf, sizeof(dbuf),
622 gbuf, sizeof(gbuf));
623 }
624 os_log_error(OS_LOG_DEFAULT, "%s: error deleting route to "
625 "%s->%s->%s, flags=0x%x, err=%d\n", __func__,
626 dbuf, gbuf, (rt->rt_ifp != NULL) ?
627 rt->rt_ifp->if_xname : "", rt->rt_flags,
628 err);
629 RT_UNLOCK(rt);
630 } else {
631 ap->killed++;
632 }
633 rtfree_locked(rt);
634 } else {
635 uint64_t expire = (rt->rt_expire - timenow);
636
637 if (ap->updating && expire > rtq_reallyold) {
638 rt_setexpire(rt, timenow + rtq_reallyold);
639 if (verbose) {
640 os_log_debug(OS_LOG_DEFAULT, "%s: route to "
641 "%s->%s->%s, flags=0x%x, adjusted "
642 "expire=T+%u (was T+%u)\n",
643 __func__, dbuf, gbuf,
644 (rt->rt_ifp != NULL) ?
645 rt->rt_ifp->if_xname : "",
646 rt->rt_flags,
647 (rt->rt_expire - timenow), expire);
648 }
649 }
650 ap->nextstop = lmin(ap->nextstop, rt->rt_expire);
651 RT_UNLOCK(rt);
652 }
653 } else {
654 RT_UNLOCK(rt);
655 }
656
657 return 0;
658 }
659
660 #define RTQ_TIMEOUT 60*10 /* run no less than once every ten minutes */
661 static int rtq_timeout = RTQ_TIMEOUT;
662
663 static void
in6_rtqtimo(void * targ)664 in6_rtqtimo(void *targ)
665 {
666 #pragma unused(targ)
667 struct radix_node_head *__single rnh;
668 struct rtqk_arg arg;
669 struct timeval atv;
670 static uint64_t last_adjusted_timeout = 0;
671 boolean_t verbose = (rt_verbose > 1);
672 uint64_t timenow;
673 uint32_t ours;
674
675 lck_mtx_lock(rnh_lock);
676 rnh = rt_tables[AF_INET6];
677 VERIFY(rnh != NULL);
678
679 /* Get the timestamp after we acquire the lock for better accuracy */
680 timenow = net_uptime();
681 if (verbose) {
682 os_log_debug(OS_LOG_DEFAULT, "%s: initial nextstop is T+%u seconds\n",
683 __func__, rtq_timeout);
684 }
685 bzero(&arg, sizeof(arg));
686 arg.rnh = rnh;
687 arg.nextstop = timenow + rtq_timeout;
688 rnh->rnh_walktree(rnh, in6_rtqkill, &arg);
689 if (verbose) {
690 os_log_debug(OS_LOG_DEFAULT, "%s: found %u, killed %u\n", __func__,
691 arg.found, arg.killed);
692 }
693 /*
694 * Attempt to be somewhat dynamic about this:
695 * If there are ``too many'' routes sitting around taking up space,
696 * then crank down the timeout, and see if we can't make some more
697 * go away. However, we make sure that we will never adjust more
698 * than once in rtq_timeout seconds, to keep from cranking down too
699 * hard.
700 */
701 ours = (arg.found - arg.killed);
702 if (ours > rtq_toomany &&
703 ((timenow - last_adjusted_timeout) >= (uint64_t)rtq_timeout) &&
704 rtq_reallyold > rtq_minreallyold) {
705 rtq_reallyold = 2 * rtq_reallyold / 3;
706 if (rtq_reallyold < rtq_minreallyold) {
707 rtq_reallyold = rtq_minreallyold;
708 }
709
710 last_adjusted_timeout = timenow;
711 if (verbose) {
712 os_log_debug(OS_LOG_DEFAULT, "%s: adjusted rtq_reallyold to %d "
713 "seconds\n", __func__, rtq_reallyold);
714 }
715 arg.found = arg.killed = 0;
716 arg.updating = 1;
717 rnh->rnh_walktree(rnh, in6_rtqkill, &arg);
718 }
719
720 atv.tv_usec = 0;
721 atv.tv_sec = arg.nextstop - timenow;
722 /* re-arm the timer only if there's work to do */
723 in6_rtqtimo_run = 0;
724 if (ours > 0) {
725 in6_sched_rtqtimo(&atv);
726 } else if (verbose) {
727 os_log_debug(OS_LOG_DEFAULT, "%s: not rescheduling timer\n", __func__);
728 }
729 lck_mtx_unlock(rnh_lock);
730 }
731
732 static void
in6_sched_rtqtimo(struct timeval * atv)733 in6_sched_rtqtimo(struct timeval *atv)
734 {
735 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
736
737 if (!in6_rtqtimo_run) {
738 struct timeval tv;
739
740 if (atv == NULL) {
741 tv.tv_usec = 0;
742 tv.tv_sec = MAX(rtq_timeout / 10, 1);
743 atv = &tv;
744 }
745 if (rt_verbose > 2) {
746 os_log_debug(OS_LOG_DEFAULT, "%s: timer scheduled in "
747 "T+%llus.%lluu\n", __func__,
748 (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec);
749 }
750 in6_rtqtimo_run = 1;
751 timeout(in6_rtqtimo, NULL, tvtohz(atv));
752 }
753 }
754
755 void
in6_rtqdrain(void)756 in6_rtqdrain(void)
757 {
758 struct radix_node_head *__single rnh;
759 struct rtqk_arg arg;
760
761 if (rt_verbose > 1) {
762 os_log_debug(OS_LOG_DEFAULT, "%s: draining routes\n", __func__);
763 }
764
765 lck_mtx_lock(rnh_lock);
766 rnh = rt_tables[AF_INET6];
767 VERIFY(rnh != NULL);
768 bzero(&arg, sizeof(arg));
769 arg.rnh = rnh;
770 arg.draining = 1;
771 rnh->rnh_walktree(rnh, in6_rtqkill, &arg);
772 lck_mtx_unlock(rnh_lock);
773 }
774
775 /*
776 * Initialize our routing tree.
777 */
778 int
in6_inithead(void ** head,int off)779 in6_inithead(void **head, int off)
780 {
781 struct radix_node_head *__single rnh;
782
783 /* If called from route_init(), make sure it is exactly once */
784 VERIFY(head != (void **)&rt_tables[AF_INET6] || *head == NULL);
785
786 if (!rn_inithead(head, off)) {
787 return 0;
788 }
789
790 /*
791 * We can get here from nfs_subs.c as well, in which case this
792 * won't be for the real routing table and thus we're done;
793 * this also takes care of the case when we're called more than
794 * once from anywhere but route_init().
795 */
796 if (head != (void **)&rt_tables[AF_INET6]) {
797 return 1; /* only do this for the real routing table */
798 }
799 rnh = *head;
800 rnh->rnh_addaddr = in6_addroute;
801 rnh->rnh_deladdr = in6_deleteroute;
802 rnh->rnh_matchaddr = in6_matroute;
803 rnh->rnh_matchaddr_args = in6_matroute_args;
804 rnh->rnh_close = in6_clsroute;
805 return 1;
806 }
807