xref: /freebsd/sys/net/route.c (revision 65a1d63665bf8b9cd2596d4319b31efc2232b722)
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_var.h>
65 #include <net/route/nhop.h>
66 #include <net/route/shared.h>
67 #include <net/vnet.h>
68 
69 #ifdef RADIX_MPATH
70 #include <net/radix_mpath.h>
71 #endif
72 
73 #include <netinet/in.h>
74 #include <netinet/ip_mroute.h>
75 
76 #include <vm/uma.h>
77 
78 #define	RT_MAXFIBS	UINT16_MAX
79 
80 /* Kernel config default option. */
81 #ifdef ROUTETABLES
82 #if ROUTETABLES <= 0
83 #error "ROUTETABLES defined too low"
84 #endif
85 #if ROUTETABLES > RT_MAXFIBS
86 #error "ROUTETABLES defined too big"
87 #endif
88 #define	RT_NUMFIBS	ROUTETABLES
89 #endif /* ROUTETABLES */
90 /* Initialize to default if not otherwise set. */
91 #ifndef	RT_NUMFIBS
92 #define	RT_NUMFIBS	1
93 #endif
94 
95 /* This is read-only.. */
96 u_int rt_numfibs = RT_NUMFIBS;
97 SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RDTUN, &rt_numfibs, 0, "");
98 
99 /*
100  * By default add routes to all fibs for new interfaces.
101  * Once this is set to 0 then only allocate routes on interface
102  * changes for the FIB of the caller when adding a new set of addresses
103  * to an interface.  XXX this is a shotgun aproach to a problem that needs
104  * a more fine grained solution.. that will come.
105  * XXX also has the problems getting the FIB from curthread which will not
106  * always work given the fib can be overridden and prefixes can be added
107  * from the network stack context.
108  */
109 VNET_DEFINE(u_int, rt_add_addr_allfibs) = 1;
110 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RWTUN | CTLFLAG_VNET,
111     &VNET_NAME(rt_add_addr_allfibs), 0, "");
112 
113 VNET_PCPUSTAT_DEFINE(struct rtstat, rtstat);
114 
115 VNET_PCPUSTAT_SYSINIT(rtstat);
116 #ifdef VIMAGE
117 VNET_PCPUSTAT_SYSUNINIT(rtstat);
118 #endif
119 
120 VNET_DEFINE(struct rib_head *, rt_tables);
121 #define	V_rt_tables	VNET(rt_tables)
122 
123 VNET_DEFINE(int, rttrash);		/* routes not in table but not freed */
124 #define	V_rttrash	VNET(rttrash)
125 
126 
127 /*
128  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
129  * The operation can be done safely (in this code) because a
130  * 'struct rtentry' starts with two 'struct radix_node''s, the first
131  * one representing leaf nodes in the routing tree, which is
132  * what the code in radix.c passes us as a 'struct radix_node'.
133  *
134  * But because there are a lot of assumptions in this conversion,
135  * do not cast explicitly, but always use the macro below.
136  */
137 #define RNTORT(p)	((struct rtentry *)(p))
138 
139 VNET_DEFINE_STATIC(uma_zone_t, rtzone);		/* Routing table UMA zone. */
140 #define	V_rtzone	VNET(rtzone)
141 
142 EVENTHANDLER_LIST_DEFINE(rt_addrmsg);
143 
144 static int rt_getifa_fib(struct rt_addrinfo *, u_int);
145 static void rt_setmetrics(const struct rt_addrinfo *, struct rtentry *);
146 static int rt_ifdelroute(const struct rtentry *rt, const struct nhop_object *,
147     void *arg);
148 static struct rtentry *rt_unlinkrte(struct rib_head *rnh,
149     struct rt_addrinfo *info, int *perror);
150 static void rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info);
151 #ifdef RADIX_MPATH
152 static struct radix_node *rt_mpath_unlink(struct rib_head *rnh,
153     struct rt_addrinfo *info, struct rtentry *rto, int *perror);
154 #endif
155 static int rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info,
156     int flags);
157 
158 static int add_route(struct rib_head *rnh, struct rt_addrinfo *info,
159     struct rtentry **ret_nrt);
160 static int del_route(struct rib_head *rnh, struct rt_addrinfo *info,
161     struct rtentry **ret_nrt);
162 static int change_route(struct rib_head *, struct rt_addrinfo *,
163     struct rtentry **);
164 
165 /*
166  * handler for net.my_fibnum
167  */
168 static int
169 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
170 {
171         int fibnum;
172         int error;
173 
174         fibnum = curthread->td_proc->p_fibnum;
175         error = sysctl_handle_int(oidp, &fibnum, 0, req);
176         return (error);
177 }
178 
179 SYSCTL_PROC(_net, OID_AUTO, my_fibnum,
180     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
181     &sysctl_my_fibnum, "I",
182     "default FIB of caller");
183 
184 static __inline struct rib_head **
185 rt_tables_get_rnh_ptr(int table, int fam)
186 {
187 	struct rib_head **rnh;
188 
189 	KASSERT(table >= 0 && table < rt_numfibs,
190 	    ("%s: table out of bounds (0 <= %d < %d)", __func__, table,
191 	     rt_numfibs));
192 	KASSERT(fam >= 0 && fam < (AF_MAX + 1),
193 	    ("%s: fam out of bounds (0 <= %d < %d)", __func__, fam, AF_MAX+1));
194 
195 	/* rnh is [fib=0][af=0]. */
196 	rnh = (struct rib_head **)V_rt_tables;
197 	/* Get the offset to the requested table and fam. */
198 	rnh += table * (AF_MAX+1) + fam;
199 
200 	return (rnh);
201 }
202 
203 struct rib_head *
204 rt_tables_get_rnh(int table, int fam)
205 {
206 
207 	return (*rt_tables_get_rnh_ptr(table, fam));
208 }
209 
210 u_int
211 rt_tables_get_gen(int table, int fam)
212 {
213 	struct rib_head *rnh;
214 
215 	rnh = *rt_tables_get_rnh_ptr(table, fam);
216 	KASSERT(rnh != NULL, ("%s: NULL rib_head pointer table %d fam %d",
217 	    __func__, table, fam));
218 	return (rnh->rnh_gen);
219 }
220 
221 
222 /*
223  * route initialization must occur before ip6_init2(), which happenas at
224  * SI_ORDER_MIDDLE.
225  */
226 static void
227 route_init(void)
228 {
229 
230 	/* whack the tunable ints into  line. */
231 	if (rt_numfibs > RT_MAXFIBS)
232 		rt_numfibs = RT_MAXFIBS;
233 	if (rt_numfibs == 0)
234 		rt_numfibs = 1;
235 	nhops_init();
236 }
237 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, NULL);
238 
239 static int
240 rtentry_zinit(void *mem, int size, int how)
241 {
242 	struct rtentry *rt = mem;
243 
244 	RT_LOCK_INIT(rt);
245 
246 	return (0);
247 }
248 
249 static void
250 rtentry_zfini(void *mem, int size)
251 {
252 	struct rtentry *rt = mem;
253 
254 	RT_LOCK_DESTROY(rt);
255 }
256 
257 static int
258 rtentry_ctor(void *mem, int size, void *arg, int how)
259 {
260 	struct rtentry *rt = mem;
261 
262 	bzero(rt, offsetof(struct rtentry, rt_endzero));
263 	rt->rt_chain = NULL;
264 
265 	return (0);
266 }
267 
268 static void
269 rtentry_dtor(void *mem, int size, void *arg)
270 {
271 	struct rtentry *rt = mem;
272 
273 	RT_UNLOCK_COND(rt);
274 }
275 
276 static void
277 vnet_route_init(const void *unused __unused)
278 {
279 	struct domain *dom;
280 	struct rib_head **rnh;
281 	int table;
282 	int fam;
283 
284 	V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
285 	    sizeof(struct rib_head *), M_RTABLE, M_WAITOK|M_ZERO);
286 
287 	V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
288 	    rtentry_ctor, rtentry_dtor,
289 	    rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
290 	for (dom = domains; dom; dom = dom->dom_next) {
291 		if (dom->dom_rtattach == NULL)
292 			continue;
293 
294 		for  (table = 0; table < rt_numfibs; table++) {
295 			fam = dom->dom_family;
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_rtattach((void **)rnh, 0, table);
303 		}
304 	}
305 }
306 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
307     vnet_route_init, 0);
308 
309 #ifdef VIMAGE
310 static void
311 vnet_route_uninit(const void *unused __unused)
312 {
313 	int table;
314 	int fam;
315 	struct domain *dom;
316 	struct rib_head **rnh;
317 
318 	for (dom = domains; dom; dom = dom->dom_next) {
319 		if (dom->dom_rtdetach == NULL)
320 			continue;
321 
322 		for (table = 0; table < rt_numfibs; table++) {
323 			fam = dom->dom_family;
324 
325 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
326 				break;
327 
328 			rnh = rt_tables_get_rnh_ptr(table, fam);
329 			if (rnh == NULL)
330 				panic("%s: rnh NULL", __func__);
331 			dom->dom_rtdetach((void **)rnh, 0);
332 		}
333 	}
334 
335 	free(V_rt_tables, M_RTABLE);
336 	uma_zdestroy(V_rtzone);
337 }
338 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
339     vnet_route_uninit, 0);
340 #endif
341 
342 struct rib_head *
343 rt_table_init(int offset, int family, u_int fibnum)
344 {
345 	struct rib_head *rh;
346 
347 	rh = malloc(sizeof(struct rib_head), M_RTABLE, M_WAITOK | M_ZERO);
348 
349 	/* TODO: These details should be hidded inside radix.c */
350 	/* Init masks tree */
351 	rn_inithead_internal(&rh->head, rh->rnh_nodes, offset);
352 	rn_inithead_internal(&rh->rmhead.head, rh->rmhead.mask_nodes, 0);
353 	rh->head.rnh_masks = &rh->rmhead;
354 
355 	/* Save metadata associated with this routing table. */
356 	rh->rib_family = family;
357 	rh->rib_fibnum = fibnum;
358 #ifdef VIMAGE
359 	rh->rib_vnet = curvnet;
360 #endif
361 
362 	tmproutes_init(rh);
363 
364 	/* Init locks */
365 	RIB_LOCK_INIT(rh);
366 
367 	nhops_init_rib(rh);
368 
369 	/* Finally, set base callbacks */
370 	rh->rnh_addaddr = rn_addroute;
371 	rh->rnh_deladdr = rn_delete;
372 	rh->rnh_matchaddr = rn_match;
373 	rh->rnh_lookup = rn_lookup;
374 	rh->rnh_walktree = rn_walktree;
375 	rh->rnh_walktree_from = rn_walktree_from;
376 
377 	return (rh);
378 }
379 
380 static int
381 rt_freeentry(struct radix_node *rn, void *arg)
382 {
383 	struct radix_head * const rnh = arg;
384 	struct radix_node *x;
385 
386 	x = (struct radix_node *)rn_delete(rn + 2, NULL, rnh);
387 	if (x != NULL)
388 		R_Free(x);
389 	return (0);
390 }
391 
392 void
393 rt_table_destroy(struct rib_head *rh)
394 {
395 
396 	tmproutes_destroy(rh);
397 
398 	rn_walktree(&rh->rmhead.head, rt_freeentry, &rh->rmhead.head);
399 
400 	nhops_destroy_rib(rh);
401 
402 	/* Assume table is already empty */
403 	RIB_LOCK_DESTROY(rh);
404 	free(rh, M_RTABLE);
405 }
406 
407 
408 #ifndef _SYS_SYSPROTO_H_
409 struct setfib_args {
410 	int     fibnum;
411 };
412 #endif
413 int
414 sys_setfib(struct thread *td, struct setfib_args *uap)
415 {
416 	if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
417 		return EINVAL;
418 	td->td_proc->p_fibnum = uap->fibnum;
419 	return (0);
420 }
421 
422 /*
423  * Remove a reference count from an rtentry.
424  * If the count gets low enough, take it out of the routing table
425  */
426 void
427 rtfree(struct rtentry *rt)
428 {
429 
430 	KASSERT(rt != NULL,("%s: NULL rt", __func__));
431 
432 	RT_LOCK_ASSERT(rt);
433 
434 	/*
435 	 * The callers should use RTFREE_LOCKED() or RTFREE(), so
436 	 * we should come here exactly with the last reference.
437 	 */
438 	RT_REMREF(rt);
439 	if (rt->rt_refcnt > 0) {
440 		log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
441 		goto done;
442 	}
443 
444 	/*
445 	 * If we are no longer "up" (and ref == 0)
446 	 * then we can free the resources associated
447 	 * with the route.
448 	 */
449 	if ((rt->rt_flags & RTF_UP) == 0) {
450 		if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
451 			panic("rtfree 2");
452 		/*
453 		 * the rtentry must have been removed from the routing table
454 		 * so it is represented in rttrash.. remove that now.
455 		 */
456 		V_rttrash--;
457 #ifdef	DIAGNOSTIC
458 		if (rt->rt_refcnt < 0) {
459 			printf("rtfree: %p not freed (neg refs)\n", rt);
460 			goto done;
461 		}
462 #endif
463 
464 		/* Unreference nexthop */
465 		nhop_free(rt->rt_nhop);
466 
467 		/*
468 		 * and the rtentry itself of course
469 		 */
470 		uma_zfree(V_rtzone, rt);
471 		return;
472 	}
473 done:
474 	RT_UNLOCK(rt);
475 }
476 
477 /*
478  * Temporary RTFREE() function wrapper.
479  *  Intended to use in control plane code to
480  *  avoid exposing internal layout of 'struct rtentry'.
481  */
482 void
483 rtfree_func(struct rtentry *rt)
484 {
485 
486 	RTFREE(rt);
487 }
488 
489 /*
490  * Adds a temporal redirect entry to the routing table.
491  * @fibnum: fib number
492  * @dst: destination to install redirect to
493  * @gateway: gateway to go via
494  * @author: sockaddr of originating router, can be NULL
495  * @ifp: interface to use for the redirected route
496  * @flags: set of flags to add. Allowed: RTF_GATEWAY
497  * @lifetime_sec: time in seconds to expire this redirect.
498  *
499  * Retuns 0 on success, errno otherwise.
500  */
501 int
502 rib_add_redirect(u_int fibnum, struct sockaddr *dst, struct sockaddr *gateway,
503     struct sockaddr *author, struct ifnet *ifp, int flags, int lifetime_sec)
504 {
505 	struct rtentry *rt;
506 	int error;
507 	struct rt_addrinfo info;
508 	struct rt_metrics rti_rmx;
509 	struct ifaddr *ifa;
510 
511 	NET_EPOCH_ASSERT();
512 
513 	if (rt_tables_get_rnh(fibnum, dst->sa_family) == NULL)
514 		return (EAFNOSUPPORT);
515 
516 	/* Verify the allowed flag mask. */
517 	KASSERT(((flags & ~(RTF_GATEWAY)) == 0),
518 	    ("invalid redirect flags: %x", flags));
519 
520 	/* Get the best ifa for the given interface and gateway. */
521 	if ((ifa = ifaof_ifpforaddr(gateway, ifp)) == NULL)
522 		return (ENETUNREACH);
523 	ifa_ref(ifa);
524 
525 	bzero(&info, sizeof(info));
526 	info.rti_info[RTAX_DST] = dst;
527 	info.rti_info[RTAX_GATEWAY] = gateway;
528 	info.rti_ifa = ifa;
529 	info.rti_ifp = ifp;
530 	info.rti_flags = flags | RTF_HOST | RTF_DYNAMIC;
531 
532 	/* Setup route metrics to define expire time. */
533 	bzero(&rti_rmx, sizeof(rti_rmx));
534 	/* Set expire time as absolute. */
535 	rti_rmx.rmx_expire = lifetime_sec + time_second;
536 	info.rti_mflags |= RTV_EXPIRE;
537 	info.rti_rmx = &rti_rmx;
538 
539 	error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
540 	ifa_free(ifa);
541 
542 	if (error != 0) {
543 		/* TODO: add per-fib redirect stats. */
544 		return (error);
545 	}
546 
547 	RT_LOCK(rt);
548 	flags = rt->rt_flags;
549 	RTFREE_LOCKED(rt);
550 
551 	RTSTAT_INC(rts_dynamic);
552 
553 	/* Send notification of a route addition to userland. */
554 	bzero(&info, sizeof(info));
555 	info.rti_info[RTAX_DST] = dst;
556 	info.rti_info[RTAX_GATEWAY] = gateway;
557 	info.rti_info[RTAX_AUTHOR] = author;
558 	rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
559 
560 	return (0);
561 }
562 
563 /*
564  * Routing table ioctl interface.
565  */
566 int
567 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
568 {
569 
570 	/*
571 	 * If more ioctl commands are added here, make sure the proper
572 	 * super-user checks are being performed because it is possible for
573 	 * prison-root to make it this far if raw sockets have been enabled
574 	 * in jails.
575 	 */
576 #ifdef INET
577 	/* Multicast goop, grrr... */
578 	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
579 #else /* INET */
580 	return ENXIO;
581 #endif /* INET */
582 }
583 
584 struct ifaddr *
585 ifa_ifwithroute(int flags, const struct sockaddr *dst, struct sockaddr *gateway,
586 				u_int fibnum)
587 {
588 	struct ifaddr *ifa;
589 
590 	NET_EPOCH_ASSERT();
591 	if ((flags & RTF_GATEWAY) == 0) {
592 		/*
593 		 * If we are adding a route to an interface,
594 		 * and the interface is a pt to pt link
595 		 * we should search for the destination
596 		 * as our clue to the interface.  Otherwise
597 		 * we can use the local address.
598 		 */
599 		ifa = NULL;
600 		if (flags & RTF_HOST)
601 			ifa = ifa_ifwithdstaddr(dst, fibnum);
602 		if (ifa == NULL)
603 			ifa = ifa_ifwithaddr(gateway);
604 	} else {
605 		/*
606 		 * If we are adding a route to a remote net
607 		 * or host, the gateway may still be on the
608 		 * other end of a pt to pt link.
609 		 */
610 		ifa = ifa_ifwithdstaddr(gateway, fibnum);
611 	}
612 	if (ifa == NULL)
613 		ifa = ifa_ifwithnet(gateway, 0, fibnum);
614 	if (ifa == NULL) {
615 		struct nhop_object *nh;
616 
617 		nh = rib_lookup(fibnum, gateway, NHR_NONE, 0);
618 
619 		/*
620 		 * dismiss a gateway that is reachable only
621 		 * through the default router
622 		 */
623 		if ((nh == NULL) || (nh->nh_flags & NHF_DEFAULT))
624 			return (NULL);
625 		ifa = nh->nh_ifa;
626 	}
627 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
628 		struct ifaddr *oifa = ifa;
629 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
630 		if (ifa == NULL)
631 			ifa = oifa;
632 	}
633 
634 	return (ifa);
635 }
636 
637 /*
638  * Do appropriate manipulations of a routing tree given
639  * all the bits of info needed
640  */
641 int
642 rtrequest_fib(int req,
643 	struct sockaddr *dst,
644 	struct sockaddr *gateway,
645 	struct sockaddr *netmask,
646 	int flags,
647 	struct rtentry **ret_nrt,
648 	u_int fibnum)
649 {
650 	struct rt_addrinfo info;
651 
652 	if (dst->sa_len == 0)
653 		return(EINVAL);
654 
655 	bzero((caddr_t)&info, sizeof(info));
656 	info.rti_flags = flags;
657 	info.rti_info[RTAX_DST] = dst;
658 	info.rti_info[RTAX_GATEWAY] = gateway;
659 	info.rti_info[RTAX_NETMASK] = netmask;
660 	return rtrequest1_fib(req, &info, ret_nrt, fibnum);
661 }
662 
663 
664 /*
665  * Copy most of @rt data into @info.
666  *
667  * If @flags contains NHR_COPY, copies dst,netmask and gw to the
668  * pointers specified by @info structure. Assume such pointers
669  * are zeroed sockaddr-like structures with sa_len field initialized
670  * to reflect size of the provided buffer. if no NHR_COPY is specified,
671  * point dst,netmask and gw @info fields to appropriate @rt values.
672  *
673  * if @flags contains NHR_REF, do refcouting on rt_ifp and rt_ifa.
674  *
675  * Returns 0 on success.
676  */
677 int
678 rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info, int flags)
679 {
680 	struct rt_metrics *rmx;
681 	struct sockaddr *src, *dst;
682 	struct nhop_object *nh;
683 	int sa_len;
684 
685 	if (flags & NHR_COPY) {
686 		/* Copy destination if dst is non-zero */
687 		src = rt_key(rt);
688 		dst = info->rti_info[RTAX_DST];
689 		sa_len = src->sa_len;
690 		if (dst != NULL) {
691 			if (src->sa_len > dst->sa_len)
692 				return (ENOMEM);
693 			memcpy(dst, src, src->sa_len);
694 			info->rti_addrs |= RTA_DST;
695 		}
696 
697 		/* Copy mask if set && dst is non-zero */
698 		src = rt_mask(rt);
699 		dst = info->rti_info[RTAX_NETMASK];
700 		if (src != NULL && dst != NULL) {
701 
702 			/*
703 			 * Radix stores different value in sa_len,
704 			 * assume rt_mask() to have the same length
705 			 * as rt_key()
706 			 */
707 			if (sa_len > dst->sa_len)
708 				return (ENOMEM);
709 			memcpy(dst, src, src->sa_len);
710 			info->rti_addrs |= RTA_NETMASK;
711 		}
712 
713 		/* Copy gateway is set && dst is non-zero */
714 		src = &rt->rt_nhop->gw_sa;
715 		dst = info->rti_info[RTAX_GATEWAY];
716 		if ((rt->rt_flags & RTF_GATEWAY) && src != NULL && dst != NULL){
717 			if (src->sa_len > dst->sa_len)
718 				return (ENOMEM);
719 			memcpy(dst, src, src->sa_len);
720 			info->rti_addrs |= RTA_GATEWAY;
721 		}
722 	} else {
723 		info->rti_info[RTAX_DST] = rt_key(rt);
724 		info->rti_addrs |= RTA_DST;
725 		if (rt_mask(rt) != NULL) {
726 			info->rti_info[RTAX_NETMASK] = rt_mask(rt);
727 			info->rti_addrs |= RTA_NETMASK;
728 		}
729 		if (rt->rt_flags & RTF_GATEWAY) {
730 			info->rti_info[RTAX_GATEWAY] = &rt->rt_nhop->gw_sa;
731 			info->rti_addrs |= RTA_GATEWAY;
732 		}
733 	}
734 
735 	nh = rt->rt_nhop;
736 	rmx = info->rti_rmx;
737 	if (rmx != NULL) {
738 		info->rti_mflags |= RTV_MTU;
739 		rmx->rmx_mtu = nh->nh_mtu;
740 	}
741 
742 	info->rti_flags = rt->rt_flags | nhop_get_rtflags(nh);
743 	info->rti_ifp = nh->nh_ifp;
744 	info->rti_ifa = nh->nh_ifa;
745 	if (flags & NHR_REF) {
746 		if_ref(info->rti_ifp);
747 		ifa_ref(info->rti_ifa);
748 	}
749 
750 	return (0);
751 }
752 
753 /*
754  * Lookups up route entry for @dst in RIB database for fib @fibnum.
755  * Exports entry data to @info using rt_exportinfo().
756  *
757  * If @flags contains NHR_REF, refcouting is performed on rt_ifp and rt_ifa.
758  * All references can be released later by calling rib_free_info().
759  *
760  * Returns 0 on success.
761  * Returns ENOENT for lookup failure, ENOMEM for export failure.
762  */
763 int
764 rib_lookup_info(uint32_t fibnum, const struct sockaddr *dst, uint32_t flags,
765     uint32_t flowid, struct rt_addrinfo *info)
766 {
767 	RIB_RLOCK_TRACKER;
768 	struct rib_head *rh;
769 	struct radix_node *rn;
770 	struct rtentry *rt;
771 	int error;
772 
773 	KASSERT((fibnum < rt_numfibs), ("rib_lookup_rte: bad fibnum"));
774 	rh = rt_tables_get_rnh(fibnum, dst->sa_family);
775 	if (rh == NULL)
776 		return (ENOENT);
777 
778 	RIB_RLOCK(rh);
779 	rn = rh->rnh_matchaddr(__DECONST(void *, dst), &rh->head);
780 	if (rn != NULL && ((rn->rn_flags & RNF_ROOT) == 0)) {
781 		rt = RNTORT(rn);
782 		/* Ensure route & ifp is UP */
783 		if (RT_LINK_IS_UP(rt->rt_nhop->nh_ifp)) {
784 			flags = (flags & NHR_REF) | NHR_COPY;
785 			error = rt_exportinfo(rt, info, flags);
786 			RIB_RUNLOCK(rh);
787 
788 			return (error);
789 		}
790 	}
791 	RIB_RUNLOCK(rh);
792 
793 	return (ENOENT);
794 }
795 
796 /*
797  * Releases all references acquired by rib_lookup_info() when
798  * called with NHR_REF flags.
799  */
800 void
801 rib_free_info(struct rt_addrinfo *info)
802 {
803 
804 	ifa_free(info->rti_ifa);
805 	if_rele(info->rti_ifp);
806 }
807 
808 /*
809  * Iterates over all existing fibs in system calling
810  *  @setwa_f function prior to traversing each fib.
811  *  Calls @wa_f function for each element in current fib.
812  * If af is not AF_UNSPEC, iterates over fibs in particular
813  * address family.
814  */
815 void
816 rt_foreach_fib_walk(int af, rt_setwarg_t *setwa_f, rt_walktree_f_t *wa_f,
817     void *arg)
818 {
819 	struct rib_head *rnh;
820 	uint32_t fibnum;
821 	int i;
822 
823 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
824 		/* Do we want some specific family? */
825 		if (af != AF_UNSPEC) {
826 			rnh = rt_tables_get_rnh(fibnum, af);
827 			if (rnh == NULL)
828 				continue;
829 			if (setwa_f != NULL)
830 				setwa_f(rnh, fibnum, af, arg);
831 
832 			RIB_WLOCK(rnh);
833 			rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
834 			RIB_WUNLOCK(rnh);
835 			continue;
836 		}
837 
838 		for (i = 1; i <= AF_MAX; i++) {
839 			rnh = rt_tables_get_rnh(fibnum, i);
840 			if (rnh == NULL)
841 				continue;
842 			if (setwa_f != NULL)
843 				setwa_f(rnh, fibnum, i, arg);
844 
845 			RIB_WLOCK(rnh);
846 			rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
847 			RIB_WUNLOCK(rnh);
848 		}
849 	}
850 }
851 
852 struct rt_delinfo
853 {
854 	struct rt_addrinfo info;
855 	struct rib_head *rnh;
856 	struct rtentry *head;
857 };
858 
859 /*
860  * Conditionally unlinks @rn from radix tree based
861  * on info data passed in @arg.
862  */
863 static int
864 rt_checkdelroute(struct radix_node *rn, void *arg)
865 {
866 	struct rt_delinfo *di;
867 	struct rt_addrinfo *info;
868 	struct rtentry *rt;
869 	int error;
870 
871 	di = (struct rt_delinfo *)arg;
872 	rt = (struct rtentry *)rn;
873 	info = &di->info;
874 	error = 0;
875 
876 	info->rti_info[RTAX_DST] = rt_key(rt);
877 	info->rti_info[RTAX_NETMASK] = rt_mask(rt);
878 	info->rti_info[RTAX_GATEWAY] = &rt->rt_nhop->gw_sa;
879 
880 	rt = rt_unlinkrte(di->rnh, info, &error);
881 	if (rt == NULL) {
882 		/* Either not allowed or not matched. Skip entry */
883 		return (0);
884 	}
885 
886 	/* Entry was unlinked. Add to the list and return */
887 	rt->rt_chain = di->head;
888 	di->head = rt;
889 
890 	return (0);
891 }
892 
893 /*
894  * Iterates over a routing table specified by @fibnum and @family and
895  *  deletes elements marked by @filter_f.
896  * @fibnum: rtable id
897  * @family: AF_ address family
898  * @filter_f: function returning non-zero value for items to delete
899  * @arg: data to pass to the @filter_f function
900  * @report: true if rtsock notification is needed.
901  */
902 void
903 rib_walk_del(u_int fibnum, int family, rt_filter_f_t *filter_f, void *arg, bool report)
904 {
905 	struct rib_head *rnh;
906 	struct rt_delinfo di;
907 	struct rtentry *rt;
908 
909 	rnh = rt_tables_get_rnh(fibnum, family);
910 	if (rnh == NULL)
911 		return;
912 
913 	bzero(&di, sizeof(di));
914 	di.info.rti_filter = filter_f;
915 	di.info.rti_filterdata = arg;
916 	di.rnh = rnh;
917 
918 	RIB_WLOCK(rnh);
919 	rnh->rnh_walktree(&rnh->head, rt_checkdelroute, &di);
920 	RIB_WUNLOCK(rnh);
921 
922 	if (di.head == NULL)
923 		return;
924 
925 	/* We might have something to reclaim. */
926 	while (di.head != NULL) {
927 		rt = di.head;
928 		di.head = rt->rt_chain;
929 		rt->rt_chain = NULL;
930 
931 		/* TODO std rt -> rt_addrinfo export */
932 		di.info.rti_info[RTAX_DST] = rt_key(rt);
933 		di.info.rti_info[RTAX_NETMASK] = rt_mask(rt);
934 
935 		rt_notifydelete(rt, &di.info);
936 
937 		if (report)
938 			rt_routemsg(RTM_DELETE, rt, rt->rt_nhop->nh_ifp, 0,
939 			    fibnum);
940 		RTFREE_LOCKED(rt);
941 	}
942 }
943 
944 /*
945  * Iterates over all existing fibs in system and deletes each element
946  *  for which @filter_f function returns non-zero value.
947  * If @family is not AF_UNSPEC, iterates over fibs in particular
948  * address family.
949  */
950 void
951 rt_foreach_fib_walk_del(int family, rt_filter_f_t *filter_f, void *arg)
952 {
953 	u_int fibnum;
954 	int i, start, end;
955 
956 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
957 		/* Do we want some specific family? */
958 		if (family != AF_UNSPEC) {
959 			start = family;
960 			end = family;
961 		} else {
962 			start = 1;
963 			end = AF_MAX;
964 		}
965 
966 		for (i = start; i <= end; i++) {
967 			if (rt_tables_get_rnh(fibnum, i) == NULL)
968 				continue;
969 
970 			rib_walk_del(fibnum, i, filter_f, arg, 0);
971 		}
972 	}
973 }
974 
975 /*
976  * Delete Routes for a Network Interface
977  *
978  * Called for each routing entry via the rnh->rnh_walktree() call above
979  * to delete all route entries referencing a detaching network interface.
980  *
981  * Arguments:
982  *	rt	pointer to rtentry
983  *	nh	pointer to nhop
984  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
985  *
986  * Returns:
987  *	0	successful
988  *	errno	failed - reason indicated
989  */
990 static int
991 rt_ifdelroute(const struct rtentry *rt, const struct nhop_object *nh, void *arg)
992 {
993 	struct ifnet	*ifp = arg;
994 
995 	if (nh->nh_ifp != ifp)
996 		return (0);
997 
998 	/*
999 	 * Protect (sorta) against walktree recursion problems
1000 	 * with cloned routes
1001 	 */
1002 	if ((rt->rt_flags & RTF_UP) == 0)
1003 		return (0);
1004 
1005 	return (1);
1006 }
1007 
1008 /*
1009  * Delete all remaining routes using this interface
1010  * Unfortuneatly the only way to do this is to slog through
1011  * the entire routing table looking for routes which point
1012  * to this interface...oh well...
1013  */
1014 void
1015 rt_flushifroutes_af(struct ifnet *ifp, int af)
1016 {
1017 	KASSERT((af >= 1 && af <= AF_MAX), ("%s: af %d not >= 1 and <= %d",
1018 	    __func__, af, AF_MAX));
1019 
1020 	rt_foreach_fib_walk_del(af, rt_ifdelroute, ifp);
1021 }
1022 
1023 void
1024 rt_flushifroutes(struct ifnet *ifp)
1025 {
1026 
1027 	rt_foreach_fib_walk_del(AF_UNSPEC, rt_ifdelroute, ifp);
1028 }
1029 
1030 /*
1031  * Conditionally unlinks rtentry matching data inside @info from @rnh.
1032  * Returns unlinked, locked and referenced @rtentry on success,
1033  * Returns NULL and sets @perror to:
1034  * ESRCH - if prefix was not found,
1035  * EADDRINUSE - if trying to delete PINNED route without appropriate flag.
1036  * ENOENT - if supplied filter function returned 0 (not matched).
1037  */
1038 static struct rtentry *
1039 rt_unlinkrte(struct rib_head *rnh, struct rt_addrinfo *info, int *perror)
1040 {
1041 	struct sockaddr *dst, *netmask;
1042 	struct rtentry *rt;
1043 	struct radix_node *rn;
1044 
1045 	dst = info->rti_info[RTAX_DST];
1046 	netmask = info->rti_info[RTAX_NETMASK];
1047 
1048 	rt = (struct rtentry *)rnh->rnh_lookup(dst, netmask, &rnh->head);
1049 	if (rt == NULL) {
1050 		*perror = ESRCH;
1051 		return (NULL);
1052 	}
1053 
1054 	if ((info->rti_flags & RTF_PINNED) == 0) {
1055 		/* Check if target route can be deleted */
1056 		if (rt->rt_flags & RTF_PINNED) {
1057 			*perror = EADDRINUSE;
1058 			return (NULL);
1059 		}
1060 	}
1061 
1062 	if (info->rti_filter != NULL) {
1063 		if (info->rti_filter(rt, rt->rt_nhop, info->rti_filterdata)==0){
1064 			/* Not matched */
1065 			*perror = ENOENT;
1066 			return (NULL);
1067 		}
1068 
1069 		/*
1070 		 * Filter function requested rte deletion.
1071 		 * Ease the caller work by filling in remaining info
1072 		 * from that particular entry.
1073 		 */
1074 		info->rti_info[RTAX_GATEWAY] = &rt->rt_nhop->gw_sa;
1075 	}
1076 
1077 	/*
1078 	 * Remove the item from the tree and return it.
1079 	 * Complain if it is not there and do no more processing.
1080 	 */
1081 	*perror = ESRCH;
1082 #ifdef RADIX_MPATH
1083 	if (rt_mpath_capable(rnh))
1084 		rn = rt_mpath_unlink(rnh, info, rt, perror);
1085 	else
1086 #endif
1087 	rn = rnh->rnh_deladdr(dst, netmask, &rnh->head);
1088 	if (rn == NULL)
1089 		return (NULL);
1090 
1091 	if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1092 		panic ("rtrequest delete");
1093 
1094 	rt = RNTORT(rn);
1095 	RT_LOCK(rt);
1096 	RT_ADDREF(rt);
1097 	rt->rt_flags &= ~RTF_UP;
1098 
1099 	*perror = 0;
1100 
1101 	return (rt);
1102 }
1103 
1104 static void
1105 rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info)
1106 {
1107 	struct ifaddr *ifa;
1108 
1109 	/*
1110 	 * give the protocol a chance to keep things in sync.
1111 	 */
1112 	ifa = rt->rt_nhop->nh_ifa;
1113 	if (ifa != NULL && ifa->ifa_rtrequest != NULL)
1114 		ifa->ifa_rtrequest(RTM_DELETE, rt, rt->rt_nhop, info);
1115 
1116 	/*
1117 	 * One more rtentry floating around that is not
1118 	 * linked to the routing table. rttrash will be decremented
1119 	 * when RTFREE(rt) is eventually called.
1120 	 */
1121 	V_rttrash++;
1122 }
1123 
1124 
1125 /*
1126  * These (questionable) definitions of apparent local variables apply
1127  * to the next two functions.  XXXXXX!!!
1128  */
1129 #define	dst	info->rti_info[RTAX_DST]
1130 #define	gateway	info->rti_info[RTAX_GATEWAY]
1131 #define	netmask	info->rti_info[RTAX_NETMASK]
1132 #define	ifaaddr	info->rti_info[RTAX_IFA]
1133 #define	ifpaddr	info->rti_info[RTAX_IFP]
1134 #define	flags	info->rti_flags
1135 
1136 /*
1137  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
1138  * it will be referenced so the caller must free it.
1139  *
1140  * Assume basic consistency checks are executed by callers:
1141  * RTAX_DST exists, if RTF_GATEWAY is set, RTAX_GATEWAY exists as well.
1142  */
1143 int
1144 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
1145 {
1146 	struct epoch_tracker et;
1147 	int needref, error;
1148 
1149 	/*
1150 	 * ifp may be specified by sockaddr_dl
1151 	 * when protocol address is ambiguous.
1152 	 */
1153 	error = 0;
1154 	needref = (info->rti_ifa == NULL);
1155 	NET_EPOCH_ENTER(et);
1156 
1157 	/* If we have interface specified by the ifindex in the address, use it */
1158 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
1159 	    ifpaddr->sa_family == AF_LINK) {
1160 	    const struct sockaddr_dl *sdl = (const struct sockaddr_dl *)ifpaddr;
1161 	    if (sdl->sdl_index != 0)
1162 		    info->rti_ifp = ifnet_byindex(sdl->sdl_index);
1163 	}
1164 	/*
1165 	 * If we have source address specified, try to find it
1166 	 * TODO: avoid enumerating all ifas on all interfaces.
1167 	 */
1168 	if (info->rti_ifa == NULL && ifaaddr != NULL)
1169 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
1170 	if (info->rti_ifa == NULL) {
1171 		struct sockaddr *sa;
1172 
1173 		/*
1174 		 * Most common use case for the userland-supplied routes.
1175 		 *
1176 		 * Choose sockaddr to select ifa.
1177 		 * -- if ifp is set --
1178 		 * Order of preference:
1179 		 * 1) IFA address
1180 		 * 2) gateway address
1181 		 *   Note: for interface routes link-level gateway address
1182 		 *     is specified to indicate the interface index without
1183 		 *     specifying RTF_GATEWAY. In this case, ignore gateway
1184 		 *   Note: gateway AF may be different from dst AF. In this case,
1185 		 *   ignore gateway
1186 		 * 3) final destination.
1187 		 * 4) if all of these fails, try to get at least link-level ifa.
1188 		 * -- else --
1189 		 * try to lookup gateway or dst in the routing table to get ifa
1190 		 */
1191 		if (info->rti_info[RTAX_IFA] != NULL)
1192 			sa = info->rti_info[RTAX_IFA];
1193 		else if ((info->rti_flags & RTF_GATEWAY) != 0 &&
1194 		    gateway->sa_family == dst->sa_family)
1195 			sa = gateway;
1196 		else
1197 			sa = dst;
1198 		if (info->rti_ifp != NULL) {
1199 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
1200 			/* Case 4 */
1201 			if (info->rti_ifa == NULL && gateway != NULL)
1202 				info->rti_ifa = ifaof_ifpforaddr(gateway, info->rti_ifp);
1203 		} else if (dst != NULL && gateway != NULL)
1204 			info->rti_ifa = ifa_ifwithroute(flags, dst, gateway,
1205 							fibnum);
1206 		else if (sa != NULL)
1207 			info->rti_ifa = ifa_ifwithroute(flags, sa, sa,
1208 							fibnum);
1209 	}
1210 	if (needref && info->rti_ifa != NULL) {
1211 		if (info->rti_ifp == NULL)
1212 			info->rti_ifp = info->rti_ifa->ifa_ifp;
1213 		ifa_ref(info->rti_ifa);
1214 	} else
1215 		error = ENETUNREACH;
1216 	NET_EPOCH_EXIT(et);
1217 	return (error);
1218 }
1219 
1220 void
1221 rt_updatemtu(struct ifnet *ifp)
1222 {
1223 	struct rib_head *rnh;
1224 	int mtu;
1225 	int i, j;
1226 
1227 	/*
1228 	 * Try to update rt_mtu for all routes using this interface
1229 	 * Unfortunately the only way to do this is to traverse all
1230 	 * routing tables in all fibs/domains.
1231 	 */
1232 	for (i = 1; i <= AF_MAX; i++) {
1233 		mtu = if_getmtu_family(ifp, i);
1234 		for (j = 0; j < rt_numfibs; j++) {
1235 			rnh = rt_tables_get_rnh(j, i);
1236 			if (rnh == NULL)
1237 				continue;
1238 			nhops_update_ifmtu(rnh, ifp, mtu);
1239 		}
1240 	}
1241 }
1242 
1243 
1244 #if 0
1245 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
1246 int rt_print(char *buf, int buflen, struct rtentry *rt);
1247 
1248 int
1249 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
1250 {
1251 	void *paddr = NULL;
1252 
1253 	switch (s->sa_family) {
1254 	case AF_INET:
1255 		paddr = &((struct sockaddr_in *)s)->sin_addr;
1256 		break;
1257 	case AF_INET6:
1258 		paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
1259 		break;
1260 	}
1261 
1262 	if (paddr == NULL)
1263 		return (0);
1264 
1265 	if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
1266 		return (0);
1267 
1268 	return (strlen(buf));
1269 }
1270 
1271 int
1272 rt_print(char *buf, int buflen, struct rtentry *rt)
1273 {
1274 	struct sockaddr *addr, *mask;
1275 	int i = 0;
1276 
1277 	addr = rt_key(rt);
1278 	mask = rt_mask(rt);
1279 
1280 	i = p_sockaddr(buf, buflen, addr);
1281 	if (!(rt->rt_flags & RTF_HOST)) {
1282 		buf[i++] = '/';
1283 		i += p_sockaddr(buf + i, buflen - i, mask);
1284 	}
1285 
1286 	if (rt->rt_flags & RTF_GATEWAY) {
1287 		buf[i++] = '>';
1288 		i += p_sockaddr(buf + i, buflen - i, &rt->rt_nhop->gw_sa);
1289 	}
1290 
1291 	return (i);
1292 }
1293 #endif
1294 
1295 #ifdef RADIX_MPATH
1296 /*
1297  * Deletes key for single-path routes, unlinks rtentry with
1298  * gateway specified in @info from multi-path routes.
1299  *
1300  * Returnes unlinked entry. In case of failure, returns NULL
1301  * and sets @perror to ESRCH.
1302  */
1303 static struct radix_node *
1304 rt_mpath_unlink(struct rib_head *rnh, struct rt_addrinfo *info,
1305     struct rtentry *rto, int *perror)
1306 {
1307 	/*
1308 	 * if we got multipath routes, we require users to specify
1309 	 * a matching RTAX_GATEWAY.
1310 	 */
1311 	struct rtentry *rt; // *rto = NULL;
1312 	struct radix_node *rn;
1313 	struct sockaddr *gw;
1314 
1315 	gw = info->rti_info[RTAX_GATEWAY];
1316 	rt = rt_mpath_matchgate(rto, gw);
1317 	if (rt == NULL) {
1318 		*perror = ESRCH;
1319 		return (NULL);
1320 	}
1321 
1322 	/*
1323 	 * this is the first entry in the chain
1324 	 */
1325 	if (rto == rt) {
1326 		rn = rn_mpath_next((struct radix_node *)rt);
1327 		/*
1328 		 * there is another entry, now it's active
1329 		 */
1330 		if (rn) {
1331 			rto = RNTORT(rn);
1332 			RT_LOCK(rto);
1333 			rto->rt_flags |= RTF_UP;
1334 			RT_UNLOCK(rto);
1335 		} else if (rt->rt_flags & RTF_GATEWAY) {
1336 			/*
1337 			 * For gateway routes, we need to
1338 			 * make sure that we we are deleting
1339 			 * the correct gateway.
1340 			 * rt_mpath_matchgate() does not
1341 			 * check the case when there is only
1342 			 * one route in the chain.
1343 			 */
1344 			if (gw &&
1345 			    (rt->rt_nhop->gw_sa.sa_len != gw->sa_len ||
1346 				memcmp(&rt->rt_nhop->gw_sa, gw, gw->sa_len))) {
1347 				*perror = ESRCH;
1348 				return (NULL);
1349 			}
1350 		}
1351 
1352 		/*
1353 		 * use the normal delete code to remove
1354 		 * the first entry
1355 		 */
1356 		rn = rnh->rnh_deladdr(dst, netmask, &rnh->head);
1357 		*perror = 0;
1358 		return (rn);
1359 	}
1360 
1361 	/*
1362 	 * if the entry is 2nd and on up
1363 	 */
1364 	if (rt_mpath_deldup(rto, rt) == 0)
1365 		panic ("rtrequest1: rt_mpath_deldup");
1366 	*perror = 0;
1367 	rn = (struct radix_node *)rt;
1368 	return (rn);
1369 }
1370 #endif
1371 
1372 #undef dst
1373 #undef gateway
1374 #undef netmask
1375 #undef ifaaddr
1376 #undef ifpaddr
1377 #undef flags
1378 
1379 int
1380 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1381 				u_int fibnum)
1382 {
1383 	const struct sockaddr *dst;
1384 	struct rib_head *rnh;
1385 	int error;
1386 
1387 	KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1388 	KASSERT((info->rti_flags & RTF_RNH_LOCKED) == 0, ("rtrequest1_fib: locked"));
1389 
1390 	dst = info->rti_info[RTAX_DST];
1391 
1392 	switch (dst->sa_family) {
1393 	case AF_INET6:
1394 	case AF_INET:
1395 		/* We support multiple FIBs. */
1396 		break;
1397 	default:
1398 		fibnum = RT_DEFAULT_FIB;
1399 		break;
1400 	}
1401 
1402 	/*
1403 	 * Find the correct routing tree to use for this Address Family
1404 	 */
1405 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1406 	if (rnh == NULL)
1407 		return (EAFNOSUPPORT);
1408 
1409 	/*
1410 	 * If we are adding a host route then we don't want to put
1411 	 * a netmask in the tree, nor do we want to clone it.
1412 	 */
1413 	if (info->rti_flags & RTF_HOST)
1414 		info->rti_info[RTAX_NETMASK] = NULL;
1415 
1416 	error = 0;
1417 	switch (req) {
1418 	case RTM_DELETE:
1419 		error = del_route(rnh, info, ret_nrt);
1420 		break;
1421 	case RTM_RESOLVE:
1422 		/*
1423 		 * resolve was only used for route cloning
1424 		 * here for compat
1425 		 */
1426 		break;
1427 	case RTM_ADD:
1428 		error = add_route(rnh, info, ret_nrt);
1429 		break;
1430 	case RTM_CHANGE:
1431 		error = change_route(rnh, info, ret_nrt);
1432 		break;
1433 	default:
1434 		error = EOPNOTSUPP;
1435 	}
1436 
1437 	return (error);
1438 }
1439 
1440 static int
1441 add_route(struct rib_head *rnh, struct rt_addrinfo *info,
1442     struct rtentry **ret_nrt)
1443 {
1444 	struct sockaddr *dst, *ndst, *gateway, *netmask;
1445 	struct rtentry *rt, *rt_old;
1446 	struct nhop_object *nh;
1447 	struct radix_node *rn;
1448 	struct ifaddr *ifa;
1449 	int error, flags;
1450 	struct epoch_tracker et;
1451 
1452 	dst = info->rti_info[RTAX_DST];
1453 	gateway = info->rti_info[RTAX_GATEWAY];
1454 	netmask = info->rti_info[RTAX_NETMASK];
1455 	flags = info->rti_flags;
1456 
1457 	if ((flags & RTF_GATEWAY) && !gateway)
1458 		return (EINVAL);
1459 	if (dst && gateway && (dst->sa_family != gateway->sa_family) &&
1460 	    (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1461 		return (EINVAL);
1462 
1463 	if (dst->sa_len > sizeof(((struct rtentry *)NULL)->rt_dstb))
1464 		return (EINVAL);
1465 
1466 	if (info->rti_ifa == NULL) {
1467 		error = rt_getifa_fib(info, rnh->rib_fibnum);
1468 		if (error)
1469 			return (error);
1470 	} else {
1471 		ifa_ref(info->rti_ifa);
1472 	}
1473 
1474 	NET_EPOCH_ENTER(et);
1475 	error = nhop_create_from_info(rnh, info, &nh);
1476 	NET_EPOCH_EXIT(et);
1477 	if (error != 0) {
1478 		ifa_free(info->rti_ifa);
1479 		return (error);
1480 	}
1481 
1482 	rt = uma_zalloc(V_rtzone, M_NOWAIT);
1483 	if (rt == NULL) {
1484 		ifa_free(info->rti_ifa);
1485 		nhop_free(nh);
1486 		return (ENOBUFS);
1487 	}
1488 	rt->rt_flags = RTF_UP | flags;
1489 	rt->rt_nhop = nh;
1490 
1491 	/* Fill in dst */
1492 	memcpy(&rt->rt_dst, dst, dst->sa_len);
1493 	rt_key(rt) = &rt->rt_dst;
1494 
1495 	/*
1496 	 * point to the (possibly newly malloc'd) dest address.
1497 	 */
1498 	ndst = (struct sockaddr *)rt_key(rt);
1499 
1500 	/*
1501 	 * make sure it contains the value we want (masked if needed).
1502 	 */
1503 	if (netmask) {
1504 		rt_maskedcopy(dst, ndst, netmask);
1505 	} else
1506 		bcopy(dst, ndst, dst->sa_len);
1507 
1508 	/*
1509 	 * We use the ifa reference returned by rt_getifa_fib().
1510 	 * This moved from below so that rnh->rnh_addaddr() can
1511 	 * examine the ifa and  ifa->ifa_ifp if it so desires.
1512 	 */
1513 	ifa = info->rti_ifa;
1514 	rt->rt_weight = 1;
1515 
1516 	rt_setmetrics(info, rt);
1517 
1518 	RIB_WLOCK(rnh);
1519 	RT_LOCK(rt);
1520 #ifdef RADIX_MPATH
1521 	/* do not permit exactly the same dst/mask/gw pair */
1522 	if (rt_mpath_capable(rnh) &&
1523 		rt_mpath_conflict(rnh, rt, netmask)) {
1524 		RIB_WUNLOCK(rnh);
1525 
1526 		nhop_free(nh);
1527 		uma_zfree(V_rtzone, rt);
1528 		return (EEXIST);
1529 	}
1530 #endif
1531 
1532 	rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head, rt->rt_nodes);
1533 
1534 	if (rn != NULL && rt->rt_expire > 0)
1535 		tmproutes_update(rnh, rt);
1536 
1537 	rt_old = NULL;
1538 	if (rn == NULL && (info->rti_flags & RTF_PINNED) != 0) {
1539 
1540 		/*
1541 		 * Force removal and re-try addition
1542 		 * TODO: better multipath&pinned support
1543 		 */
1544 		struct sockaddr *info_dst = info->rti_info[RTAX_DST];
1545 		info->rti_info[RTAX_DST] = ndst;
1546 		/* Do not delete existing PINNED(interface) routes */
1547 		info->rti_flags &= ~RTF_PINNED;
1548 		rt_old = rt_unlinkrte(rnh, info, &error);
1549 		info->rti_flags |= RTF_PINNED;
1550 		info->rti_info[RTAX_DST] = info_dst;
1551 		if (rt_old != NULL)
1552 			rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head,
1553 			    rt->rt_nodes);
1554 	}
1555 	RIB_WUNLOCK(rnh);
1556 
1557 	if (rt_old != NULL)
1558 		RT_UNLOCK(rt_old);
1559 
1560 	/*
1561 	 * If it still failed to go into the tree,
1562 	 * then un-make it (this should be a function)
1563 	 */
1564 	if (rn == NULL) {
1565 		nhop_free(nh);
1566 		uma_zfree(V_rtzone, rt);
1567 		return (EEXIST);
1568 	}
1569 
1570 	if (rt_old != NULL) {
1571 		rt_notifydelete(rt_old, info);
1572 		RTFREE(rt_old);
1573 	}
1574 
1575 	/*
1576 	 * If this protocol has something to add to this then
1577 	 * allow it to do that as well.
1578 	 */
1579 	if (ifa->ifa_rtrequest)
1580 		ifa->ifa_rtrequest(RTM_ADD, rt, rt->rt_nhop, info);
1581 
1582 	/*
1583 	 * actually return a resultant rtentry and
1584 	 * give the caller a single reference.
1585 	 */
1586 	if (ret_nrt) {
1587 		*ret_nrt = rt;
1588 		RT_ADDREF(rt);
1589 	}
1590 	rnh->rnh_gen++;		/* Routing table updated */
1591 	RT_UNLOCK(rt);
1592 
1593 	return (0);
1594 }
1595 
1596 static int
1597 del_route(struct rib_head *rnh, struct rt_addrinfo *info,
1598     struct rtentry **ret_nrt)
1599 {
1600 	struct sockaddr *dst, *netmask;
1601 	struct sockaddr_storage mdst;
1602 	struct rtentry *rt;
1603 	int error;
1604 
1605 	dst = info->rti_info[RTAX_DST];
1606 	netmask = info->rti_info[RTAX_NETMASK];
1607 
1608 	if (netmask) {
1609 		if (dst->sa_len > sizeof(mdst))
1610 			return (EINVAL);
1611 		rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1612 		dst = (struct sockaddr *)&mdst;
1613 	}
1614 
1615 	RIB_WLOCK(rnh);
1616 	rt = rt_unlinkrte(rnh, info, &error);
1617 	RIB_WUNLOCK(rnh);
1618 	if (error != 0)
1619 		return (error);
1620 
1621 	rt_notifydelete(rt, info);
1622 
1623 	/*
1624 	 * If the caller wants it, then it can have it,
1625 	 * but it's up to it to free the rtentry as we won't be
1626 	 * doing it.
1627 	 */
1628 	if (ret_nrt) {
1629 		*ret_nrt = rt;
1630 		RT_UNLOCK(rt);
1631 	} else
1632 		RTFREE_LOCKED(rt);
1633 
1634 	return (0);
1635 }
1636 
1637 static int
1638 change_route_one(struct rib_head *rnh, struct rt_addrinfo *info,
1639     struct rtentry **ret_nrt)
1640 {
1641 	RIB_RLOCK_TRACKER;
1642 	struct rtentry *rt = NULL;
1643 	int error = 0;
1644 	int free_ifa = 0;
1645 	struct nhop_object *nh, *nh_orig;
1646 
1647 	RIB_RLOCK(rnh);
1648 	rt = (struct rtentry *)rnh->rnh_lookup(info->rti_info[RTAX_DST],
1649 	    info->rti_info[RTAX_NETMASK], &rnh->head);
1650 
1651 	if (rt == NULL) {
1652 		RIB_RUNLOCK(rnh);
1653 		return (ESRCH);
1654 	}
1655 
1656 #ifdef RADIX_MPATH
1657 	/*
1658 	 * If we got multipath routes,
1659 	 * we require users to specify a matching RTAX_GATEWAY.
1660 	 */
1661 	if (rt_mpath_capable(rnh)) {
1662 		rt = rt_mpath_matchgate(rt, info->rti_info[RTAX_GATEWAY]);
1663 		if (rt == NULL) {
1664 			RIB_RUNLOCK(rnh);
1665 			return (ESRCH);
1666 		}
1667 	}
1668 #endif
1669 	nh_orig = rt->rt_nhop;
1670 
1671 	RIB_RUNLOCK(rnh);
1672 
1673 	rt = NULL;
1674 	nh = NULL;
1675 
1676 	/*
1677 	 * New gateway could require new ifaddr, ifp;
1678 	 * flags may also be different; ifp may be specified
1679 	 * by ll sockaddr when protocol address is ambiguous
1680 	 */
1681 	if (((nh_orig->nh_flags & NHF_GATEWAY) &&
1682 	    info->rti_info[RTAX_GATEWAY] != NULL) ||
1683 	    info->rti_info[RTAX_IFP] != NULL ||
1684 	    (info->rti_info[RTAX_IFA] != NULL &&
1685 	     !sa_equal(info->rti_info[RTAX_IFA], nh_orig->nh_ifa->ifa_addr))) {
1686 		error = rt_getifa_fib(info, rnh->rib_fibnum);
1687 		if (info->rti_ifa != NULL)
1688 			free_ifa = 1;
1689 
1690 		if (error != 0) {
1691 			if (free_ifa) {
1692 				ifa_free(info->rti_ifa);
1693 				info->rti_ifa = NULL;
1694 			}
1695 
1696 			return (error);
1697 		}
1698 	}
1699 
1700 	error = nhop_create_from_nhop(rnh, nh_orig, info, &nh);
1701 	if (free_ifa) {
1702 		ifa_free(info->rti_ifa);
1703 		info->rti_ifa = NULL;
1704 	}
1705 	if (error != 0)
1706 		return (error);
1707 
1708 	RIB_WLOCK(rnh);
1709 
1710 	/* Lookup rtentry once again and check if nexthop is still the same */
1711 	rt = (struct rtentry *)rnh->rnh_lookup(info->rti_info[RTAX_DST],
1712 	    info->rti_info[RTAX_NETMASK], &rnh->head);
1713 
1714 	if (rt == NULL) {
1715 		RIB_WUNLOCK(rnh);
1716 		nhop_free(nh);
1717 		return (ESRCH);
1718 	}
1719 
1720 	if (rt->rt_nhop != nh_orig) {
1721 		RIB_WUNLOCK(rnh);
1722 		nhop_free(nh);
1723 		return (EAGAIN);
1724 	}
1725 
1726 	/* Proceed with the update */
1727 	RT_LOCK(rt);
1728 
1729 	/* Provide notification to the protocols.*/
1730 	if ((nh_orig->nh_ifa != nh->nh_ifa) && nh_orig->nh_ifa->ifa_rtrequest)
1731 		nh_orig->nh_ifa->ifa_rtrequest(RTM_DELETE, rt, nh_orig, info);
1732 
1733 	rt->rt_nhop = nh;
1734 	rt_setmetrics(info, rt);
1735 
1736 	if ((nh_orig->nh_ifa != nh->nh_ifa) && nh_orig->nh_ifa->ifa_rtrequest)
1737 		nh_orig->nh_ifa->ifa_rtrequest(RTM_DELETE, rt, nh_orig, info);
1738 
1739 	if (ret_nrt != NULL) {
1740 		*ret_nrt = rt;
1741 		RT_ADDREF(rt);
1742 	}
1743 
1744 	RT_UNLOCK(rt);
1745 
1746 	/* Update generation id to reflect rtable change */
1747 	rnh->rnh_gen++;
1748 
1749 	RIB_WUNLOCK(rnh);
1750 
1751 	nhop_free(nh_orig);
1752 
1753 	return (0);
1754 }
1755 
1756 static int
1757 change_route(struct rib_head *rnh, struct rt_addrinfo *info,
1758     struct rtentry **ret_nrt)
1759 {
1760 	struct epoch_tracker et;
1761 	int error;
1762 
1763 	/* Check if updated gateway exists */
1764 	if ((info->rti_flags & RTF_GATEWAY) &&
1765 	    (info->rti_info[RTAX_GATEWAY] == NULL))
1766 		return (EINVAL);
1767 
1768 	NET_EPOCH_ENTER(et);
1769 
1770 	/*
1771 	 * route change is done in multiple steps, with dropping and
1772 	 * reacquiring lock. In the situations with multiple processes
1773 	 * changes the same route in can lead to the case when route
1774 	 * is changed between the steps. Address it by retrying the operation
1775 	 * multiple times before failing.
1776 	 */
1777 	for (int i = 0; i < RIB_MAX_RETRIES; i++) {
1778 		error = change_route_one(rnh, info, ret_nrt);
1779 		if (error != EAGAIN)
1780 			break;
1781 	}
1782 	NET_EPOCH_EXIT(et);
1783 
1784 	return (error);
1785 }
1786 
1787 
1788 static void
1789 rt_setmetrics(const struct rt_addrinfo *info, struct rtentry *rt)
1790 {
1791 
1792 	if (info->rti_mflags & RTV_WEIGHT)
1793 		rt->rt_weight = info->rti_rmx->rmx_weight;
1794 	/* Kernel -> userland timebase conversion. */
1795 	if (info->rti_mflags & RTV_EXPIRE)
1796 		rt->rt_expire = info->rti_rmx->rmx_expire ?
1797 		    info->rti_rmx->rmx_expire - time_second + time_uptime : 0;
1798 }
1799 
1800 void
1801 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1802 {
1803 	u_char *cp1 = (u_char *)src;
1804 	u_char *cp2 = (u_char *)dst;
1805 	u_char *cp3 = (u_char *)netmask;
1806 	u_char *cplim = cp2 + *cp3;
1807 	u_char *cplim2 = cp2 + *cp1;
1808 
1809 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1810 	cp3 += 2;
1811 	if (cplim > cplim2)
1812 		cplim = cplim2;
1813 	while (cp2 < cplim)
1814 		*cp2++ = *cp1++ & *cp3++;
1815 	if (cp2 < cplim2)
1816 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1817 }
1818 
1819 /*
1820  * Set up a routing table entry, normally
1821  * for an interface.
1822  */
1823 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1824 static inline  int
1825 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1826 {
1827 	RIB_RLOCK_TRACKER;
1828 	struct sockaddr *dst;
1829 	struct sockaddr *netmask;
1830 	struct rtentry *rt = NULL;
1831 	struct rt_addrinfo info;
1832 	int error = 0;
1833 	int startfib, endfib;
1834 	char tempbuf[_SOCKADDR_TMPSIZE];
1835 	int didwork = 0;
1836 	int a_failure = 0;
1837 	struct sockaddr_dl_short *sdl = NULL;
1838 	struct rib_head *rnh;
1839 
1840 	if (flags & RTF_HOST) {
1841 		dst = ifa->ifa_dstaddr;
1842 		netmask = NULL;
1843 	} else {
1844 		dst = ifa->ifa_addr;
1845 		netmask = ifa->ifa_netmask;
1846 	}
1847 	if (dst->sa_len == 0)
1848 		return(EINVAL);
1849 	switch (dst->sa_family) {
1850 	case AF_INET6:
1851 	case AF_INET:
1852 		/* We support multiple FIBs. */
1853 		break;
1854 	default:
1855 		fibnum = RT_DEFAULT_FIB;
1856 		break;
1857 	}
1858 	if (fibnum == RT_ALL_FIBS) {
1859 		if (V_rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD)
1860 			startfib = endfib = ifa->ifa_ifp->if_fib;
1861 		else {
1862 			startfib = 0;
1863 			endfib = rt_numfibs - 1;
1864 		}
1865 	} else {
1866 		KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1867 		startfib = fibnum;
1868 		endfib = fibnum;
1869 	}
1870 
1871 	/*
1872 	 * If it's a delete, check that if it exists,
1873 	 * it's on the correct interface or we might scrub
1874 	 * a route to another ifa which would
1875 	 * be confusing at best and possibly worse.
1876 	 */
1877 	if (cmd == RTM_DELETE) {
1878 		/*
1879 		 * It's a delete, so it should already exist..
1880 		 * If it's a net, mask off the host bits
1881 		 * (Assuming we have a mask)
1882 		 * XXX this is kinda inet specific..
1883 		 */
1884 		if (netmask != NULL) {
1885 			rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
1886 			dst = (struct sockaddr *)tempbuf;
1887 		}
1888 	} else if (cmd == RTM_ADD) {
1889 		sdl = (struct sockaddr_dl_short *)tempbuf;
1890 		bzero(sdl, sizeof(struct sockaddr_dl_short));
1891 		sdl->sdl_family = AF_LINK;
1892 		sdl->sdl_len = sizeof(struct sockaddr_dl_short);
1893 		sdl->sdl_type = ifa->ifa_ifp->if_type;
1894 		sdl->sdl_index = ifa->ifa_ifp->if_index;
1895         }
1896 	/*
1897 	 * Now go through all the requested tables (fibs) and do the
1898 	 * requested action. Realistically, this will either be fib 0
1899 	 * for protocols that don't do multiple tables or all the
1900 	 * tables for those that do.
1901 	 */
1902 	for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
1903 		if (cmd == RTM_DELETE) {
1904 			struct radix_node *rn;
1905 			/*
1906 			 * Look up an rtentry that is in the routing tree and
1907 			 * contains the correct info.
1908 			 */
1909 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1910 			if (rnh == NULL)
1911 				/* this table doesn't exist but others might */
1912 				continue;
1913 			RIB_RLOCK(rnh);
1914 			rn = rnh->rnh_lookup(dst, netmask, &rnh->head);
1915 #ifdef RADIX_MPATH
1916 			if (rt_mpath_capable(rnh)) {
1917 
1918 				if (rn == NULL)
1919 					error = ESRCH;
1920 				else {
1921 					rt = RNTORT(rn);
1922 					/*
1923 					 * for interface route the gateway
1924 					 * gateway is sockaddr_dl, so
1925 					 * rt_mpath_matchgate must use the
1926 					 * interface address
1927 					 */
1928 					rt = rt_mpath_matchgate(rt,
1929 					    ifa->ifa_addr);
1930 					if (rt == NULL)
1931 						error = ESRCH;
1932 				}
1933 			}
1934 #endif
1935 			error = (rn == NULL ||
1936 			    (rn->rn_flags & RNF_ROOT) ||
1937 			    RNTORT(rn)->rt_nhop->nh_ifa != ifa);
1938 			RIB_RUNLOCK(rnh);
1939 			if (error) {
1940 				/* this is only an error if bad on ALL tables */
1941 				continue;
1942 			}
1943 		}
1944 		/*
1945 		 * Do the actual request
1946 		 */
1947 		bzero((caddr_t)&info, sizeof(info));
1948 		info.rti_ifa = ifa;
1949 		info.rti_flags = flags |
1950 		    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1951 		info.rti_info[RTAX_DST] = dst;
1952 		/*
1953 		 * doing this for compatibility reasons
1954 		 */
1955 		if (cmd == RTM_ADD)
1956 			info.rti_info[RTAX_GATEWAY] = (struct sockaddr *)sdl;
1957 		else
1958 			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1959 		info.rti_info[RTAX_NETMASK] = netmask;
1960 		error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1961 		if (error == 0 && rt != NULL) {
1962 			/*
1963 			 * notify any listening routing agents of the change
1964 			 */
1965 			RT_LOCK(rt);
1966 
1967 			/* TODO: interface routes/aliases */
1968 			RT_ADDREF(rt);
1969 			RT_UNLOCK(rt);
1970 			rt_newaddrmsg_fib(cmd, ifa, rt, fibnum);
1971 			RT_LOCK(rt);
1972 			RT_REMREF(rt);
1973 			if (cmd == RTM_DELETE) {
1974 				/*
1975 				 * If we are deleting, and we found an entry,
1976 				 * then it's been removed from the tree..
1977 				 * now throw it away.
1978 				 */
1979 				RTFREE_LOCKED(rt);
1980 			} else {
1981 				if (cmd == RTM_ADD) {
1982 					/*
1983 					 * We just wanted to add it..
1984 					 * we don't actually need a reference.
1985 					 */
1986 					RT_REMREF(rt);
1987 				}
1988 				RT_UNLOCK(rt);
1989 			}
1990 			didwork = 1;
1991 		}
1992 		if (error)
1993 			a_failure = error;
1994 	}
1995 	if (cmd == RTM_DELETE) {
1996 		if (didwork) {
1997 			error = 0;
1998 		} else {
1999 			/* we only give an error if it wasn't in any table */
2000 			error = ((flags & RTF_HOST) ?
2001 			    EHOSTUNREACH : ENETUNREACH);
2002 		}
2003 	} else {
2004 		if (a_failure) {
2005 			/* return an error if any of them failed */
2006 			error = a_failure;
2007 		}
2008 	}
2009 	return (error);
2010 }
2011 
2012 /*
2013  * Set up a routing table entry, normally
2014  * for an interface.
2015  */
2016 int
2017 rtinit(struct ifaddr *ifa, int cmd, int flags)
2018 {
2019 	struct sockaddr *dst;
2020 	int fib = RT_DEFAULT_FIB;
2021 
2022 	if (flags & RTF_HOST) {
2023 		dst = ifa->ifa_dstaddr;
2024 	} else {
2025 		dst = ifa->ifa_addr;
2026 	}
2027 
2028 	switch (dst->sa_family) {
2029 	case AF_INET6:
2030 	case AF_INET:
2031 		/* We do support multiple FIBs. */
2032 		fib = RT_ALL_FIBS;
2033 		break;
2034 	}
2035 	return (rtinit1(ifa, cmd, flags, fib));
2036 }
2037 
2038 /*
2039  * Announce interface address arrival/withdraw
2040  * Returns 0 on success.
2041  */
2042 int
2043 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
2044 {
2045 
2046 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2047 	    ("unexpected cmd %d", cmd));
2048 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2049 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2050 
2051 	EVENTHANDLER_DIRECT_INVOKE(rt_addrmsg, ifa, cmd);
2052 	return (rtsock_addrmsg(cmd, ifa, fibnum));
2053 }
2054 
2055 /*
2056  * Announce kernel-originated route addition/removal to rtsock based on @rt data.
2057  * cmd: RTM_ cmd
2058  * @rt: valid rtentry
2059  * @ifp: target route interface
2060  * @fibnum: fib id or RT_ALL_FIBS
2061  *
2062  * Returns 0 on success.
2063  */
2064 int
2065 rt_routemsg(int cmd, struct rtentry *rt, struct ifnet *ifp, int rti_addrs,
2066     int fibnum)
2067 {
2068 
2069 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2070 	    ("unexpected cmd %d", cmd));
2071 
2072 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2073 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2074 
2075 	KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
2076 
2077 	return (rtsock_routemsg(cmd, rt, ifp, 0, fibnum));
2078 }
2079 
2080 /*
2081  * Announce kernel-originated route addition/removal to rtsock based on @rt data.
2082  * cmd: RTM_ cmd
2083  * @info: addrinfo structure with valid data.
2084  * @fibnum: fib id or RT_ALL_FIBS
2085  *
2086  * Returns 0 on success.
2087  */
2088 int
2089 rt_routemsg_info(int cmd, struct rt_addrinfo *info, int fibnum)
2090 {
2091 
2092 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE || cmd == RTM_CHANGE,
2093 	    ("unexpected cmd %d", cmd));
2094 
2095 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2096 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2097 
2098 	KASSERT(info->rti_info[RTAX_DST] != NULL, (":%s: RTAX_DST must be supplied", __func__));
2099 
2100 	return (rtsock_routemsg_info(cmd, info, fibnum));
2101 }
2102 
2103 
2104 /*
2105  * This is called to generate messages from the routing socket
2106  * indicating a network interface has had addresses associated with it.
2107  */
2108 void
2109 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, struct rtentry *rt, int fibnum)
2110 {
2111 
2112 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2113 		("unexpected cmd %u", cmd));
2114 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2115 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2116 
2117 	if (cmd == RTM_ADD) {
2118 		rt_addrmsg(cmd, ifa, fibnum);
2119 		if (rt != NULL)
2120 			rt_routemsg(cmd, rt, ifa->ifa_ifp, 0, fibnum);
2121 	} else {
2122 		if (rt != NULL)
2123 			rt_routemsg(cmd, rt, ifa->ifa_ifp, 0, fibnum);
2124 		rt_addrmsg(cmd, ifa, fibnum);
2125 	}
2126 }
2127 
2128