xref: /freebsd/sys/net/route.c (revision f3856e68811a32389fbb8f50d334f7409a6dd2e7)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)route.c	8.3.1.1 (Berkeley) 2/23/95
32  * $FreeBSD$
33  */
34 /************************************************************************
35  * Note: In this file a 'fib' is a "forwarding information base"	*
36  * Which is the new name for an in kernel routing (next hop) table.	*
37  ***********************************************************************/
38 
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 #include "opt_mrouting.h"
42 #include "opt_mpath.h"
43 #include "opt_route.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/sysproto.h>
53 #include <sys/proc.h>
54 #include <sys/domain.h>
55 #include <sys/eventhandler.h>
56 #include <sys/kernel.h>
57 #include <sys/lock.h>
58 #include <sys/rmlock.h>
59 
60 #include <net/if.h>
61 #include <net/if_var.h>
62 #include <net/if_dl.h>
63 #include <net/route.h>
64 #include <net/route/route_ctl.h>
65 #include <net/route/route_var.h>
66 #include <net/route/nhop.h>
67 #include <net/route/shared.h>
68 #include <net/vnet.h>
69 
70 #ifdef RADIX_MPATH
71 #include <net/radix_mpath.h>
72 #endif
73 
74 #include <netinet/in.h>
75 #include <netinet/ip_mroute.h>
76 
77 #include <vm/uma.h>
78 
79 #define	RT_MAXFIBS	UINT16_MAX
80 
81 /* Kernel config default option. */
82 #ifdef ROUTETABLES
83 #if ROUTETABLES <= 0
84 #error "ROUTETABLES defined too low"
85 #endif
86 #if ROUTETABLES > RT_MAXFIBS
87 #error "ROUTETABLES defined too big"
88 #endif
89 #define	RT_NUMFIBS	ROUTETABLES
90 #endif /* ROUTETABLES */
91 /* Initialize to default if not otherwise set. */
92 #ifndef	RT_NUMFIBS
93 #define	RT_NUMFIBS	1
94 #endif
95 
96 /* This is read-only.. */
97 u_int rt_numfibs = RT_NUMFIBS;
98 SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RDTUN, &rt_numfibs, 0, "");
99 
100 /*
101  * By default add routes to all fibs for new interfaces.
102  * Once this is set to 0 then only allocate routes on interface
103  * changes for the FIB of the caller when adding a new set of addresses
104  * to an interface.  XXX this is a shotgun aproach to a problem that needs
105  * a more fine grained solution.. that will come.
106  * XXX also has the problems getting the FIB from curthread which will not
107  * always work given the fib can be overridden and prefixes can be added
108  * from the network stack context.
109  */
110 VNET_DEFINE(u_int, rt_add_addr_allfibs) = 1;
111 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RWTUN | CTLFLAG_VNET,
112     &VNET_NAME(rt_add_addr_allfibs), 0, "");
113 
114 VNET_PCPUSTAT_DEFINE(struct rtstat, rtstat);
115 
116 VNET_PCPUSTAT_SYSINIT(rtstat);
117 #ifdef VIMAGE
118 VNET_PCPUSTAT_SYSUNINIT(rtstat);
119 #endif
120 
121 VNET_DEFINE(struct rib_head *, rt_tables);
122 #define	V_rt_tables	VNET(rt_tables)
123 
124 
125 VNET_DEFINE(uma_zone_t, rtzone);		/* Routing table UMA zone. */
126 #define	V_rtzone	VNET(rtzone)
127 
128 EVENTHANDLER_LIST_DEFINE(rt_addrmsg);
129 
130 static int rt_ifdelroute(const struct rtentry *rt, const struct nhop_object *,
131     void *arg);
132 static void destroy_rtentry_epoch(epoch_context_t ctx);
133 static int rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info,
134     int flags);
135 
136 /*
137  * handler for net.my_fibnum
138  */
139 static int
140 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
141 {
142         int fibnum;
143         int error;
144 
145         fibnum = curthread->td_proc->p_fibnum;
146         error = sysctl_handle_int(oidp, &fibnum, 0, req);
147         return (error);
148 }
149 
150 SYSCTL_PROC(_net, OID_AUTO, my_fibnum,
151     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
152     &sysctl_my_fibnum, "I",
153     "default FIB of caller");
154 
155 static __inline struct rib_head **
156 rt_tables_get_rnh_ptr(int table, int fam)
157 {
158 	struct rib_head **rnh;
159 
160 	KASSERT(table >= 0 && table < rt_numfibs,
161 	    ("%s: table out of bounds (0 <= %d < %d)", __func__, table,
162 	     rt_numfibs));
163 	KASSERT(fam >= 0 && fam < (AF_MAX + 1),
164 	    ("%s: fam out of bounds (0 <= %d < %d)", __func__, fam, AF_MAX+1));
165 
166 	/* rnh is [fib=0][af=0]. */
167 	rnh = (struct rib_head **)V_rt_tables;
168 	/* Get the offset to the requested table and fam. */
169 	rnh += table * (AF_MAX+1) + fam;
170 
171 	return (rnh);
172 }
173 
174 struct rib_head *
175 rt_tables_get_rnh(int table, int fam)
176 {
177 
178 	return (*rt_tables_get_rnh_ptr(table, fam));
179 }
180 
181 u_int
182 rt_tables_get_gen(int table, int fam)
183 {
184 	struct rib_head *rnh;
185 
186 	rnh = *rt_tables_get_rnh_ptr(table, fam);
187 	KASSERT(rnh != NULL, ("%s: NULL rib_head pointer table %d fam %d",
188 	    __func__, table, fam));
189 	return (rnh->rnh_gen);
190 }
191 
192 
193 /*
194  * route initialization must occur before ip6_init2(), which happenas at
195  * SI_ORDER_MIDDLE.
196  */
197 static void
198 route_init(void)
199 {
200 
201 	/* whack the tunable ints into  line. */
202 	if (rt_numfibs > RT_MAXFIBS)
203 		rt_numfibs = RT_MAXFIBS;
204 	if (rt_numfibs == 0)
205 		rt_numfibs = 1;
206 	nhops_init();
207 }
208 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, NULL);
209 
210 static int
211 rtentry_zinit(void *mem, int size, int how)
212 {
213 	struct rtentry *rt = mem;
214 
215 	RT_LOCK_INIT(rt);
216 
217 	return (0);
218 }
219 
220 static void
221 rtentry_zfini(void *mem, int size)
222 {
223 	struct rtentry *rt = mem;
224 
225 	RT_LOCK_DESTROY(rt);
226 }
227 
228 static int
229 rtentry_ctor(void *mem, int size, void *arg, int how)
230 {
231 	struct rtentry *rt = mem;
232 
233 	bzero(rt, offsetof(struct rtentry, rt_endzero));
234 	rt->rt_chain = NULL;
235 
236 	return (0);
237 }
238 
239 static void
240 rtentry_dtor(void *mem, int size, void *arg)
241 {
242 	struct rtentry *rt = mem;
243 
244 	RT_UNLOCK_COND(rt);
245 }
246 
247 static void
248 vnet_route_init(const void *unused __unused)
249 {
250 	struct domain *dom;
251 	struct rib_head **rnh;
252 	int table;
253 	int fam;
254 
255 	V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
256 	    sizeof(struct rib_head *), M_RTABLE, M_WAITOK|M_ZERO);
257 
258 	V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
259 	    rtentry_ctor, rtentry_dtor,
260 	    rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
261 	for (dom = domains; dom; dom = dom->dom_next) {
262 		if (dom->dom_rtattach == NULL)
263 			continue;
264 
265 		for  (table = 0; table < rt_numfibs; table++) {
266 			fam = dom->dom_family;
267 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
268 				break;
269 
270 			rnh = rt_tables_get_rnh_ptr(table, fam);
271 			if (rnh == NULL)
272 				panic("%s: rnh NULL", __func__);
273 			dom->dom_rtattach((void **)rnh, 0, table);
274 		}
275 	}
276 }
277 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
278     vnet_route_init, 0);
279 
280 #ifdef VIMAGE
281 static void
282 vnet_route_uninit(const void *unused __unused)
283 {
284 	int table;
285 	int fam;
286 	struct domain *dom;
287 	struct rib_head **rnh;
288 
289 	for (dom = domains; dom; dom = dom->dom_next) {
290 		if (dom->dom_rtdetach == NULL)
291 			continue;
292 
293 		for (table = 0; table < rt_numfibs; table++) {
294 			fam = dom->dom_family;
295 
296 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
297 				break;
298 
299 			rnh = rt_tables_get_rnh_ptr(table, fam);
300 			if (rnh == NULL)
301 				panic("%s: rnh NULL", __func__);
302 			dom->dom_rtdetach((void **)rnh, 0);
303 		}
304 	}
305 
306 	/*
307 	 * dom_rtdetach calls rt_table_destroy(), which
308 	 *  schedules deletion for all rtentries, nexthops and control
309 	 *  structures. Wait for the destruction callbacks to fire.
310 	 * Note that this should result in freeing all rtentries, but
311 	 *  nexthops deletions will be scheduled for the next epoch run
312 	 *  and will be completed after vnet teardown.
313 	 */
314 	epoch_drain_callbacks(net_epoch_preempt);
315 
316 	free(V_rt_tables, M_RTABLE);
317 	uma_zdestroy(V_rtzone);
318 }
319 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
320     vnet_route_uninit, 0);
321 #endif
322 
323 struct rib_head *
324 rt_table_init(int offset, int family, u_int fibnum)
325 {
326 	struct rib_head *rh;
327 
328 	rh = malloc(sizeof(struct rib_head), M_RTABLE, M_WAITOK | M_ZERO);
329 
330 	/* TODO: These details should be hidded inside radix.c */
331 	/* Init masks tree */
332 	rn_inithead_internal(&rh->head, rh->rnh_nodes, offset);
333 	rn_inithead_internal(&rh->rmhead.head, rh->rmhead.mask_nodes, 0);
334 	rh->head.rnh_masks = &rh->rmhead;
335 
336 	/* Save metadata associated with this routing table. */
337 	rh->rib_family = family;
338 	rh->rib_fibnum = fibnum;
339 #ifdef VIMAGE
340 	rh->rib_vnet = curvnet;
341 #endif
342 
343 	tmproutes_init(rh);
344 
345 	/* Init locks */
346 	RIB_LOCK_INIT(rh);
347 
348 	nhops_init_rib(rh);
349 
350 	/* Init subscription system */
351 	rib_init_subscriptions(rh);
352 
353 	/* Finally, set base callbacks */
354 	rh->rnh_addaddr = rn_addroute;
355 	rh->rnh_deladdr = rn_delete;
356 	rh->rnh_matchaddr = rn_match;
357 	rh->rnh_lookup = rn_lookup;
358 	rh->rnh_walktree = rn_walktree;
359 	rh->rnh_walktree_from = rn_walktree_from;
360 
361 	return (rh);
362 }
363 
364 static int
365 rt_freeentry(struct radix_node *rn, void *arg)
366 {
367 	struct radix_head * const rnh = arg;
368 	struct radix_node *x;
369 
370 	x = (struct radix_node *)rn_delete(rn + 2, NULL, rnh);
371 	if (x != NULL)
372 		R_Free(x);
373 	return (0);
374 }
375 
376 void
377 rt_table_destroy(struct rib_head *rh)
378 {
379 
380 	tmproutes_destroy(rh);
381 
382 	rn_walktree(&rh->rmhead.head, rt_freeentry, &rh->rmhead.head);
383 
384 	nhops_destroy_rib(rh);
385 
386 	rib_destroy_subscriptions(rh);
387 
388 	/* Assume table is already empty */
389 	RIB_LOCK_DESTROY(rh);
390 	free(rh, M_RTABLE);
391 }
392 
393 
394 #ifndef _SYS_SYSPROTO_H_
395 struct setfib_args {
396 	int     fibnum;
397 };
398 #endif
399 int
400 sys_setfib(struct thread *td, struct setfib_args *uap)
401 {
402 	if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
403 		return EINVAL;
404 	td->td_proc->p_fibnum = uap->fibnum;
405 	return (0);
406 }
407 
408 /*
409  * Remove a reference count from an rtentry.
410  * If the count gets low enough, take it out of the routing table
411  */
412 void
413 rtfree(struct rtentry *rt)
414 {
415 
416 	KASSERT(rt != NULL,("%s: NULL rt", __func__));
417 
418 	RT_LOCK_ASSERT(rt);
419 
420 	RT_UNLOCK(rt);
421 	epoch_call(net_epoch_preempt, destroy_rtentry_epoch,
422 	    &rt->rt_epoch_ctx);
423 }
424 
425 static void
426 destroy_rtentry(struct rtentry *rt)
427 {
428 
429 	/*
430 	 * At this moment rnh, nh_control may be already freed.
431 	 * nhop interface may have been migrated to a different vnet.
432 	 * Use vnet stored in the nexthop to delete the entry.
433 	 */
434 	CURVNET_SET(nhop_get_vnet(rt->rt_nhop));
435 
436 	/* Unreference nexthop */
437 	nhop_free(rt->rt_nhop);
438 
439 	uma_zfree(V_rtzone, rt);
440 
441 	CURVNET_RESTORE();
442 }
443 
444 /*
445  * Epoch callback indicating rtentry is safe to destroy
446  */
447 static void
448 destroy_rtentry_epoch(epoch_context_t ctx)
449 {
450 	struct rtentry *rt;
451 
452 	rt = __containerof(ctx, struct rtentry, rt_epoch_ctx);
453 
454 	destroy_rtentry(rt);
455 }
456 
457 /*
458  * Adds a temporal redirect entry to the routing table.
459  * @fibnum: fib number
460  * @dst: destination to install redirect to
461  * @gateway: gateway to go via
462  * @author: sockaddr of originating router, can be NULL
463  * @ifp: interface to use for the redirected route
464  * @flags: set of flags to add. Allowed: RTF_GATEWAY
465  * @lifetime_sec: time in seconds to expire this redirect.
466  *
467  * Retuns 0 on success, errno otherwise.
468  */
469 int
470 rib_add_redirect(u_int fibnum, struct sockaddr *dst, struct sockaddr *gateway,
471     struct sockaddr *author, struct ifnet *ifp, int flags, int lifetime_sec)
472 {
473 	struct rtentry *rt;
474 	int error;
475 	struct rt_addrinfo info;
476 	struct rt_metrics rti_rmx;
477 	struct ifaddr *ifa;
478 
479 	NET_EPOCH_ASSERT();
480 
481 	if (rt_tables_get_rnh(fibnum, dst->sa_family) == NULL)
482 		return (EAFNOSUPPORT);
483 
484 	/* Verify the allowed flag mask. */
485 	KASSERT(((flags & ~(RTF_GATEWAY)) == 0),
486 	    ("invalid redirect flags: %x", flags));
487 
488 	/* Get the best ifa for the given interface and gateway. */
489 	if ((ifa = ifaof_ifpforaddr(gateway, ifp)) == NULL)
490 		return (ENETUNREACH);
491 	ifa_ref(ifa);
492 
493 	bzero(&info, sizeof(info));
494 	info.rti_info[RTAX_DST] = dst;
495 	info.rti_info[RTAX_GATEWAY] = gateway;
496 	info.rti_ifa = ifa;
497 	info.rti_ifp = ifp;
498 	info.rti_flags = flags | RTF_HOST | RTF_DYNAMIC;
499 
500 	/* Setup route metrics to define expire time. */
501 	bzero(&rti_rmx, sizeof(rti_rmx));
502 	/* Set expire time as absolute. */
503 	rti_rmx.rmx_expire = lifetime_sec + time_second;
504 	info.rti_mflags |= RTV_EXPIRE;
505 	info.rti_rmx = &rti_rmx;
506 
507 	error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
508 	ifa_free(ifa);
509 
510 	if (error != 0) {
511 		/* TODO: add per-fib redirect stats. */
512 		return (error);
513 	}
514 
515 	RT_LOCK(rt);
516 	flags = rt->rt_flags;
517 	RT_UNLOCK(rt);
518 
519 	RTSTAT_INC(rts_dynamic);
520 
521 	/* Send notification of a route addition to userland. */
522 	bzero(&info, sizeof(info));
523 	info.rti_info[RTAX_DST] = dst;
524 	info.rti_info[RTAX_GATEWAY] = gateway;
525 	info.rti_info[RTAX_AUTHOR] = author;
526 	rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
527 
528 	return (0);
529 }
530 
531 /*
532  * Routing table ioctl interface.
533  */
534 int
535 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
536 {
537 
538 	/*
539 	 * If more ioctl commands are added here, make sure the proper
540 	 * super-user checks are being performed because it is possible for
541 	 * prison-root to make it this far if raw sockets have been enabled
542 	 * in jails.
543 	 */
544 #ifdef INET
545 	/* Multicast goop, grrr... */
546 	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
547 #else /* INET */
548 	return ENXIO;
549 #endif /* INET */
550 }
551 
552 struct ifaddr *
553 ifa_ifwithroute(int flags, const struct sockaddr *dst,
554     const struct sockaddr *gateway, u_int fibnum)
555 {
556 	struct ifaddr *ifa;
557 
558 	NET_EPOCH_ASSERT();
559 	if ((flags & RTF_GATEWAY) == 0) {
560 		/*
561 		 * If we are adding a route to an interface,
562 		 * and the interface is a pt to pt link
563 		 * we should search for the destination
564 		 * as our clue to the interface.  Otherwise
565 		 * we can use the local address.
566 		 */
567 		ifa = NULL;
568 		if (flags & RTF_HOST)
569 			ifa = ifa_ifwithdstaddr(dst, fibnum);
570 		if (ifa == NULL)
571 			ifa = ifa_ifwithaddr(gateway);
572 	} else {
573 		/*
574 		 * If we are adding a route to a remote net
575 		 * or host, the gateway may still be on the
576 		 * other end of a pt to pt link.
577 		 */
578 		ifa = ifa_ifwithdstaddr(gateway, fibnum);
579 	}
580 	if (ifa == NULL)
581 		ifa = ifa_ifwithnet(gateway, 0, fibnum);
582 	if (ifa == NULL) {
583 		struct nhop_object *nh;
584 
585 		nh = rib_lookup(fibnum, gateway, NHR_NONE, 0);
586 
587 		/*
588 		 * dismiss a gateway that is reachable only
589 		 * through the default router
590 		 */
591 		if ((nh == NULL) || (nh->nh_flags & NHF_DEFAULT))
592 			return (NULL);
593 		ifa = nh->nh_ifa;
594 	}
595 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
596 		struct ifaddr *oifa = ifa;
597 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
598 		if (ifa == NULL)
599 			ifa = oifa;
600 	}
601 
602 	return (ifa);
603 }
604 
605 /*
606  * Do appropriate manipulations of a routing tree given
607  * all the bits of info needed
608  */
609 int
610 rtrequest_fib(int req,
611 	struct sockaddr *dst,
612 	struct sockaddr *gateway,
613 	struct sockaddr *netmask,
614 	int flags,
615 	struct rtentry **ret_nrt,
616 	u_int fibnum)
617 {
618 	struct rt_addrinfo info;
619 
620 	if (dst->sa_len == 0)
621 		return(EINVAL);
622 
623 	bzero((caddr_t)&info, sizeof(info));
624 	info.rti_flags = flags;
625 	info.rti_info[RTAX_DST] = dst;
626 	info.rti_info[RTAX_GATEWAY] = gateway;
627 	info.rti_info[RTAX_NETMASK] = netmask;
628 	return rtrequest1_fib(req, &info, ret_nrt, fibnum);
629 }
630 
631 
632 /*
633  * Copy most of @rt data into @info.
634  *
635  * If @flags contains NHR_COPY, copies dst,netmask and gw to the
636  * pointers specified by @info structure. Assume such pointers
637  * are zeroed sockaddr-like structures with sa_len field initialized
638  * to reflect size of the provided buffer. if no NHR_COPY is specified,
639  * point dst,netmask and gw @info fields to appropriate @rt values.
640  *
641  * if @flags contains NHR_REF, do refcouting on rt_ifp and rt_ifa.
642  *
643  * Returns 0 on success.
644  */
645 int
646 rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info, int flags)
647 {
648 	struct rt_metrics *rmx;
649 	struct sockaddr *src, *dst;
650 	struct nhop_object *nh;
651 	int sa_len;
652 
653 	if (flags & NHR_COPY) {
654 		/* Copy destination if dst is non-zero */
655 		src = rt_key(rt);
656 		dst = info->rti_info[RTAX_DST];
657 		sa_len = src->sa_len;
658 		if (dst != NULL) {
659 			if (src->sa_len > dst->sa_len)
660 				return (ENOMEM);
661 			memcpy(dst, src, src->sa_len);
662 			info->rti_addrs |= RTA_DST;
663 		}
664 
665 		/* Copy mask if set && dst is non-zero */
666 		src = rt_mask(rt);
667 		dst = info->rti_info[RTAX_NETMASK];
668 		if (src != NULL && dst != NULL) {
669 
670 			/*
671 			 * Radix stores different value in sa_len,
672 			 * assume rt_mask() to have the same length
673 			 * as rt_key()
674 			 */
675 			if (sa_len > dst->sa_len)
676 				return (ENOMEM);
677 			memcpy(dst, src, src->sa_len);
678 			info->rti_addrs |= RTA_NETMASK;
679 		}
680 
681 		/* Copy gateway is set && dst is non-zero */
682 		src = &rt->rt_nhop->gw_sa;
683 		dst = info->rti_info[RTAX_GATEWAY];
684 		if ((rt->rt_flags & RTF_GATEWAY) && src != NULL && dst != NULL){
685 			if (src->sa_len > dst->sa_len)
686 				return (ENOMEM);
687 			memcpy(dst, src, src->sa_len);
688 			info->rti_addrs |= RTA_GATEWAY;
689 		}
690 	} else {
691 		info->rti_info[RTAX_DST] = rt_key(rt);
692 		info->rti_addrs |= RTA_DST;
693 		if (rt_mask(rt) != NULL) {
694 			info->rti_info[RTAX_NETMASK] = rt_mask(rt);
695 			info->rti_addrs |= RTA_NETMASK;
696 		}
697 		if (rt->rt_flags & RTF_GATEWAY) {
698 			info->rti_info[RTAX_GATEWAY] = &rt->rt_nhop->gw_sa;
699 			info->rti_addrs |= RTA_GATEWAY;
700 		}
701 	}
702 
703 	nh = rt->rt_nhop;
704 	rmx = info->rti_rmx;
705 	if (rmx != NULL) {
706 		info->rti_mflags |= RTV_MTU;
707 		rmx->rmx_mtu = nh->nh_mtu;
708 	}
709 
710 	info->rti_flags = rt->rt_flags | nhop_get_rtflags(nh);
711 	info->rti_ifp = nh->nh_ifp;
712 	info->rti_ifa = nh->nh_ifa;
713 	if (flags & NHR_REF) {
714 		if_ref(info->rti_ifp);
715 		ifa_ref(info->rti_ifa);
716 	}
717 
718 	return (0);
719 }
720 
721 /*
722  * Lookups up route entry for @dst in RIB database for fib @fibnum.
723  * Exports entry data to @info using rt_exportinfo().
724  *
725  * If @flags contains NHR_REF, refcouting is performed on rt_ifp and rt_ifa.
726  * All references can be released later by calling rib_free_info().
727  *
728  * Returns 0 on success.
729  * Returns ENOENT for lookup failure, ENOMEM for export failure.
730  */
731 int
732 rib_lookup_info(uint32_t fibnum, const struct sockaddr *dst, uint32_t flags,
733     uint32_t flowid, struct rt_addrinfo *info)
734 {
735 	RIB_RLOCK_TRACKER;
736 	struct rib_head *rh;
737 	struct radix_node *rn;
738 	struct rtentry *rt;
739 	int error;
740 
741 	KASSERT((fibnum < rt_numfibs), ("rib_lookup_rte: bad fibnum"));
742 	rh = rt_tables_get_rnh(fibnum, dst->sa_family);
743 	if (rh == NULL)
744 		return (ENOENT);
745 
746 	RIB_RLOCK(rh);
747 	rn = rh->rnh_matchaddr(__DECONST(void *, dst), &rh->head);
748 	if (rn != NULL && ((rn->rn_flags & RNF_ROOT) == 0)) {
749 		rt = RNTORT(rn);
750 		/* Ensure route & ifp is UP */
751 		if (RT_LINK_IS_UP(rt->rt_nhop->nh_ifp)) {
752 			flags = (flags & NHR_REF) | NHR_COPY;
753 			error = rt_exportinfo(rt, info, flags);
754 			RIB_RUNLOCK(rh);
755 
756 			return (error);
757 		}
758 	}
759 	RIB_RUNLOCK(rh);
760 
761 	return (ENOENT);
762 }
763 
764 /*
765  * Releases all references acquired by rib_lookup_info() when
766  * called with NHR_REF flags.
767  */
768 void
769 rib_free_info(struct rt_addrinfo *info)
770 {
771 
772 	ifa_free(info->rti_ifa);
773 	if_rele(info->rti_ifp);
774 }
775 
776 /*
777  * Iterates over all existing fibs in system calling
778  *  @setwa_f function prior to traversing each fib.
779  *  Calls @wa_f function for each element in current fib.
780  * If af is not AF_UNSPEC, iterates over fibs in particular
781  * address family.
782  */
783 void
784 rt_foreach_fib_walk(int af, rt_setwarg_t *setwa_f, rt_walktree_f_t *wa_f,
785     void *arg)
786 {
787 	struct rib_head *rnh;
788 	uint32_t fibnum;
789 	int i;
790 
791 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
792 		/* Do we want some specific family? */
793 		if (af != AF_UNSPEC) {
794 			rnh = rt_tables_get_rnh(fibnum, af);
795 			if (rnh == NULL)
796 				continue;
797 			if (setwa_f != NULL)
798 				setwa_f(rnh, fibnum, af, arg);
799 
800 			RIB_WLOCK(rnh);
801 			rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
802 			RIB_WUNLOCK(rnh);
803 			continue;
804 		}
805 
806 		for (i = 1; i <= AF_MAX; i++) {
807 			rnh = rt_tables_get_rnh(fibnum, i);
808 			if (rnh == NULL)
809 				continue;
810 			if (setwa_f != NULL)
811 				setwa_f(rnh, fibnum, i, arg);
812 
813 			RIB_WLOCK(rnh);
814 			rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
815 			RIB_WUNLOCK(rnh);
816 		}
817 	}
818 }
819 
820 /*
821  * Iterates over all existing fibs in system and deletes each element
822  *  for which @filter_f function returns non-zero value.
823  * If @family is not AF_UNSPEC, iterates over fibs in particular
824  * address family.
825  */
826 void
827 rt_foreach_fib_walk_del(int family, rt_filter_f_t *filter_f, void *arg)
828 {
829 	u_int fibnum;
830 	int i, start, end;
831 
832 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
833 		/* Do we want some specific family? */
834 		if (family != AF_UNSPEC) {
835 			start = family;
836 			end = family;
837 		} else {
838 			start = 1;
839 			end = AF_MAX;
840 		}
841 
842 		for (i = start; i <= end; i++) {
843 			if (rt_tables_get_rnh(fibnum, i) == NULL)
844 				continue;
845 
846 			rib_walk_del(fibnum, i, filter_f, arg, 0);
847 		}
848 	}
849 }
850 
851 /*
852  * Delete Routes for a Network Interface
853  *
854  * Called for each routing entry via the rnh->rnh_walktree() call above
855  * to delete all route entries referencing a detaching network interface.
856  *
857  * Arguments:
858  *	rt	pointer to rtentry
859  *	nh	pointer to nhop
860  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
861  *
862  * Returns:
863  *	0	successful
864  *	errno	failed - reason indicated
865  */
866 static int
867 rt_ifdelroute(const struct rtentry *rt, const struct nhop_object *nh, void *arg)
868 {
869 	struct ifnet	*ifp = arg;
870 
871 	if (nh->nh_ifp != ifp)
872 		return (0);
873 
874 	/*
875 	 * Protect (sorta) against walktree recursion problems
876 	 * with cloned routes
877 	 */
878 	if ((rt->rt_flags & RTF_UP) == 0)
879 		return (0);
880 
881 	return (1);
882 }
883 
884 /*
885  * Delete all remaining routes using this interface
886  * Unfortuneatly the only way to do this is to slog through
887  * the entire routing table looking for routes which point
888  * to this interface...oh well...
889  */
890 void
891 rt_flushifroutes_af(struct ifnet *ifp, int af)
892 {
893 	KASSERT((af >= 1 && af <= AF_MAX), ("%s: af %d not >= 1 and <= %d",
894 	    __func__, af, AF_MAX));
895 
896 	rt_foreach_fib_walk_del(af, rt_ifdelroute, ifp);
897 }
898 
899 void
900 rt_flushifroutes(struct ifnet *ifp)
901 {
902 
903 	rt_foreach_fib_walk_del(AF_UNSPEC, rt_ifdelroute, ifp);
904 }
905 
906 /*
907  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
908  * it will be referenced so the caller must free it.
909  *
910  * Assume basic consistency checks are executed by callers:
911  * RTAX_DST exists, if RTF_GATEWAY is set, RTAX_GATEWAY exists as well.
912  */
913 int
914 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
915 {
916 	const struct sockaddr *dst, *gateway, *ifpaddr, *ifaaddr;
917 	struct epoch_tracker et;
918 	int needref, error, flags;
919 
920 	dst = info->rti_info[RTAX_DST];
921 	gateway = info->rti_info[RTAX_GATEWAY];
922 	ifpaddr = info->rti_info[RTAX_IFP];
923 	ifaaddr = info->rti_info[RTAX_IFA];
924 	flags = info->rti_flags;
925 
926 	/*
927 	 * ifp may be specified by sockaddr_dl
928 	 * when protocol address is ambiguous.
929 	 */
930 	error = 0;
931 	needref = (info->rti_ifa == NULL);
932 	NET_EPOCH_ENTER(et);
933 
934 	/* If we have interface specified by the ifindex in the address, use it */
935 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
936 	    ifpaddr->sa_family == AF_LINK) {
937 	    const struct sockaddr_dl *sdl = (const struct sockaddr_dl *)ifpaddr;
938 	    if (sdl->sdl_index != 0)
939 		    info->rti_ifp = ifnet_byindex(sdl->sdl_index);
940 	}
941 	/*
942 	 * If we have source address specified, try to find it
943 	 * TODO: avoid enumerating all ifas on all interfaces.
944 	 */
945 	if (info->rti_ifa == NULL && ifaaddr != NULL)
946 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
947 	if (info->rti_ifa == NULL) {
948 		const struct sockaddr *sa;
949 
950 		/*
951 		 * Most common use case for the userland-supplied routes.
952 		 *
953 		 * Choose sockaddr to select ifa.
954 		 * -- if ifp is set --
955 		 * Order of preference:
956 		 * 1) IFA address
957 		 * 2) gateway address
958 		 *   Note: for interface routes link-level gateway address
959 		 *     is specified to indicate the interface index without
960 		 *     specifying RTF_GATEWAY. In this case, ignore gateway
961 		 *   Note: gateway AF may be different from dst AF. In this case,
962 		 *   ignore gateway
963 		 * 3) final destination.
964 		 * 4) if all of these fails, try to get at least link-level ifa.
965 		 * -- else --
966 		 * try to lookup gateway or dst in the routing table to get ifa
967 		 */
968 		if (info->rti_info[RTAX_IFA] != NULL)
969 			sa = info->rti_info[RTAX_IFA];
970 		else if ((info->rti_flags & RTF_GATEWAY) != 0 &&
971 		    gateway->sa_family == dst->sa_family)
972 			sa = gateway;
973 		else
974 			sa = dst;
975 		if (info->rti_ifp != NULL) {
976 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
977 			/* Case 4 */
978 			if (info->rti_ifa == NULL && gateway != NULL)
979 				info->rti_ifa = ifaof_ifpforaddr(gateway, info->rti_ifp);
980 		} else if (dst != NULL && gateway != NULL)
981 			info->rti_ifa = ifa_ifwithroute(flags, dst, gateway,
982 							fibnum);
983 		else if (sa != NULL)
984 			info->rti_ifa = ifa_ifwithroute(flags, sa, sa,
985 							fibnum);
986 	}
987 	if (needref && info->rti_ifa != NULL) {
988 		if (info->rti_ifp == NULL)
989 			info->rti_ifp = info->rti_ifa->ifa_ifp;
990 		ifa_ref(info->rti_ifa);
991 	} else
992 		error = ENETUNREACH;
993 	NET_EPOCH_EXIT(et);
994 	return (error);
995 }
996 
997 void
998 rt_updatemtu(struct ifnet *ifp)
999 {
1000 	struct rib_head *rnh;
1001 	int mtu;
1002 	int i, j;
1003 
1004 	/*
1005 	 * Try to update rt_mtu for all routes using this interface
1006 	 * Unfortunately the only way to do this is to traverse all
1007 	 * routing tables in all fibs/domains.
1008 	 */
1009 	for (i = 1; i <= AF_MAX; i++) {
1010 		mtu = if_getmtu_family(ifp, i);
1011 		for (j = 0; j < rt_numfibs; j++) {
1012 			rnh = rt_tables_get_rnh(j, i);
1013 			if (rnh == NULL)
1014 				continue;
1015 			nhops_update_ifmtu(rnh, ifp, mtu);
1016 		}
1017 	}
1018 }
1019 
1020 
1021 #if 0
1022 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
1023 int rt_print(char *buf, int buflen, struct rtentry *rt);
1024 
1025 int
1026 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
1027 {
1028 	void *paddr = NULL;
1029 
1030 	switch (s->sa_family) {
1031 	case AF_INET:
1032 		paddr = &((struct sockaddr_in *)s)->sin_addr;
1033 		break;
1034 	case AF_INET6:
1035 		paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
1036 		break;
1037 	}
1038 
1039 	if (paddr == NULL)
1040 		return (0);
1041 
1042 	if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
1043 		return (0);
1044 
1045 	return (strlen(buf));
1046 }
1047 
1048 int
1049 rt_print(char *buf, int buflen, struct rtentry *rt)
1050 {
1051 	struct sockaddr *addr, *mask;
1052 	int i = 0;
1053 
1054 	addr = rt_key(rt);
1055 	mask = rt_mask(rt);
1056 
1057 	i = p_sockaddr(buf, buflen, addr);
1058 	if (!(rt->rt_flags & RTF_HOST)) {
1059 		buf[i++] = '/';
1060 		i += p_sockaddr(buf + i, buflen - i, mask);
1061 	}
1062 
1063 	if (rt->rt_flags & RTF_GATEWAY) {
1064 		buf[i++] = '>';
1065 		i += p_sockaddr(buf + i, buflen - i, &rt->rt_nhop->gw_sa);
1066 	}
1067 
1068 	return (i);
1069 }
1070 #endif
1071 
1072 #ifdef RADIX_MPATH
1073 /*
1074  * Deletes key for single-path routes, unlinks rtentry with
1075  * gateway specified in @info from multi-path routes.
1076  *
1077  * Returnes unlinked entry. In case of failure, returns NULL
1078  * and sets @perror to ESRCH.
1079  */
1080 struct radix_node *
1081 rt_mpath_unlink(struct rib_head *rnh, struct rt_addrinfo *info,
1082     struct rtentry *rto, int *perror)
1083 {
1084 	/*
1085 	 * if we got multipath routes, we require users to specify
1086 	 * a matching RTAX_GATEWAY.
1087 	 */
1088 	struct rtentry *rt; // *rto = NULL;
1089 	struct radix_node *rn;
1090 	struct sockaddr *gw;
1091 
1092 	gw = info->rti_info[RTAX_GATEWAY];
1093 	rt = rt_mpath_matchgate(rto, gw);
1094 	if (rt == NULL) {
1095 		*perror = ESRCH;
1096 		return (NULL);
1097 	}
1098 
1099 	/*
1100 	 * this is the first entry in the chain
1101 	 */
1102 	if (rto == rt) {
1103 		rn = rn_mpath_next((struct radix_node *)rt);
1104 		/*
1105 		 * there is another entry, now it's active
1106 		 */
1107 		if (rn) {
1108 			rto = RNTORT(rn);
1109 			RT_LOCK(rto);
1110 			rto->rt_flags |= RTF_UP;
1111 			RT_UNLOCK(rto);
1112 		} else if (rt->rt_flags & RTF_GATEWAY) {
1113 			/*
1114 			 * For gateway routes, we need to
1115 			 * make sure that we we are deleting
1116 			 * the correct gateway.
1117 			 * rt_mpath_matchgate() does not
1118 			 * check the case when there is only
1119 			 * one route in the chain.
1120 			 */
1121 			if (gw &&
1122 			    (rt->rt_nhop->gw_sa.sa_len != gw->sa_len ||
1123 				memcmp(&rt->rt_nhop->gw_sa, gw, gw->sa_len))) {
1124 				*perror = ESRCH;
1125 				return (NULL);
1126 			}
1127 		}
1128 
1129 		/*
1130 		 * use the normal delete code to remove
1131 		 * the first entry
1132 		 */
1133 		rn = rnh->rnh_deladdr(info->rti_info[RTAX_DST],
1134 					info->rti_info[RTAX_NETMASK],
1135 					&rnh->head);
1136 		*perror = 0;
1137 		return (rn);
1138 	}
1139 
1140 	/*
1141 	 * if the entry is 2nd and on up
1142 	 */
1143 	if (rt_mpath_deldup(rto, rt) == 0)
1144 		panic ("rtrequest1: rt_mpath_deldup");
1145 	*perror = 0;
1146 	rn = (struct radix_node *)rt;
1147 	return (rn);
1148 }
1149 #endif
1150 
1151 int
1152 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1153 				u_int fibnum)
1154 {
1155 	const struct sockaddr *dst;
1156 	struct rib_head *rnh;
1157 	struct rib_cmd_info rc;
1158 	int error;
1159 
1160 	KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1161 	KASSERT((info->rti_flags & RTF_RNH_LOCKED) == 0, ("rtrequest1_fib: locked"));
1162 	NET_EPOCH_ASSERT();
1163 
1164 	dst = info->rti_info[RTAX_DST];
1165 
1166 	switch (dst->sa_family) {
1167 	case AF_INET6:
1168 	case AF_INET:
1169 		/* We support multiple FIBs. */
1170 		break;
1171 	default:
1172 		fibnum = RT_DEFAULT_FIB;
1173 		break;
1174 	}
1175 
1176 	/*
1177 	 * Find the correct routing tree to use for this Address Family
1178 	 */
1179 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1180 	if (rnh == NULL)
1181 		return (EAFNOSUPPORT);
1182 
1183 	/*
1184 	 * If we are adding a host route then we don't want to put
1185 	 * a netmask in the tree, nor do we want to clone it.
1186 	 */
1187 	if (info->rti_flags & RTF_HOST)
1188 		info->rti_info[RTAX_NETMASK] = NULL;
1189 
1190 	bzero(&rc, sizeof(struct rib_cmd_info));
1191 	error = 0;
1192 	switch (req) {
1193 	case RTM_DELETE:
1194 		error = del_route(rnh, info, &rc);
1195 		break;
1196 	case RTM_RESOLVE:
1197 		/*
1198 		 * resolve was only used for route cloning
1199 		 * here for compat
1200 		 */
1201 		break;
1202 	case RTM_ADD:
1203 		error = add_route(rnh, info, &rc);
1204 		break;
1205 	case RTM_CHANGE:
1206 		error = change_route(rnh, info, &rc);
1207 		break;
1208 	default:
1209 		error = EOPNOTSUPP;
1210 	}
1211 
1212 	if (ret_nrt != NULL)
1213 		*ret_nrt = rc.rc_rt;
1214 
1215 	return (error);
1216 }
1217 
1218 void
1219 rt_setmetrics(const struct rt_addrinfo *info, struct rtentry *rt)
1220 {
1221 
1222 	if (info->rti_mflags & RTV_WEIGHT)
1223 		rt->rt_weight = info->rti_rmx->rmx_weight;
1224 	/* Kernel -> userland timebase conversion. */
1225 	if (info->rti_mflags & RTV_EXPIRE)
1226 		rt->rt_expire = info->rti_rmx->rmx_expire ?
1227 		    info->rti_rmx->rmx_expire - time_second + time_uptime : 0;
1228 }
1229 
1230 void
1231 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1232 {
1233 	u_char *cp1 = (u_char *)src;
1234 	u_char *cp2 = (u_char *)dst;
1235 	u_char *cp3 = (u_char *)netmask;
1236 	u_char *cplim = cp2 + *cp3;
1237 	u_char *cplim2 = cp2 + *cp1;
1238 
1239 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1240 	cp3 += 2;
1241 	if (cplim > cplim2)
1242 		cplim = cplim2;
1243 	while (cp2 < cplim)
1244 		*cp2++ = *cp1++ & *cp3++;
1245 	if (cp2 < cplim2)
1246 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1247 }
1248 
1249 /*
1250  * Set up a routing table entry, normally
1251  * for an interface.
1252  */
1253 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1254 static inline  int
1255 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1256 {
1257 	RIB_RLOCK_TRACKER;
1258 	struct epoch_tracker et;
1259 	struct sockaddr *dst;
1260 	struct sockaddr *netmask;
1261 	struct rtentry *rt = NULL;
1262 	struct rt_addrinfo info;
1263 	int error = 0;
1264 	int startfib, endfib;
1265 	char tempbuf[_SOCKADDR_TMPSIZE];
1266 	int didwork = 0;
1267 	int a_failure = 0;
1268 	struct sockaddr_dl_short *sdl = NULL;
1269 	struct rib_head *rnh;
1270 
1271 	if (flags & RTF_HOST) {
1272 		dst = ifa->ifa_dstaddr;
1273 		netmask = NULL;
1274 	} else {
1275 		dst = ifa->ifa_addr;
1276 		netmask = ifa->ifa_netmask;
1277 	}
1278 	if (dst->sa_len == 0)
1279 		return(EINVAL);
1280 	switch (dst->sa_family) {
1281 	case AF_INET6:
1282 	case AF_INET:
1283 		/* We support multiple FIBs. */
1284 		break;
1285 	default:
1286 		fibnum = RT_DEFAULT_FIB;
1287 		break;
1288 	}
1289 	if (fibnum == RT_ALL_FIBS) {
1290 		if (V_rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD)
1291 			startfib = endfib = ifa->ifa_ifp->if_fib;
1292 		else {
1293 			startfib = 0;
1294 			endfib = rt_numfibs - 1;
1295 		}
1296 	} else {
1297 		KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1298 		startfib = fibnum;
1299 		endfib = fibnum;
1300 	}
1301 
1302 	/*
1303 	 * If it's a delete, check that if it exists,
1304 	 * it's on the correct interface or we might scrub
1305 	 * a route to another ifa which would
1306 	 * be confusing at best and possibly worse.
1307 	 */
1308 	if (cmd == RTM_DELETE) {
1309 		/*
1310 		 * It's a delete, so it should already exist..
1311 		 * If it's a net, mask off the host bits
1312 		 * (Assuming we have a mask)
1313 		 * XXX this is kinda inet specific..
1314 		 */
1315 		if (netmask != NULL) {
1316 			rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
1317 			dst = (struct sockaddr *)tempbuf;
1318 		}
1319 	} else if (cmd == RTM_ADD) {
1320 		sdl = (struct sockaddr_dl_short *)tempbuf;
1321 		bzero(sdl, sizeof(struct sockaddr_dl_short));
1322 		sdl->sdl_family = AF_LINK;
1323 		sdl->sdl_len = sizeof(struct sockaddr_dl_short);
1324 		sdl->sdl_type = ifa->ifa_ifp->if_type;
1325 		sdl->sdl_index = ifa->ifa_ifp->if_index;
1326         }
1327 	/*
1328 	 * Now go through all the requested tables (fibs) and do the
1329 	 * requested action. Realistically, this will either be fib 0
1330 	 * for protocols that don't do multiple tables or all the
1331 	 * tables for those that do.
1332 	 */
1333 	for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
1334 		if (cmd == RTM_DELETE) {
1335 			struct radix_node *rn;
1336 			/*
1337 			 * Look up an rtentry that is in the routing tree and
1338 			 * contains the correct info.
1339 			 */
1340 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1341 			if (rnh == NULL)
1342 				/* this table doesn't exist but others might */
1343 				continue;
1344 			RIB_RLOCK(rnh);
1345 			rn = rnh->rnh_lookup(dst, netmask, &rnh->head);
1346 #ifdef RADIX_MPATH
1347 			if (rt_mpath_capable(rnh)) {
1348 
1349 				if (rn == NULL)
1350 					error = ESRCH;
1351 				else {
1352 					rt = RNTORT(rn);
1353 					/*
1354 					 * for interface route the gateway
1355 					 * gateway is sockaddr_dl, so
1356 					 * rt_mpath_matchgate must use the
1357 					 * interface address
1358 					 */
1359 					rt = rt_mpath_matchgate(rt,
1360 					    ifa->ifa_addr);
1361 					if (rt == NULL)
1362 						error = ESRCH;
1363 				}
1364 			}
1365 #endif
1366 			error = (rn == NULL ||
1367 			    (rn->rn_flags & RNF_ROOT) ||
1368 			    RNTORT(rn)->rt_nhop->nh_ifa != ifa);
1369 			RIB_RUNLOCK(rnh);
1370 			if (error) {
1371 				/* this is only an error if bad on ALL tables */
1372 				continue;
1373 			}
1374 		}
1375 		/*
1376 		 * Do the actual request
1377 		 */
1378 		bzero((caddr_t)&info, sizeof(info));
1379 		info.rti_ifa = ifa;
1380 		info.rti_flags = flags |
1381 		    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1382 		info.rti_info[RTAX_DST] = dst;
1383 		/*
1384 		 * doing this for compatibility reasons
1385 		 */
1386 		if (cmd == RTM_ADD)
1387 			info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)sdl;
1388 		else
1389 			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1390 		info.rti_info[RTAX_NETMASK] = netmask;
1391 		NET_EPOCH_ENTER(et);
1392 		error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1393 		if (error == 0 && rt != NULL) {
1394 			/*
1395 			 * notify any listening routing agents of the change
1396 			 */
1397 
1398 			/* TODO: interface routes/aliases */
1399 			rt_newaddrmsg_fib(cmd, ifa, rt, fibnum);
1400 			didwork = 1;
1401 		}
1402 		NET_EPOCH_EXIT(et);
1403 		if (error)
1404 			a_failure = error;
1405 	}
1406 	if (cmd == RTM_DELETE) {
1407 		if (didwork) {
1408 			error = 0;
1409 		} else {
1410 			/* we only give an error if it wasn't in any table */
1411 			error = ((flags & RTF_HOST) ?
1412 			    EHOSTUNREACH : ENETUNREACH);
1413 		}
1414 	} else {
1415 		if (a_failure) {
1416 			/* return an error if any of them failed */
1417 			error = a_failure;
1418 		}
1419 	}
1420 	return (error);
1421 }
1422 
1423 /*
1424  * Set up a routing table entry, normally
1425  * for an interface.
1426  */
1427 int
1428 rtinit(struct ifaddr *ifa, int cmd, int flags)
1429 {
1430 	struct sockaddr *dst;
1431 	int fib = RT_DEFAULT_FIB;
1432 
1433 	if (flags & RTF_HOST) {
1434 		dst = ifa->ifa_dstaddr;
1435 	} else {
1436 		dst = ifa->ifa_addr;
1437 	}
1438 
1439 	switch (dst->sa_family) {
1440 	case AF_INET6:
1441 	case AF_INET:
1442 		/* We do support multiple FIBs. */
1443 		fib = RT_ALL_FIBS;
1444 		break;
1445 	}
1446 	return (rtinit1(ifa, cmd, flags, fib));
1447 }
1448 
1449 /*
1450  * Announce interface address arrival/withdraw
1451  * Returns 0 on success.
1452  */
1453 int
1454 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
1455 {
1456 
1457 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1458 	    ("unexpected cmd %d", cmd));
1459 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1460 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1461 
1462 	EVENTHANDLER_DIRECT_INVOKE(rt_addrmsg, ifa, cmd);
1463 	return (rtsock_addrmsg(cmd, ifa, fibnum));
1464 }
1465 
1466 /*
1467  * Announce kernel-originated route addition/removal to rtsock based on @rt data.
1468  * cmd: RTM_ cmd
1469  * @rt: valid rtentry
1470  * @ifp: target route interface
1471  * @fibnum: fib id or RT_ALL_FIBS
1472  *
1473  * Returns 0 on success.
1474  */
1475 int
1476 rt_routemsg(int cmd, struct rtentry *rt, struct ifnet *ifp, int rti_addrs,
1477     int fibnum)
1478 {
1479 
1480 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1481 	    ("unexpected cmd %d", cmd));
1482 
1483 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1484 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1485 
1486 	KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
1487 
1488 	return (rtsock_routemsg(cmd, rt, ifp, 0, fibnum));
1489 }
1490 
1491 /*
1492  * Announce kernel-originated route addition/removal to rtsock based on @rt data.
1493  * cmd: RTM_ cmd
1494  * @info: addrinfo structure with valid data.
1495  * @fibnum: fib id or RT_ALL_FIBS
1496  *
1497  * Returns 0 on success.
1498  */
1499 int
1500 rt_routemsg_info(int cmd, struct rt_addrinfo *info, int fibnum)
1501 {
1502 
1503 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE || cmd == RTM_CHANGE,
1504 	    ("unexpected cmd %d", cmd));
1505 
1506 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1507 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1508 
1509 	KASSERT(info->rti_info[RTAX_DST] != NULL, (":%s: RTAX_DST must be supplied", __func__));
1510 
1511 	return (rtsock_routemsg_info(cmd, info, fibnum));
1512 }
1513 
1514 
1515 /*
1516  * This is called to generate messages from the routing socket
1517  * indicating a network interface has had addresses associated with it.
1518  */
1519 void
1520 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, struct rtentry *rt, int fibnum)
1521 {
1522 
1523 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1524 		("unexpected cmd %u", cmd));
1525 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1526 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1527 
1528 	if (cmd == RTM_ADD) {
1529 		rt_addrmsg(cmd, ifa, fibnum);
1530 		if (rt != NULL)
1531 			rt_routemsg(cmd, rt, ifa->ifa_ifp, 0, fibnum);
1532 	} else {
1533 		if (rt != NULL)
1534 			rt_routemsg(cmd, rt, ifa->ifa_ifp, 0, fibnum);
1535 		rt_addrmsg(cmd, ifa, fibnum);
1536 	}
1537 }
1538 
1539