xref: /freebsd/sys/net/route.c (revision a0ee8cc636cd5c2374ec44ca71226564ea0bca95)
1 /*-
2  * Copyright (c) 1980, 1986, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)route.c	8.3.1.1 (Berkeley) 2/23/95
30  * $FreeBSD$
31  */
32 /************************************************************************
33  * Note: In this file a 'fib' is a "forwarding information base"	*
34  * Which is the new name for an in kernel routing (next hop) table.	*
35  ***********************************************************************/
36 
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_route.h"
40 #include "opt_sctp.h"
41 #include "opt_mrouting.h"
42 #include "opt_mpath.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/socket.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <sys/sysproto.h>
52 #include <sys/proc.h>
53 #include <sys/domain.h>
54 #include <sys/kernel.h>
55 
56 #include <net/if.h>
57 #include <net/if_var.h>
58 #include <net/if_dl.h>
59 #include <net/route.h>
60 #include <net/vnet.h>
61 #include <net/flowtable.h>
62 
63 #ifdef RADIX_MPATH
64 #include <net/radix_mpath.h>
65 #endif
66 
67 #include <netinet/in.h>
68 #include <netinet/ip_mroute.h>
69 
70 #include <vm/uma.h>
71 
72 #define	RT_MAXFIBS	UINT16_MAX
73 
74 /* Kernel config default option. */
75 #ifdef ROUTETABLES
76 #if ROUTETABLES <= 0
77 #error "ROUTETABLES defined too low"
78 #endif
79 #if ROUTETABLES > RT_MAXFIBS
80 #error "ROUTETABLES defined too big"
81 #endif
82 #define	RT_NUMFIBS	ROUTETABLES
83 #endif /* ROUTETABLES */
84 /* Initialize to default if not otherwise set. */
85 #ifndef	RT_NUMFIBS
86 #define	RT_NUMFIBS	1
87 #endif
88 
89 #if defined(INET) || defined(INET6)
90 #ifdef SCTP
91 extern void sctp_addr_change(struct ifaddr *ifa, int cmd);
92 #endif /* SCTP */
93 #endif
94 
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_DEFINE(struct rtstat, rtstat);
115 #define	V_rtstat	VNET(rtstat)
116 
117 VNET_DEFINE(struct radix_node_head *, rt_tables);
118 #define	V_rt_tables	VNET(rt_tables)
119 
120 VNET_DEFINE(int, rttrash);		/* routes not in table but not freed */
121 #define	V_rttrash	VNET(rttrash)
122 
123 
124 /*
125  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
126  * The operation can be done safely (in this code) because a
127  * 'struct rtentry' starts with two 'struct radix_node''s, the first
128  * one representing leaf nodes in the routing tree, which is
129  * what the code in radix.c passes us as a 'struct radix_node'.
130  *
131  * But because there are a lot of assumptions in this conversion,
132  * do not cast explicitly, but always use the macro below.
133  */
134 #define RNTORT(p)	((struct rtentry *)(p))
135 
136 static VNET_DEFINE(uma_zone_t, rtzone);		/* Routing table UMA zone. */
137 #define	V_rtzone	VNET(rtzone)
138 
139 static int rtrequest1_fib_change(struct radix_node_head *, struct rt_addrinfo *,
140     struct rtentry **, u_int);
141 static void rt_setmetrics(const struct rt_addrinfo *, struct rtentry *);
142 static int rt_ifdelroute(const struct rtentry *rt, void *arg);
143 static struct rtentry *rt_unlinkrte(struct radix_node_head *rnh,
144     struct rt_addrinfo *info, int *perror);
145 static void rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info);
146 #ifdef RADIX_MPATH
147 static struct radix_node *rt_mpath_unlink(struct radix_node_head *rnh,
148     struct rt_addrinfo *info, struct rtentry *rto, int *perror);
149 #endif
150 static int rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info,
151     int flags);
152 
153 struct if_mtuinfo
154 {
155 	struct ifnet	*ifp;
156 	int		mtu;
157 };
158 
159 static int	if_updatemtu_cb(struct radix_node *, void *);
160 
161 /*
162  * handler for net.my_fibnum
163  */
164 static int
165 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
166 {
167         int fibnum;
168         int error;
169 
170         fibnum = curthread->td_proc->p_fibnum;
171         error = sysctl_handle_int(oidp, &fibnum, 0, req);
172         return (error);
173 }
174 
175 SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
176             NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
177 
178 static __inline struct radix_node_head **
179 rt_tables_get_rnh_ptr(int table, int fam)
180 {
181 	struct radix_node_head **rnh;
182 
183 	KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
184 	    __func__));
185 	KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
186 	    __func__));
187 
188 	/* rnh is [fib=0][af=0]. */
189 	rnh = (struct radix_node_head **)V_rt_tables;
190 	/* Get the offset to the requested table and fam. */
191 	rnh += table * (AF_MAX+1) + fam;
192 
193 	return (rnh);
194 }
195 
196 struct radix_node_head *
197 rt_tables_get_rnh(int table, int fam)
198 {
199 
200 	return (*rt_tables_get_rnh_ptr(table, fam));
201 }
202 
203 /*
204  * route initialization must occur before ip6_init2(), which happenas at
205  * SI_ORDER_MIDDLE.
206  */
207 static void
208 route_init(void)
209 {
210 
211 	/* whack the tunable ints into  line. */
212 	if (rt_numfibs > RT_MAXFIBS)
213 		rt_numfibs = RT_MAXFIBS;
214 	if (rt_numfibs == 0)
215 		rt_numfibs = 1;
216 }
217 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
218 
219 static int
220 rtentry_zinit(void *mem, int size, int how)
221 {
222 	struct rtentry *rt = mem;
223 
224 	rt->rt_pksent = counter_u64_alloc(how);
225 	if (rt->rt_pksent == NULL)
226 		return (ENOMEM);
227 
228 	RT_LOCK_INIT(rt);
229 
230 	return (0);
231 }
232 
233 static void
234 rtentry_zfini(void *mem, int size)
235 {
236 	struct rtentry *rt = mem;
237 
238 	RT_LOCK_DESTROY(rt);
239 	counter_u64_free(rt->rt_pksent);
240 }
241 
242 static int
243 rtentry_ctor(void *mem, int size, void *arg, int how)
244 {
245 	struct rtentry *rt = mem;
246 
247 	bzero(rt, offsetof(struct rtentry, rt_endzero));
248 	counter_u64_zero(rt->rt_pksent);
249 	rt->rt_chain = NULL;
250 
251 	return (0);
252 }
253 
254 static void
255 rtentry_dtor(void *mem, int size, void *arg)
256 {
257 	struct rtentry *rt = mem;
258 
259 	RT_UNLOCK_COND(rt);
260 }
261 
262 static void
263 vnet_route_init(const void *unused __unused)
264 {
265 	struct domain *dom;
266 	struct radix_node_head **rnh;
267 	int table;
268 	int fam;
269 
270 	V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
271 	    sizeof(struct radix_node_head *), M_RTABLE, M_WAITOK|M_ZERO);
272 
273 	V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
274 	    rtentry_ctor, rtentry_dtor,
275 	    rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
276 	for (dom = domains; dom; dom = dom->dom_next) {
277 		if (dom->dom_rtattach == NULL)
278 			continue;
279 
280 		for  (table = 0; table < rt_numfibs; table++) {
281 			fam = dom->dom_family;
282 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
283 				break;
284 
285 			rnh = rt_tables_get_rnh_ptr(table, fam);
286 			if (rnh == NULL)
287 				panic("%s: rnh NULL", __func__);
288 			dom->dom_rtattach((void **)rnh, 0);
289 		}
290 	}
291 }
292 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
293     vnet_route_init, 0);
294 
295 #ifdef VIMAGE
296 static void
297 vnet_route_uninit(const void *unused __unused)
298 {
299 	int table;
300 	int fam;
301 	struct domain *dom;
302 	struct radix_node_head **rnh;
303 
304 	for (dom = domains; dom; dom = dom->dom_next) {
305 		if (dom->dom_rtdetach == NULL)
306 			continue;
307 
308 		for (table = 0; table < rt_numfibs; table++) {
309 			fam = dom->dom_family;
310 
311 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
312 				break;
313 
314 			rnh = rt_tables_get_rnh_ptr(table, fam);
315 			if (rnh == NULL)
316 				panic("%s: rnh NULL", __func__);
317 			dom->dom_rtdetach((void **)rnh, 0);
318 		}
319 	}
320 
321 	free(V_rt_tables, M_RTABLE);
322 	uma_zdestroy(V_rtzone);
323 }
324 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
325     vnet_route_uninit, 0);
326 #endif
327 
328 #ifndef _SYS_SYSPROTO_H_
329 struct setfib_args {
330 	int     fibnum;
331 };
332 #endif
333 int
334 sys_setfib(struct thread *td, struct setfib_args *uap)
335 {
336 	if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
337 		return EINVAL;
338 	td->td_proc->p_fibnum = uap->fibnum;
339 	return (0);
340 }
341 
342 /*
343  * Packet routing routines.
344  */
345 void
346 rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
347 {
348 	struct rtentry *rt;
349 
350 	if ((rt = ro->ro_rt) != NULL) {
351 		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
352 			return;
353 		RTFREE(rt);
354 		ro->ro_rt = NULL;
355 	}
356 	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
357 	if (ro->ro_rt)
358 		RT_UNLOCK(ro->ro_rt);
359 }
360 
361 /*
362  * Look up the route that matches the address given
363  * Or, at least try.. Create a cloned route if needed.
364  *
365  * The returned route, if any, is locked.
366  */
367 struct rtentry *
368 rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
369 {
370 
371 	return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
372 }
373 
374 struct rtentry *
375 rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
376 		    u_int fibnum)
377 {
378 	struct radix_node_head *rnh;
379 	struct radix_node *rn;
380 	struct rtentry *newrt;
381 	struct rt_addrinfo info;
382 	int err = 0, msgtype = RTM_MISS;
383 
384 	KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
385 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
386 	newrt = NULL;
387 	if (rnh == NULL)
388 		goto miss;
389 
390 	/*
391 	 * Look up the address in the table for that Address Family
392 	 */
393 	RADIX_NODE_HEAD_RLOCK(rnh);
394 	rn = rnh->rnh_matchaddr(dst, rnh);
395 	if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
396 		newrt = RNTORT(rn);
397 		RT_LOCK(newrt);
398 		RT_ADDREF(newrt);
399 		RADIX_NODE_HEAD_RUNLOCK(rnh);
400 		return (newrt);
401 
402 	} else
403 		RADIX_NODE_HEAD_RUNLOCK(rnh);
404 
405 	/*
406 	 * Either we hit the root or couldn't find any match,
407 	 * Which basically means
408 	 * "caint get there frm here"
409 	 */
410 miss:
411 	V_rtstat.rts_unreach++;
412 
413 	if (report) {
414 		/*
415 		 * If required, report the failure to the supervising
416 		 * Authorities.
417 		 * For a delete, this is not an error. (report == 0)
418 		 */
419 		bzero(&info, sizeof(info));
420 		info.rti_info[RTAX_DST] = dst;
421 		rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
422 	}
423 	return (newrt);
424 }
425 
426 /*
427  * Remove a reference count from an rtentry.
428  * If the count gets low enough, take it out of the routing table
429  */
430 void
431 rtfree(struct rtentry *rt)
432 {
433 	struct radix_node_head *rnh;
434 
435 	KASSERT(rt != NULL,("%s: NULL rt", __func__));
436 	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
437 	KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
438 
439 	RT_LOCK_ASSERT(rt);
440 
441 	/*
442 	 * The callers should use RTFREE_LOCKED() or RTFREE(), so
443 	 * we should come here exactly with the last reference.
444 	 */
445 	RT_REMREF(rt);
446 	if (rt->rt_refcnt > 0) {
447 		log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
448 		goto done;
449 	}
450 
451 	/*
452 	 * On last reference give the "close method" a chance
453 	 * to cleanup private state.  This also permits (for
454 	 * IPv4 and IPv6) a chance to decide if the routing table
455 	 * entry should be purged immediately or at a later time.
456 	 * When an immediate purge is to happen the close routine
457 	 * typically calls rtexpunge which clears the RTF_UP flag
458 	 * on the entry so that the code below reclaims the storage.
459 	 */
460 	if (rt->rt_refcnt == 0 && rnh->rnh_close)
461 		rnh->rnh_close((struct radix_node *)rt, rnh);
462 
463 	/*
464 	 * If we are no longer "up" (and ref == 0)
465 	 * then we can free the resources associated
466 	 * with the route.
467 	 */
468 	if ((rt->rt_flags & RTF_UP) == 0) {
469 		if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
470 			panic("rtfree 2");
471 		/*
472 		 * the rtentry must have been removed from the routing table
473 		 * so it is represented in rttrash.. remove that now.
474 		 */
475 		V_rttrash--;
476 #ifdef	DIAGNOSTIC
477 		if (rt->rt_refcnt < 0) {
478 			printf("rtfree: %p not freed (neg refs)\n", rt);
479 			goto done;
480 		}
481 #endif
482 		/*
483 		 * release references on items we hold them on..
484 		 * e.g other routes and ifaddrs.
485 		 */
486 		if (rt->rt_ifa)
487 			ifa_free(rt->rt_ifa);
488 		/*
489 		 * The key is separatly alloc'd so free it (see rt_setgate()).
490 		 * This also frees the gateway, as they are always malloc'd
491 		 * together.
492 		 */
493 		R_Free(rt_key(rt));
494 
495 		/*
496 		 * and the rtentry itself of course
497 		 */
498 		uma_zfree(V_rtzone, rt);
499 		return;
500 	}
501 done:
502 	RT_UNLOCK(rt);
503 }
504 
505 
506 /*
507  * Force a routing table entry to the specified
508  * destination to go through the given gateway.
509  * Normally called as a result of a routing redirect
510  * message from the network layer.
511  */
512 void
513 rtredirect_fib(struct sockaddr *dst,
514 	struct sockaddr *gateway,
515 	struct sockaddr *netmask,
516 	int flags,
517 	struct sockaddr *src,
518 	u_int fibnum)
519 {
520 	struct rtentry *rt;
521 	int error = 0;
522 	short *stat = NULL;
523 	struct rt_addrinfo info;
524 	struct ifaddr *ifa;
525 	struct radix_node_head *rnh;
526 
527 	ifa = NULL;
528 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
529 	if (rnh == NULL) {
530 		error = EAFNOSUPPORT;
531 		goto out;
532 	}
533 
534 	/* verify the gateway is directly reachable */
535 	if ((ifa = ifa_ifwithnet(gateway, 0, fibnum)) == NULL) {
536 		error = ENETUNREACH;
537 		goto out;
538 	}
539 	rt = rtalloc1_fib(dst, 0, 0UL, fibnum);	/* NB: rt is locked */
540 	/*
541 	 * If the redirect isn't from our current router for this dst,
542 	 * it's either old or wrong.  If it redirects us to ourselves,
543 	 * we have a routing loop, perhaps as a result of an interface
544 	 * going down recently.
545 	 */
546 	if (!(flags & RTF_DONE) && rt) {
547 		if (!sa_equal(src, rt->rt_gateway)) {
548 			error = EINVAL;
549 			goto done;
550 		}
551 		if (rt->rt_ifa != ifa && ifa->ifa_addr->sa_family != AF_LINK) {
552 			error = EINVAL;
553 			goto done;
554 		}
555 	}
556 	if ((flags & RTF_GATEWAY) && ifa_ifwithaddr_check(gateway)) {
557 		error = EHOSTUNREACH;
558 		goto done;
559 	}
560 	/*
561 	 * Create a new entry if we just got back a wildcard entry
562 	 * or the lookup failed.  This is necessary for hosts
563 	 * which use routing redirects generated by smart gateways
564 	 * to dynamically build the routing tables.
565 	 */
566 	if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
567 		goto create;
568 	/*
569 	 * Don't listen to the redirect if it's
570 	 * for a route to an interface.
571 	 */
572 	if (rt->rt_flags & RTF_GATEWAY) {
573 		if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
574 			/*
575 			 * Changing from route to net => route to host.
576 			 * Create new route, rather than smashing route to net.
577 			 */
578 		create:
579 			if (rt != NULL)
580 				RTFREE_LOCKED(rt);
581 
582 			flags |= RTF_DYNAMIC;
583 			bzero((caddr_t)&info, sizeof(info));
584 			info.rti_info[RTAX_DST] = dst;
585 			info.rti_info[RTAX_GATEWAY] = gateway;
586 			info.rti_info[RTAX_NETMASK] = netmask;
587 			info.rti_ifa = ifa;
588 			info.rti_flags = flags;
589 			error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
590 			if (rt != NULL) {
591 				RT_LOCK(rt);
592 				flags = rt->rt_flags;
593 			}
594 
595 			stat = &V_rtstat.rts_dynamic;
596 		} else {
597 
598 			/*
599 			 * Smash the current notion of the gateway to
600 			 * this destination.  Should check about netmask!!!
601 			 */
602 			if ((flags & RTF_GATEWAY) == 0)
603 				rt->rt_flags &= ~RTF_GATEWAY;
604 			rt->rt_flags |= RTF_MODIFIED;
605 			flags |= RTF_MODIFIED;
606 			stat = &V_rtstat.rts_newgateway;
607 			/*
608 			 * add the key and gateway (in one malloc'd chunk).
609 			 */
610 			RT_UNLOCK(rt);
611 			RADIX_NODE_HEAD_LOCK(rnh);
612 			RT_LOCK(rt);
613 			rt_setgate(rt, rt_key(rt), gateway);
614 			RADIX_NODE_HEAD_UNLOCK(rnh);
615 		}
616 	} else
617 		error = EHOSTUNREACH;
618 done:
619 	if (rt)
620 		RTFREE_LOCKED(rt);
621 out:
622 	if (error)
623 		V_rtstat.rts_badredirect++;
624 	else if (stat != NULL)
625 		(*stat)++;
626 	bzero((caddr_t)&info, sizeof(info));
627 	info.rti_info[RTAX_DST] = dst;
628 	info.rti_info[RTAX_GATEWAY] = gateway;
629 	info.rti_info[RTAX_NETMASK] = netmask;
630 	info.rti_info[RTAX_AUTHOR] = src;
631 	rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
632 	if (ifa != NULL)
633 		ifa_free(ifa);
634 }
635 
636 /*
637  * Routing table ioctl interface.
638  */
639 int
640 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
641 {
642 
643 	/*
644 	 * If more ioctl commands are added here, make sure the proper
645 	 * super-user checks are being performed because it is possible for
646 	 * prison-root to make it this far if raw sockets have been enabled
647 	 * in jails.
648 	 */
649 #ifdef INET
650 	/* Multicast goop, grrr... */
651 	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
652 #else /* INET */
653 	return ENXIO;
654 #endif /* INET */
655 }
656 
657 struct ifaddr *
658 ifa_ifwithroute(int flags, const struct sockaddr *dst, struct sockaddr *gateway,
659 				u_int fibnum)
660 {
661 	struct ifaddr *ifa;
662 	int not_found = 0;
663 
664 	if ((flags & RTF_GATEWAY) == 0) {
665 		/*
666 		 * If we are adding a route to an interface,
667 		 * and the interface is a pt to pt link
668 		 * we should search for the destination
669 		 * as our clue to the interface.  Otherwise
670 		 * we can use the local address.
671 		 */
672 		ifa = NULL;
673 		if (flags & RTF_HOST)
674 			ifa = ifa_ifwithdstaddr(dst, fibnum);
675 		if (ifa == NULL)
676 			ifa = ifa_ifwithaddr(gateway);
677 	} else {
678 		/*
679 		 * If we are adding a route to a remote net
680 		 * or host, the gateway may still be on the
681 		 * other end of a pt to pt link.
682 		 */
683 		ifa = ifa_ifwithdstaddr(gateway, fibnum);
684 	}
685 	if (ifa == NULL)
686 		ifa = ifa_ifwithnet(gateway, 0, fibnum);
687 	if (ifa == NULL) {
688 		struct rtentry *rt = rtalloc1_fib(gateway, 0, 0, fibnum);
689 		if (rt == NULL)
690 			return (NULL);
691 		/*
692 		 * dismiss a gateway that is reachable only
693 		 * through the default router
694 		 */
695 		switch (gateway->sa_family) {
696 		case AF_INET:
697 			if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
698 				not_found = 1;
699 			break;
700 		case AF_INET6:
701 			if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
702 				not_found = 1;
703 			break;
704 		default:
705 			break;
706 		}
707 		if (!not_found && rt->rt_ifa != NULL) {
708 			ifa = rt->rt_ifa;
709 			ifa_ref(ifa);
710 		}
711 		RT_REMREF(rt);
712 		RT_UNLOCK(rt);
713 		if (not_found || ifa == NULL)
714 			return (NULL);
715 	}
716 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
717 		struct ifaddr *oifa = ifa;
718 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
719 		if (ifa == NULL)
720 			ifa = oifa;
721 		else
722 			ifa_free(oifa);
723 	}
724 	return (ifa);
725 }
726 
727 /*
728  * Do appropriate manipulations of a routing tree given
729  * all the bits of info needed
730  */
731 int
732 rtrequest_fib(int req,
733 	struct sockaddr *dst,
734 	struct sockaddr *gateway,
735 	struct sockaddr *netmask,
736 	int flags,
737 	struct rtentry **ret_nrt,
738 	u_int fibnum)
739 {
740 	struct rt_addrinfo info;
741 
742 	if (dst->sa_len == 0)
743 		return(EINVAL);
744 
745 	bzero((caddr_t)&info, sizeof(info));
746 	info.rti_flags = flags;
747 	info.rti_info[RTAX_DST] = dst;
748 	info.rti_info[RTAX_GATEWAY] = gateway;
749 	info.rti_info[RTAX_NETMASK] = netmask;
750 	return rtrequest1_fib(req, &info, ret_nrt, fibnum);
751 }
752 
753 
754 /*
755  * Copy most of @rt data into @info.
756  *
757  * If @flags contains NHR_COPY, copies dst,netmask and gw to the
758  * pointers specified by @info structure. Assume such pointers
759  * are zeroed sockaddr-like structures with sa_len field initialized
760  * to reflect size of the provided buffer. if no NHR_COPY is specified,
761  * point dst,netmask and gw @info fields to appropriate @rt values.
762  *
763  * if @flags contains NHR_REF, do refcouting on rt_ifp.
764  *
765  * Returns 0 on success.
766  */
767 int
768 rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info, int flags)
769 {
770 	struct rt_metrics *rmx;
771 	struct sockaddr *src, *dst;
772 	int sa_len;
773 
774 	if (flags & NHR_COPY) {
775 		/* Copy destination if dst is non-zero */
776 		src = rt_key(rt);
777 		dst = info->rti_info[RTAX_DST];
778 		sa_len = src->sa_len;
779 		if (dst != NULL) {
780 			if (src->sa_len > dst->sa_len)
781 				return (ENOMEM);
782 			memcpy(dst, src, src->sa_len);
783 			info->rti_addrs |= RTA_DST;
784 		}
785 
786 		/* Copy mask if set && dst is non-zero */
787 		src = rt_mask(rt);
788 		dst = info->rti_info[RTAX_NETMASK];
789 		if (src != NULL && dst != NULL) {
790 
791 			/*
792 			 * Radix stores different value in sa_len,
793 			 * assume rt_mask() to have the same length
794 			 * as rt_key()
795 			 */
796 			if (sa_len > dst->sa_len)
797 				return (ENOMEM);
798 			memcpy(dst, src, src->sa_len);
799 			info->rti_addrs |= RTA_NETMASK;
800 		}
801 
802 		/* Copy gateway is set && dst is non-zero */
803 		src = rt->rt_gateway;
804 		dst = info->rti_info[RTAX_GATEWAY];
805 		if ((rt->rt_flags & RTF_GATEWAY) && src != NULL && dst != NULL){
806 			if (src->sa_len > dst->sa_len)
807 				return (ENOMEM);
808 			memcpy(dst, src, src->sa_len);
809 			info->rti_addrs |= RTA_GATEWAY;
810 		}
811 	} else {
812 		info->rti_info[RTAX_DST] = rt_key(rt);
813 		info->rti_addrs |= RTA_DST;
814 		if (rt_mask(rt) != NULL) {
815 			info->rti_info[RTAX_NETMASK] = rt_mask(rt);
816 			info->rti_addrs |= RTA_NETMASK;
817 		}
818 		if (rt->rt_flags & RTF_GATEWAY) {
819 			info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
820 			info->rti_addrs |= RTA_GATEWAY;
821 		}
822 	}
823 
824 	rmx = info->rti_rmx;
825 	if (rmx != NULL) {
826 		info->rti_mflags |= RTV_MTU;
827 		rmx->rmx_mtu = rt->rt_mtu;
828 	}
829 
830 	info->rti_flags = rt->rt_flags;
831 	info->rti_ifp = rt->rt_ifp;
832 	info->rti_ifa = rt->rt_ifa;
833 
834 	if (flags & NHR_REF) {
835 		/* Do 'traditional' refcouting */
836 		if_ref(info->rti_ifp);
837 	}
838 
839 	return (0);
840 }
841 
842 /*
843  * Lookups up route entry for @dst in RIB database for fib @fibnum.
844  * Exports entry data to @info using rt_exportinfo().
845  *
846  * if @flags contains NHR_REF, refcouting is performed on rt_ifp.
847  *   All references can be released later by calling rib_free_info()
848  *
849  * Returns 0 on success.
850  * Returns ENOENT for lookup failure, ENOMEM for export failure.
851  */
852 int
853 rib_lookup_info(uint32_t fibnum, const struct sockaddr *dst, uint32_t flags,
854     uint32_t flowid, struct rt_addrinfo *info)
855 {
856 	struct radix_node_head *rh;
857 	struct radix_node *rn;
858 	struct rtentry *rt;
859 	int error;
860 
861 	KASSERT((fibnum < rt_numfibs), ("rib_lookup_rte: bad fibnum"));
862 	rh = rt_tables_get_rnh(fibnum, dst->sa_family);
863 	if (rh == NULL)
864 		return (ENOENT);
865 
866 	RADIX_NODE_HEAD_RLOCK(rh);
867 	rn = rh->rnh_matchaddr(__DECONST(void *, dst), rh);
868 	if (rn != NULL && ((rn->rn_flags & RNF_ROOT) == 0)) {
869 		rt = RNTORT(rn);
870 		/* Ensure route & ifp is UP */
871 		if (RT_LINK_IS_UP(rt->rt_ifp)) {
872 			flags = (flags & NHR_REF) | NHR_COPY;
873 			error = rt_exportinfo(rt, info, flags);
874 			RADIX_NODE_HEAD_RUNLOCK(rh);
875 
876 			return (error);
877 		}
878 	}
879 	RADIX_NODE_HEAD_RUNLOCK(rh);
880 
881 	return (ENOENT);
882 }
883 
884 /*
885  * Releases all references acquired by rib_lookup_info() when
886  * called with NHR_REF flags.
887  */
888 void
889 rib_free_info(struct rt_addrinfo *info)
890 {
891 
892 	if_rele(info->rti_ifp);
893 }
894 
895 /*
896  * Iterates over all existing fibs in system calling
897  *  @setwa_f function prior to traversing each fib.
898  *  Calls @wa_f function for each element in current fib.
899  * If af is not AF_UNSPEC, iterates over fibs in particular
900  * address family.
901  */
902 void
903 rt_foreach_fib_walk(int af, rt_setwarg_t *setwa_f, rt_walktree_f_t *wa_f,
904     void *arg)
905 {
906 	struct radix_node_head *rnh;
907 	uint32_t fibnum;
908 	int i;
909 
910 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
911 		/* Do we want some specific family? */
912 		if (af != AF_UNSPEC) {
913 			rnh = rt_tables_get_rnh(fibnum, af);
914 			if (rnh == NULL)
915 				continue;
916 			if (setwa_f != NULL)
917 				setwa_f(rnh, fibnum, af, arg);
918 
919 			RADIX_NODE_HEAD_LOCK(rnh);
920 			rnh->rnh_walktree(rnh, (walktree_f_t *)wa_f, arg);
921 			RADIX_NODE_HEAD_UNLOCK(rnh);
922 			continue;
923 		}
924 
925 		for (i = 1; i <= AF_MAX; i++) {
926 			rnh = rt_tables_get_rnh(fibnum, i);
927 			if (rnh == NULL)
928 				continue;
929 			if (setwa_f != NULL)
930 				setwa_f(rnh, fibnum, i, arg);
931 
932 			RADIX_NODE_HEAD_LOCK(rnh);
933 			rnh->rnh_walktree(rnh, (walktree_f_t *)wa_f, arg);
934 			RADIX_NODE_HEAD_UNLOCK(rnh);
935 		}
936 	}
937 }
938 
939 struct rt_delinfo
940 {
941 	struct rt_addrinfo info;
942 	struct radix_node_head *rnh;
943 	struct rtentry *head;
944 };
945 
946 /*
947  * Conditionally unlinks @rn from radix tree based
948  * on info data passed in @arg.
949  */
950 static int
951 rt_checkdelroute(struct radix_node *rn, void *arg)
952 {
953 	struct rt_delinfo *di;
954 	struct rt_addrinfo *info;
955 	struct rtentry *rt;
956 	int error;
957 
958 	di = (struct rt_delinfo *)arg;
959 	rt = (struct rtentry *)rn;
960 	info = &di->info;
961 	error = 0;
962 
963 	info->rti_info[RTAX_DST] = rt_key(rt);
964 	info->rti_info[RTAX_NETMASK] = rt_mask(rt);
965 	info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
966 
967 	rt = rt_unlinkrte(di->rnh, info, &error);
968 	if (rt == NULL) {
969 		/* Either not allowed or not matched. Skip entry */
970 		return (0);
971 	}
972 
973 	/* Entry was unlinked. Add to the list and return */
974 	rt->rt_chain = di->head;
975 	di->head = rt;
976 
977 	return (0);
978 }
979 
980 /*
981  * Iterates over all existing fibs in system.
982  * Deletes each element for which @filter_f function returned
983  * non-zero value.
984  * If @af is not AF_UNSPEC, iterates over fibs in particular
985  * address family.
986  */
987 void
988 rt_foreach_fib_walk_del(int af, rt_filter_f_t *filter_f, void *arg)
989 {
990 	struct radix_node_head *rnh;
991 	struct rt_delinfo di;
992 	struct rtentry *rt;
993 	uint32_t fibnum;
994 	int i, start, end;
995 
996 	bzero(&di, sizeof(di));
997 	di.info.rti_filter = filter_f;
998 	di.info.rti_filterdata = arg;
999 
1000 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
1001 		/* Do we want some specific family? */
1002 		if (af != AF_UNSPEC) {
1003 			start = af;
1004 			end = af;
1005 		} else {
1006 			start = 1;
1007 			end = AF_MAX;
1008 		}
1009 
1010 		for (i = start; i <= end; i++) {
1011 			rnh = rt_tables_get_rnh(fibnum, i);
1012 			if (rnh == NULL)
1013 				continue;
1014 			di.rnh = rnh;
1015 
1016 			RADIX_NODE_HEAD_LOCK(rnh);
1017 			rnh->rnh_walktree(rnh, rt_checkdelroute, &di);
1018 			RADIX_NODE_HEAD_UNLOCK(rnh);
1019 
1020 			if (di.head == NULL)
1021 				continue;
1022 
1023 			/* We might have something to reclaim */
1024 			while (di.head != NULL) {
1025 				rt = di.head;
1026 				di.head = rt->rt_chain;
1027 				rt->rt_chain = NULL;
1028 
1029 				/* TODO std rt -> rt_addrinfo export */
1030 				di.info.rti_info[RTAX_DST] = rt_key(rt);
1031 				di.info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1032 
1033 				rt_notifydelete(rt, &di.info);
1034 				RTFREE_LOCKED(rt);
1035 			}
1036 
1037 		}
1038 	}
1039 }
1040 
1041 /*
1042  * Delete Routes for a Network Interface
1043  *
1044  * Called for each routing entry via the rnh->rnh_walktree() call above
1045  * to delete all route entries referencing a detaching network interface.
1046  *
1047  * Arguments:
1048  *	rt	pointer to rtentry
1049  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
1050  *
1051  * Returns:
1052  *	0	successful
1053  *	errno	failed - reason indicated
1054  */
1055 static int
1056 rt_ifdelroute(const struct rtentry *rt, void *arg)
1057 {
1058 	struct ifnet	*ifp = arg;
1059 
1060 	if (rt->rt_ifp != ifp)
1061 		return (0);
1062 
1063 	/*
1064 	 * Protect (sorta) against walktree recursion problems
1065 	 * with cloned routes
1066 	 */
1067 	if ((rt->rt_flags & RTF_UP) == 0)
1068 		return (0);
1069 
1070 	return (1);
1071 }
1072 
1073 /*
1074  * Delete all remaining routes using this interface
1075  * Unfortuneatly the only way to do this is to slog through
1076  * the entire routing table looking for routes which point
1077  * to this interface...oh well...
1078  */
1079 void
1080 rt_flushifroutes(struct ifnet *ifp)
1081 {
1082 
1083 	rt_foreach_fib_walk_del(AF_UNSPEC, rt_ifdelroute, ifp);
1084 }
1085 
1086 /*
1087  * Conditionally unlinks rtentry matching data inside @info from @rnh.
1088  * Returns unlinked, locked and referenced @rtentry on success,
1089  * Returns NULL and sets @perror to:
1090  * ESRCH - if prefix was not found,
1091  * EADDRINUSE - if trying to delete PINNED route without appropriate flag.
1092  * ENOENT - if supplied filter function returned 0 (not matched).
1093  */
1094 static struct rtentry *
1095 rt_unlinkrte(struct radix_node_head *rnh, struct rt_addrinfo *info, int *perror)
1096 {
1097 	struct sockaddr *dst, *netmask;
1098 	struct rtentry *rt;
1099 	struct radix_node *rn;
1100 
1101 	dst = info->rti_info[RTAX_DST];
1102 	netmask = info->rti_info[RTAX_NETMASK];
1103 
1104 	rt = (struct rtentry *)rnh->rnh_lookup(dst, netmask, rnh);
1105 	if (rt == NULL) {
1106 		*perror = ESRCH;
1107 		return (NULL);
1108 	}
1109 
1110 	if ((info->rti_flags & RTF_PINNED) == 0) {
1111 		/* Check if target route can be deleted */
1112 		if (rt->rt_flags & RTF_PINNED) {
1113 			*perror = EADDRINUSE;
1114 			return (NULL);
1115 		}
1116 	}
1117 
1118 	if (info->rti_filter != NULL) {
1119 		if (info->rti_filter(rt, info->rti_filterdata) == 0) {
1120 			/* Not matched */
1121 			*perror = ENOENT;
1122 			return (NULL);
1123 		}
1124 
1125 		/*
1126 		 * Filter function requested rte deletion.
1127 		 * Ease the caller work by filling in remaining info
1128 		 * from that particular entry.
1129 		 */
1130 		info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1131 	}
1132 
1133 	/*
1134 	 * Remove the item from the tree and return it.
1135 	 * Complain if it is not there and do no more processing.
1136 	 */
1137 	*perror = ESRCH;
1138 #ifdef RADIX_MPATH
1139 	if (rn_mpath_capable(rnh))
1140 		rn = rt_mpath_unlink(rnh, info, rt, perror);
1141 	else
1142 #endif
1143 	rn = rnh->rnh_deladdr(dst, netmask, rnh);
1144 	if (rn == NULL)
1145 		return (NULL);
1146 
1147 	if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1148 		panic ("rtrequest delete");
1149 
1150 	rt = RNTORT(rn);
1151 	RT_LOCK(rt);
1152 	RT_ADDREF(rt);
1153 	rt->rt_flags &= ~RTF_UP;
1154 
1155 	*perror = 0;
1156 
1157 	return (rt);
1158 }
1159 
1160 static void
1161 rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info)
1162 {
1163 	struct ifaddr *ifa;
1164 
1165 	/*
1166 	 * give the protocol a chance to keep things in sync.
1167 	 */
1168 	ifa = rt->rt_ifa;
1169 	if (ifa != NULL && ifa->ifa_rtrequest != NULL)
1170 		ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1171 
1172 	/*
1173 	 * One more rtentry floating around that is not
1174 	 * linked to the routing table. rttrash will be decremented
1175 	 * when RTFREE(rt) is eventually called.
1176 	 */
1177 	V_rttrash++;
1178 }
1179 
1180 
1181 /*
1182  * These (questionable) definitions of apparent local variables apply
1183  * to the next two functions.  XXXXXX!!!
1184  */
1185 #define	dst	info->rti_info[RTAX_DST]
1186 #define	gateway	info->rti_info[RTAX_GATEWAY]
1187 #define	netmask	info->rti_info[RTAX_NETMASK]
1188 #define	ifaaddr	info->rti_info[RTAX_IFA]
1189 #define	ifpaddr	info->rti_info[RTAX_IFP]
1190 #define	flags	info->rti_flags
1191 
1192 /*
1193  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
1194  * it will be referenced so the caller must free it.
1195  */
1196 int
1197 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
1198 {
1199 	struct ifaddr *ifa;
1200 	int error = 0;
1201 
1202 	/*
1203 	 * ifp may be specified by sockaddr_dl
1204 	 * when protocol address is ambiguous.
1205 	 */
1206 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
1207 	    ifpaddr->sa_family == AF_LINK &&
1208 	    (ifa = ifa_ifwithnet(ifpaddr, 0, fibnum)) != NULL) {
1209 		info->rti_ifp = ifa->ifa_ifp;
1210 		ifa_free(ifa);
1211 	}
1212 	if (info->rti_ifa == NULL && ifaaddr != NULL)
1213 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
1214 	if (info->rti_ifa == NULL) {
1215 		struct sockaddr *sa;
1216 
1217 		sa = ifaaddr != NULL ? ifaaddr :
1218 		    (gateway != NULL ? gateway : dst);
1219 		if (sa != NULL && info->rti_ifp != NULL)
1220 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
1221 		else if (dst != NULL && gateway != NULL)
1222 			info->rti_ifa = ifa_ifwithroute(flags, dst, gateway,
1223 							fibnum);
1224 		else if (sa != NULL)
1225 			info->rti_ifa = ifa_ifwithroute(flags, sa, sa,
1226 							fibnum);
1227 	}
1228 	if ((ifa = info->rti_ifa) != NULL) {
1229 		if (info->rti_ifp == NULL)
1230 			info->rti_ifp = ifa->ifa_ifp;
1231 	} else
1232 		error = ENETUNREACH;
1233 	return (error);
1234 }
1235 
1236 static int
1237 if_updatemtu_cb(struct radix_node *rn, void *arg)
1238 {
1239 	struct rtentry *rt;
1240 	struct if_mtuinfo *ifmtu;
1241 
1242 	rt = (struct rtentry *)rn;
1243 	ifmtu = (struct if_mtuinfo *)arg;
1244 
1245 	if (rt->rt_ifp != ifmtu->ifp)
1246 		return (0);
1247 
1248 	if (rt->rt_mtu >= ifmtu->mtu) {
1249 		/* We have to decrease mtu regardless of flags */
1250 		rt->rt_mtu = ifmtu->mtu;
1251 		return (0);
1252 	}
1253 
1254 	/*
1255 	 * New MTU is bigger. Check if are allowed to alter it
1256 	 */
1257 	if ((rt->rt_flags & (RTF_FIXEDMTU | RTF_GATEWAY | RTF_HOST)) != 0) {
1258 
1259 		/*
1260 		 * Skip routes with user-supplied MTU and
1261 		 * non-interface routes
1262 		 */
1263 		return (0);
1264 	}
1265 
1266 	/* We are safe to update route MTU */
1267 	rt->rt_mtu = ifmtu->mtu;
1268 
1269 	return (0);
1270 }
1271 
1272 void
1273 rt_updatemtu(struct ifnet *ifp)
1274 {
1275 	struct if_mtuinfo ifmtu;
1276 	struct radix_node_head *rnh;
1277 	int i, j;
1278 
1279 	ifmtu.ifp = ifp;
1280 
1281 	/*
1282 	 * Try to update rt_mtu for all routes using this interface
1283 	 * Unfortunately the only way to do this is to traverse all
1284 	 * routing tables in all fibs/domains.
1285 	 */
1286 	for (i = 1; i <= AF_MAX; i++) {
1287 		ifmtu.mtu = if_getmtu_family(ifp, i);
1288 		for (j = 0; j < rt_numfibs; j++) {
1289 			rnh = rt_tables_get_rnh(j, i);
1290 			if (rnh == NULL)
1291 				continue;
1292 			RADIX_NODE_HEAD_LOCK(rnh);
1293 			rnh->rnh_walktree(rnh, if_updatemtu_cb, &ifmtu);
1294 			RADIX_NODE_HEAD_UNLOCK(rnh);
1295 		}
1296 	}
1297 }
1298 
1299 
1300 #if 0
1301 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
1302 int rt_print(char *buf, int buflen, struct rtentry *rt);
1303 
1304 int
1305 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
1306 {
1307 	void *paddr = NULL;
1308 
1309 	switch (s->sa_family) {
1310 	case AF_INET:
1311 		paddr = &((struct sockaddr_in *)s)->sin_addr;
1312 		break;
1313 	case AF_INET6:
1314 		paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
1315 		break;
1316 	}
1317 
1318 	if (paddr == NULL)
1319 		return (0);
1320 
1321 	if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
1322 		return (0);
1323 
1324 	return (strlen(buf));
1325 }
1326 
1327 int
1328 rt_print(char *buf, int buflen, struct rtentry *rt)
1329 {
1330 	struct sockaddr *addr, *mask;
1331 	int i = 0;
1332 
1333 	addr = rt_key(rt);
1334 	mask = rt_mask(rt);
1335 
1336 	i = p_sockaddr(buf, buflen, addr);
1337 	if (!(rt->rt_flags & RTF_HOST)) {
1338 		buf[i++] = '/';
1339 		i += p_sockaddr(buf + i, buflen - i, mask);
1340 	}
1341 
1342 	if (rt->rt_flags & RTF_GATEWAY) {
1343 		buf[i++] = '>';
1344 		i += p_sockaddr(buf + i, buflen - i, rt->rt_gateway);
1345 	}
1346 
1347 	return (i);
1348 }
1349 #endif
1350 
1351 #ifdef RADIX_MPATH
1352 /*
1353  * Deletes key for single-path routes, unlinks rtentry with
1354  * gateway specified in @info from multi-path routes.
1355  *
1356  * Returnes unlinked entry. In case of failure, returns NULL
1357  * and sets @perror to ESRCH.
1358  */
1359 static struct radix_node *
1360 rt_mpath_unlink(struct radix_node_head *rnh, struct rt_addrinfo *info,
1361     struct rtentry *rto, int *perror)
1362 {
1363 	/*
1364 	 * if we got multipath routes, we require users to specify
1365 	 * a matching RTAX_GATEWAY.
1366 	 */
1367 	struct rtentry *rt; // *rto = NULL;
1368 	struct radix_node *rn;
1369 	struct sockaddr *gw;
1370 
1371 	gw = info->rti_info[RTAX_GATEWAY];
1372 	rt = rt_mpath_matchgate(rto, gw);
1373 	if (rt == NULL) {
1374 		*perror = ESRCH;
1375 		return (NULL);
1376 	}
1377 
1378 	/*
1379 	 * this is the first entry in the chain
1380 	 */
1381 	if (rto == rt) {
1382 		rn = rn_mpath_next((struct radix_node *)rt);
1383 		/*
1384 		 * there is another entry, now it's active
1385 		 */
1386 		if (rn) {
1387 			rto = RNTORT(rn);
1388 			RT_LOCK(rto);
1389 			rto->rt_flags |= RTF_UP;
1390 			RT_UNLOCK(rto);
1391 		} else if (rt->rt_flags & RTF_GATEWAY) {
1392 			/*
1393 			 * For gateway routes, we need to
1394 			 * make sure that we we are deleting
1395 			 * the correct gateway.
1396 			 * rt_mpath_matchgate() does not
1397 			 * check the case when there is only
1398 			 * one route in the chain.
1399 			 */
1400 			if (gw &&
1401 			    (rt->rt_gateway->sa_len != gw->sa_len ||
1402 				memcmp(rt->rt_gateway, gw, gw->sa_len))) {
1403 				*perror = ESRCH;
1404 				return (NULL);
1405 			}
1406 		}
1407 
1408 		/*
1409 		 * use the normal delete code to remove
1410 		 * the first entry
1411 		 */
1412 		rn = rnh->rnh_deladdr(dst, netmask, rnh);
1413 		*perror = 0;
1414 		return (rn);
1415 	}
1416 
1417 	/*
1418 	 * if the entry is 2nd and on up
1419 	 */
1420 	if (rt_mpath_deldup(rto, rt) == 0)
1421 		panic ("rtrequest1: rt_mpath_deldup");
1422 	*perror = 0;
1423 	rn = (struct radix_node *)rt;
1424 	return (rn);
1425 }
1426 #endif
1427 
1428 #ifdef FLOWTABLE
1429 static struct rtentry *
1430 rt_flowtable_check_route(struct radix_node_head *rnh, struct rt_addrinfo *info)
1431 {
1432 #if defined(INET6) || defined(INET)
1433 	struct radix_node *rn;
1434 #endif
1435 	struct rtentry *rt0;
1436 
1437 	rt0 = NULL;
1438 	/* "flow-table" only supports IPv6 and IPv4 at the moment. */
1439 	switch (dst->sa_family) {
1440 #ifdef INET6
1441 	case AF_INET6:
1442 #endif
1443 #ifdef INET
1444 	case AF_INET:
1445 #endif
1446 #if defined(INET6) || defined(INET)
1447 		rn = rnh->rnh_matchaddr(dst, rnh);
1448 		if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
1449 			struct sockaddr *mask;
1450 			u_char *m, *n;
1451 			int len;
1452 
1453 			/*
1454 			 * compare mask to see if the new route is
1455 			 * more specific than the existing one
1456 			 */
1457 			rt0 = RNTORT(rn);
1458 			RT_LOCK(rt0);
1459 			RT_ADDREF(rt0);
1460 			RT_UNLOCK(rt0);
1461 			/*
1462 			 * A host route is already present, so
1463 			 * leave the flow-table entries as is.
1464 			 */
1465 			if (rt0->rt_flags & RTF_HOST) {
1466 				RTFREE(rt0);
1467 				rt0 = NULL;
1468 			} else if (!(flags & RTF_HOST) && netmask) {
1469 				mask = rt_mask(rt0);
1470 				len = mask->sa_len;
1471 				m = (u_char *)mask;
1472 				n = (u_char *)netmask;
1473 				while (len-- > 0) {
1474 					if (*n != *m)
1475 						break;
1476 					n++;
1477 					m++;
1478 				}
1479 				if (len == 0 || (*n < *m)) {
1480 					RTFREE(rt0);
1481 					rt0 = NULL;
1482 				}
1483 			}
1484 		}
1485 #endif/* INET6 || INET */
1486 	}
1487 
1488 	return (rt0);
1489 }
1490 #endif
1491 
1492 int
1493 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1494 				u_int fibnum)
1495 {
1496 	int error = 0;
1497 	struct rtentry *rt, *rt_old;
1498 #ifdef FLOWTABLE
1499 	struct rtentry *rt0;
1500 #endif
1501 	struct radix_node *rn;
1502 	struct radix_node_head *rnh;
1503 	struct ifaddr *ifa;
1504 	struct sockaddr *ndst;
1505 	struct sockaddr_storage mdst;
1506 
1507 	KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1508 	KASSERT((flags & RTF_RNH_LOCKED) == 0, ("rtrequest1_fib: locked"));
1509 	switch (dst->sa_family) {
1510 	case AF_INET6:
1511 	case AF_INET:
1512 		/* We support multiple FIBs. */
1513 		break;
1514 	default:
1515 		fibnum = RT_DEFAULT_FIB;
1516 		break;
1517 	}
1518 
1519 	/*
1520 	 * Find the correct routing tree to use for this Address Family
1521 	 */
1522 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1523 	if (rnh == NULL)
1524 		return (EAFNOSUPPORT);
1525 
1526 	/*
1527 	 * If we are adding a host route then we don't want to put
1528 	 * a netmask in the tree, nor do we want to clone it.
1529 	 */
1530 	if (flags & RTF_HOST)
1531 		netmask = NULL;
1532 
1533 	switch (req) {
1534 	case RTM_DELETE:
1535 		if (netmask) {
1536 			rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1537 			dst = (struct sockaddr *)&mdst;
1538 		}
1539 
1540 		RADIX_NODE_HEAD_LOCK(rnh);
1541 		rt = rt_unlinkrte(rnh, info, &error);
1542 		RADIX_NODE_HEAD_UNLOCK(rnh);
1543 		if (error != 0)
1544 			return (error);
1545 
1546 		rt_notifydelete(rt, info);
1547 
1548 		/*
1549 		 * If the caller wants it, then it can have it,
1550 		 * but it's up to it to free the rtentry as we won't be
1551 		 * doing it.
1552 		 */
1553 		if (ret_nrt) {
1554 			*ret_nrt = rt;
1555 			RT_UNLOCK(rt);
1556 		} else
1557 			RTFREE_LOCKED(rt);
1558 		break;
1559 	case RTM_RESOLVE:
1560 		/*
1561 		 * resolve was only used for route cloning
1562 		 * here for compat
1563 		 */
1564 		break;
1565 	case RTM_ADD:
1566 		if ((flags & RTF_GATEWAY) && !gateway)
1567 			return (EINVAL);
1568 		if (dst && gateway && (dst->sa_family != gateway->sa_family) &&
1569 		    (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1570 			return (EINVAL);
1571 
1572 		if (info->rti_ifa == NULL) {
1573 			error = rt_getifa_fib(info, fibnum);
1574 			if (error)
1575 				return (error);
1576 		} else
1577 			ifa_ref(info->rti_ifa);
1578 		ifa = info->rti_ifa;
1579 		rt = uma_zalloc(V_rtzone, M_NOWAIT);
1580 		if (rt == NULL) {
1581 			ifa_free(ifa);
1582 			return (ENOBUFS);
1583 		}
1584 		rt->rt_flags = RTF_UP | flags;
1585 		rt->rt_fibnum = fibnum;
1586 		/*
1587 		 * Add the gateway. Possibly re-malloc-ing the storage for it.
1588 		 */
1589 		if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1590 			ifa_free(ifa);
1591 			uma_zfree(V_rtzone, rt);
1592 			return (error);
1593 		}
1594 
1595 		/*
1596 		 * point to the (possibly newly malloc'd) dest address.
1597 		 */
1598 		ndst = (struct sockaddr *)rt_key(rt);
1599 
1600 		/*
1601 		 * make sure it contains the value we want (masked if needed).
1602 		 */
1603 		if (netmask) {
1604 			rt_maskedcopy(dst, ndst, netmask);
1605 		} else
1606 			bcopy(dst, ndst, dst->sa_len);
1607 
1608 		/*
1609 		 * We use the ifa reference returned by rt_getifa_fib().
1610 		 * This moved from below so that rnh->rnh_addaddr() can
1611 		 * examine the ifa and  ifa->ifa_ifp if it so desires.
1612 		 */
1613 		rt->rt_ifa = ifa;
1614 		rt->rt_ifp = ifa->ifa_ifp;
1615 		rt->rt_weight = 1;
1616 
1617 		rt_setmetrics(info, rt);
1618 
1619 		RADIX_NODE_HEAD_LOCK(rnh);
1620 		RT_LOCK(rt);
1621 #ifdef RADIX_MPATH
1622 		/* do not permit exactly the same dst/mask/gw pair */
1623 		if (rn_mpath_capable(rnh) &&
1624 			rt_mpath_conflict(rnh, rt, netmask)) {
1625 			RADIX_NODE_HEAD_UNLOCK(rnh);
1626 
1627 			ifa_free(rt->rt_ifa);
1628 			R_Free(rt_key(rt));
1629 			uma_zfree(V_rtzone, rt);
1630 			return (EEXIST);
1631 		}
1632 #endif
1633 
1634 #ifdef FLOWTABLE
1635 		rt0 = rt_flowtable_check_route(rnh, info);
1636 #endif /* FLOWTABLE */
1637 
1638 		/* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1639 		rn = rnh->rnh_addaddr(ndst, netmask, rnh, rt->rt_nodes);
1640 
1641 		rt_old = NULL;
1642 		if (rn == NULL && (info->rti_flags & RTF_PINNED) != 0) {
1643 
1644 			/*
1645 			 * Force removal and re-try addition
1646 			 * TODO: better multipath&pinned support
1647 			 */
1648 			struct sockaddr *info_dst = info->rti_info[RTAX_DST];
1649 			info->rti_info[RTAX_DST] = ndst;
1650 			/* Do not delete existing PINNED(interface) routes */
1651 			info->rti_flags &= ~RTF_PINNED;
1652 			rt_old = rt_unlinkrte(rnh, info, &error);
1653 			info->rti_flags |= RTF_PINNED;
1654 			info->rti_info[RTAX_DST] = info_dst;
1655 			if (rt_old != NULL)
1656 				rn = rnh->rnh_addaddr(ndst, netmask, rnh,
1657 				    rt->rt_nodes);
1658 		}
1659 		RADIX_NODE_HEAD_UNLOCK(rnh);
1660 
1661 		if (rt_old != NULL)
1662 			RT_UNLOCK(rt_old);
1663 
1664 		/*
1665 		 * If it still failed to go into the tree,
1666 		 * then un-make it (this should be a function)
1667 		 */
1668 		if (rn == NULL) {
1669 			ifa_free(rt->rt_ifa);
1670 			R_Free(rt_key(rt));
1671 			uma_zfree(V_rtzone, rt);
1672 #ifdef FLOWTABLE
1673 			if (rt0 != NULL)
1674 				RTFREE(rt0);
1675 #endif
1676 			return (EEXIST);
1677 		}
1678 #ifdef FLOWTABLE
1679 		else if (rt0 != NULL) {
1680 			flowtable_route_flush(dst->sa_family, rt0);
1681 			RTFREE(rt0);
1682 		}
1683 #endif
1684 
1685 		if (rt_old != NULL) {
1686 			rt_notifydelete(rt_old, info);
1687 			RTFREE(rt_old);
1688 		}
1689 
1690 		/*
1691 		 * If this protocol has something to add to this then
1692 		 * allow it to do that as well.
1693 		 */
1694 		if (ifa->ifa_rtrequest)
1695 			ifa->ifa_rtrequest(req, rt, info);
1696 
1697 		/*
1698 		 * actually return a resultant rtentry and
1699 		 * give the caller a single reference.
1700 		 */
1701 		if (ret_nrt) {
1702 			*ret_nrt = rt;
1703 			RT_ADDREF(rt);
1704 		}
1705 		RT_UNLOCK(rt);
1706 		break;
1707 	case RTM_CHANGE:
1708 		RADIX_NODE_HEAD_LOCK(rnh);
1709 		error = rtrequest1_fib_change(rnh, info, ret_nrt, fibnum);
1710 		RADIX_NODE_HEAD_UNLOCK(rnh);
1711 		break;
1712 	default:
1713 		error = EOPNOTSUPP;
1714 	}
1715 
1716 	return (error);
1717 }
1718 
1719 #undef dst
1720 #undef gateway
1721 #undef netmask
1722 #undef ifaaddr
1723 #undef ifpaddr
1724 #undef flags
1725 
1726 static int
1727 rtrequest1_fib_change(struct radix_node_head *rnh, struct rt_addrinfo *info,
1728     struct rtentry **ret_nrt, u_int fibnum)
1729 {
1730 	struct rtentry *rt = NULL;
1731 	int error = 0;
1732 	int free_ifa = 0;
1733 	int family, mtu;
1734 	struct if_mtuinfo ifmtu;
1735 
1736 	rt = (struct rtentry *)rnh->rnh_lookup(info->rti_info[RTAX_DST],
1737 	    info->rti_info[RTAX_NETMASK], rnh);
1738 
1739 	if (rt == NULL)
1740 		return (ESRCH);
1741 
1742 #ifdef RADIX_MPATH
1743 	/*
1744 	 * If we got multipath routes,
1745 	 * we require users to specify a matching RTAX_GATEWAY.
1746 	 */
1747 	if (rn_mpath_capable(rnh)) {
1748 		rt = rt_mpath_matchgate(rt, info->rti_info[RTAX_GATEWAY]);
1749 		if (rt == NULL)
1750 			return (ESRCH);
1751 	}
1752 #endif
1753 
1754 	RT_LOCK(rt);
1755 
1756 	rt_setmetrics(info, rt);
1757 
1758 	/*
1759 	 * New gateway could require new ifaddr, ifp;
1760 	 * flags may also be different; ifp may be specified
1761 	 * by ll sockaddr when protocol address is ambiguous
1762 	 */
1763 	if (((rt->rt_flags & RTF_GATEWAY) &&
1764 	    info->rti_info[RTAX_GATEWAY] != NULL) ||
1765 	    info->rti_info[RTAX_IFP] != NULL ||
1766 	    (info->rti_info[RTAX_IFA] != NULL &&
1767 	     !sa_equal(info->rti_info[RTAX_IFA], rt->rt_ifa->ifa_addr))) {
1768 
1769 		error = rt_getifa_fib(info, fibnum);
1770 		if (info->rti_ifa != NULL)
1771 			free_ifa = 1;
1772 
1773 		if (error != 0)
1774 			goto bad;
1775 	}
1776 
1777 	/* Check if outgoing interface has changed */
1778 	if (info->rti_ifa != NULL && info->rti_ifa != rt->rt_ifa &&
1779 	    rt->rt_ifa != NULL && rt->rt_ifa->ifa_rtrequest != NULL) {
1780 		rt->rt_ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1781 		ifa_free(rt->rt_ifa);
1782 	}
1783 	/* Update gateway address */
1784 	if (info->rti_info[RTAX_GATEWAY] != NULL) {
1785 		error = rt_setgate(rt, rt_key(rt), info->rti_info[RTAX_GATEWAY]);
1786 		if (error != 0)
1787 			goto bad;
1788 
1789 		rt->rt_flags &= ~RTF_GATEWAY;
1790 		rt->rt_flags |= (RTF_GATEWAY & info->rti_flags);
1791 	}
1792 
1793 	if (info->rti_ifa != NULL && info->rti_ifa != rt->rt_ifa) {
1794 		ifa_ref(info->rti_ifa);
1795 		rt->rt_ifa = info->rti_ifa;
1796 		rt->rt_ifp = info->rti_ifp;
1797 	}
1798 	/* Allow some flags to be toggled on change. */
1799 	rt->rt_flags &= ~RTF_FMASK;
1800 	rt->rt_flags |= info->rti_flags & RTF_FMASK;
1801 
1802 	if (rt->rt_ifa && rt->rt_ifa->ifa_rtrequest != NULL)
1803 	       rt->rt_ifa->ifa_rtrequest(RTM_ADD, rt, info);
1804 
1805 	/* Alter route MTU if necessary */
1806 	if (rt->rt_ifp != NULL) {
1807 		family = info->rti_info[RTAX_DST]->sa_family;
1808 		mtu = if_getmtu_family(rt->rt_ifp, family);
1809 		/* Set default MTU */
1810 		if (rt->rt_mtu == 0)
1811 			rt->rt_mtu = mtu;
1812 		if (rt->rt_mtu != mtu) {
1813 			/* Check if we really need to update */
1814 			ifmtu.ifp = rt->rt_ifp;
1815 			ifmtu.mtu = mtu;
1816 			if_updatemtu_cb(rt->rt_nodes, &ifmtu);
1817 		}
1818 	}
1819 
1820 	if (ret_nrt) {
1821 		*ret_nrt = rt;
1822 		RT_ADDREF(rt);
1823 	}
1824 bad:
1825 	RT_UNLOCK(rt);
1826 	if (free_ifa != 0)
1827 		ifa_free(info->rti_ifa);
1828 	return (error);
1829 }
1830 
1831 static void
1832 rt_setmetrics(const struct rt_addrinfo *info, struct rtentry *rt)
1833 {
1834 
1835 	if (info->rti_mflags & RTV_MTU) {
1836 		if (info->rti_rmx->rmx_mtu != 0) {
1837 
1838 			/*
1839 			 * MTU was explicitly provided by user.
1840 			 * Keep it.
1841 			 */
1842 			rt->rt_flags |= RTF_FIXEDMTU;
1843 		} else {
1844 
1845 			/*
1846 			 * User explicitly sets MTU to 0.
1847 			 * Assume rollback to default.
1848 			 */
1849 			rt->rt_flags &= ~RTF_FIXEDMTU;
1850 		}
1851 		rt->rt_mtu = info->rti_rmx->rmx_mtu;
1852 	}
1853 	if (info->rti_mflags & RTV_WEIGHT)
1854 		rt->rt_weight = info->rti_rmx->rmx_weight;
1855 	/* Kernel -> userland timebase conversion. */
1856 	if (info->rti_mflags & RTV_EXPIRE)
1857 		rt->rt_expire = info->rti_rmx->rmx_expire ?
1858 		    info->rti_rmx->rmx_expire - time_second + time_uptime : 0;
1859 }
1860 
1861 int
1862 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1863 {
1864 	/* XXX dst may be overwritten, can we move this to below */
1865 	int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1866 
1867 	/*
1868 	 * Prepare to store the gateway in rt->rt_gateway.
1869 	 * Both dst and gateway are stored one after the other in the same
1870 	 * malloc'd chunk. If we have room, we can reuse the old buffer,
1871 	 * rt_gateway already points to the right place.
1872 	 * Otherwise, malloc a new block and update the 'dst' address.
1873 	 */
1874 	if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1875 		caddr_t new;
1876 
1877 		R_Malloc(new, caddr_t, dlen + glen);
1878 		if (new == NULL)
1879 			return ENOBUFS;
1880 		/*
1881 		 * XXX note, we copy from *dst and not *rt_key(rt) because
1882 		 * rt_setgate() can be called to initialize a newly
1883 		 * allocated route entry, in which case rt_key(rt) == NULL
1884 		 * (and also rt->rt_gateway == NULL).
1885 		 * Free()/free() handle a NULL argument just fine.
1886 		 */
1887 		bcopy(dst, new, dlen);
1888 		R_Free(rt_key(rt));	/* free old block, if any */
1889 		rt_key(rt) = (struct sockaddr *)new;
1890 		rt->rt_gateway = (struct sockaddr *)(new + dlen);
1891 	}
1892 
1893 	/*
1894 	 * Copy the new gateway value into the memory chunk.
1895 	 */
1896 	bcopy(gate, rt->rt_gateway, glen);
1897 
1898 	return (0);
1899 }
1900 
1901 void
1902 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1903 {
1904 	u_char *cp1 = (u_char *)src;
1905 	u_char *cp2 = (u_char *)dst;
1906 	u_char *cp3 = (u_char *)netmask;
1907 	u_char *cplim = cp2 + *cp3;
1908 	u_char *cplim2 = cp2 + *cp1;
1909 
1910 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1911 	cp3 += 2;
1912 	if (cplim > cplim2)
1913 		cplim = cplim2;
1914 	while (cp2 < cplim)
1915 		*cp2++ = *cp1++ & *cp3++;
1916 	if (cp2 < cplim2)
1917 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1918 }
1919 
1920 /*
1921  * Set up a routing table entry, normally
1922  * for an interface.
1923  */
1924 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1925 static inline  int
1926 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1927 {
1928 	struct sockaddr *dst;
1929 	struct sockaddr *netmask;
1930 	struct rtentry *rt = NULL;
1931 	struct rt_addrinfo info;
1932 	int error = 0;
1933 	int startfib, endfib;
1934 	char tempbuf[_SOCKADDR_TMPSIZE];
1935 	int didwork = 0;
1936 	int a_failure = 0;
1937 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1938 	struct radix_node_head *rnh;
1939 
1940 	if (flags & RTF_HOST) {
1941 		dst = ifa->ifa_dstaddr;
1942 		netmask = NULL;
1943 	} else {
1944 		dst = ifa->ifa_addr;
1945 		netmask = ifa->ifa_netmask;
1946 	}
1947 	if (dst->sa_len == 0)
1948 		return(EINVAL);
1949 	switch (dst->sa_family) {
1950 	case AF_INET6:
1951 	case AF_INET:
1952 		/* We support multiple FIBs. */
1953 		break;
1954 	default:
1955 		fibnum = RT_DEFAULT_FIB;
1956 		break;
1957 	}
1958 	if (fibnum == RT_ALL_FIBS) {
1959 		if (V_rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD)
1960 			startfib = endfib = ifa->ifa_ifp->if_fib;
1961 		else {
1962 			startfib = 0;
1963 			endfib = rt_numfibs - 1;
1964 		}
1965 	} else {
1966 		KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1967 		startfib = fibnum;
1968 		endfib = fibnum;
1969 	}
1970 
1971 	/*
1972 	 * If it's a delete, check that if it exists,
1973 	 * it's on the correct interface or we might scrub
1974 	 * a route to another ifa which would
1975 	 * be confusing at best and possibly worse.
1976 	 */
1977 	if (cmd == RTM_DELETE) {
1978 		/*
1979 		 * It's a delete, so it should already exist..
1980 		 * If it's a net, mask off the host bits
1981 		 * (Assuming we have a mask)
1982 		 * XXX this is kinda inet specific..
1983 		 */
1984 		if (netmask != NULL) {
1985 			rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
1986 			dst = (struct sockaddr *)tempbuf;
1987 		}
1988 	}
1989 	/*
1990 	 * Now go through all the requested tables (fibs) and do the
1991 	 * requested action. Realistically, this will either be fib 0
1992 	 * for protocols that don't do multiple tables or all the
1993 	 * tables for those that do.
1994 	 */
1995 	for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
1996 		if (cmd == RTM_DELETE) {
1997 			struct radix_node *rn;
1998 			/*
1999 			 * Look up an rtentry that is in the routing tree and
2000 			 * contains the correct info.
2001 			 */
2002 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
2003 			if (rnh == NULL)
2004 				/* this table doesn't exist but others might */
2005 				continue;
2006 			RADIX_NODE_HEAD_RLOCK(rnh);
2007 			rn = rnh->rnh_lookup(dst, netmask, rnh);
2008 #ifdef RADIX_MPATH
2009 			if (rn_mpath_capable(rnh)) {
2010 
2011 				if (rn == NULL)
2012 					error = ESRCH;
2013 				else {
2014 					rt = RNTORT(rn);
2015 					/*
2016 					 * for interface route the
2017 					 * rt->rt_gateway is sockaddr_intf
2018 					 * for cloning ARP entries, so
2019 					 * rt_mpath_matchgate must use the
2020 					 * interface address
2021 					 */
2022 					rt = rt_mpath_matchgate(rt,
2023 					    ifa->ifa_addr);
2024 					if (rt == NULL)
2025 						error = ESRCH;
2026 				}
2027 			}
2028 #endif
2029 			error = (rn == NULL ||
2030 			    (rn->rn_flags & RNF_ROOT) ||
2031 			    RNTORT(rn)->rt_ifa != ifa);
2032 			RADIX_NODE_HEAD_RUNLOCK(rnh);
2033 			if (error) {
2034 				/* this is only an error if bad on ALL tables */
2035 				continue;
2036 			}
2037 		}
2038 		/*
2039 		 * Do the actual request
2040 		 */
2041 		bzero((caddr_t)&info, sizeof(info));
2042 		info.rti_ifa = ifa;
2043 		info.rti_flags = flags |
2044 		    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
2045 		info.rti_info[RTAX_DST] = dst;
2046 		/*
2047 		 * doing this for compatibility reasons
2048 		 */
2049 		if (cmd == RTM_ADD)
2050 			info.rti_info[RTAX_GATEWAY] =
2051 			    (struct sockaddr *)&null_sdl;
2052 		else
2053 			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
2054 		info.rti_info[RTAX_NETMASK] = netmask;
2055 		error = rtrequest1_fib(cmd, &info, &rt, fibnum);
2056 
2057 		if (error == 0 && rt != NULL) {
2058 			/*
2059 			 * notify any listening routing agents of the change
2060 			 */
2061 			RT_LOCK(rt);
2062 #ifdef RADIX_MPATH
2063 			/*
2064 			 * in case address alias finds the first address
2065 			 * e.g. ifconfig bge0 192.0.2.246/24
2066 			 * e.g. ifconfig bge0 192.0.2.247/24
2067 			 * the address set in the route is 192.0.2.246
2068 			 * so we need to replace it with 192.0.2.247
2069 			 */
2070 			if (memcmp(rt->rt_ifa->ifa_addr,
2071 			    ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
2072 				ifa_free(rt->rt_ifa);
2073 				ifa_ref(ifa);
2074 				rt->rt_ifp = ifa->ifa_ifp;
2075 				rt->rt_ifa = ifa;
2076 			}
2077 #endif
2078 			/*
2079 			 * doing this for compatibility reasons
2080 			 */
2081 			if (cmd == RTM_ADD) {
2082 			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
2083 				rt->rt_ifp->if_type;
2084 			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
2085 				rt->rt_ifp->if_index;
2086 			}
2087 			RT_ADDREF(rt);
2088 			RT_UNLOCK(rt);
2089 			rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
2090 			RT_LOCK(rt);
2091 			RT_REMREF(rt);
2092 			if (cmd == RTM_DELETE) {
2093 				/*
2094 				 * If we are deleting, and we found an entry,
2095 				 * then it's been removed from the tree..
2096 				 * now throw it away.
2097 				 */
2098 				RTFREE_LOCKED(rt);
2099 			} else {
2100 				if (cmd == RTM_ADD) {
2101 					/*
2102 					 * We just wanted to add it..
2103 					 * we don't actually need a reference.
2104 					 */
2105 					RT_REMREF(rt);
2106 				}
2107 				RT_UNLOCK(rt);
2108 			}
2109 			didwork = 1;
2110 		}
2111 		if (error)
2112 			a_failure = error;
2113 	}
2114 	if (cmd == RTM_DELETE) {
2115 		if (didwork) {
2116 			error = 0;
2117 		} else {
2118 			/* we only give an error if it wasn't in any table */
2119 			error = ((flags & RTF_HOST) ?
2120 			    EHOSTUNREACH : ENETUNREACH);
2121 		}
2122 	} else {
2123 		if (a_failure) {
2124 			/* return an error if any of them failed */
2125 			error = a_failure;
2126 		}
2127 	}
2128 	return (error);
2129 }
2130 
2131 /*
2132  * Set up a routing table entry, normally
2133  * for an interface.
2134  */
2135 int
2136 rtinit(struct ifaddr *ifa, int cmd, int flags)
2137 {
2138 	struct sockaddr *dst;
2139 	int fib = RT_DEFAULT_FIB;
2140 
2141 	if (flags & RTF_HOST) {
2142 		dst = ifa->ifa_dstaddr;
2143 	} else {
2144 		dst = ifa->ifa_addr;
2145 	}
2146 
2147 	switch (dst->sa_family) {
2148 	case AF_INET6:
2149 	case AF_INET:
2150 		/* We do support multiple FIBs. */
2151 		fib = RT_ALL_FIBS;
2152 		break;
2153 	}
2154 	return (rtinit1(ifa, cmd, flags, fib));
2155 }
2156 
2157 /*
2158  * Announce interface address arrival/withdraw
2159  * Returns 0 on success.
2160  */
2161 int
2162 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
2163 {
2164 
2165 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2166 	    ("unexpected cmd %d", cmd));
2167 
2168 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2169 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2170 
2171 #if defined(INET) || defined(INET6)
2172 #ifdef SCTP
2173 	/*
2174 	 * notify the SCTP stack
2175 	 * this will only get called when an address is added/deleted
2176 	 * XXX pass the ifaddr struct instead if ifa->ifa_addr...
2177 	 */
2178 	sctp_addr_change(ifa, cmd);
2179 #endif /* SCTP */
2180 #endif
2181 	return (rtsock_addrmsg(cmd, ifa, fibnum));
2182 }
2183 
2184 /*
2185  * Announce route addition/removal.
2186  * Users of this function MUST validate input data BEFORE calling.
2187  * However we have to be able to handle invalid data:
2188  * if some userland app sends us "invalid" route message (invalid mask,
2189  * no dst, wrong address families, etc...) we need to pass it back
2190  * to app (and any other rtsock consumers) with rtm_errno field set to
2191  * non-zero value.
2192  * Returns 0 on success.
2193  */
2194 int
2195 rt_routemsg(int cmd, struct ifnet *ifp, int error, struct rtentry *rt,
2196     int fibnum)
2197 {
2198 
2199 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2200 	    ("unexpected cmd %d", cmd));
2201 
2202 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2203 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2204 
2205 	KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
2206 
2207 	return (rtsock_routemsg(cmd, ifp, error, rt, fibnum));
2208 }
2209 
2210 void
2211 rt_newaddrmsg(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt)
2212 {
2213 
2214 	rt_newaddrmsg_fib(cmd, ifa, error, rt, RT_ALL_FIBS);
2215 }
2216 
2217 /*
2218  * This is called to generate messages from the routing socket
2219  * indicating a network interface has had addresses associated with it.
2220  */
2221 void
2222 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt,
2223     int fibnum)
2224 {
2225 
2226 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2227 		("unexpected cmd %u", cmd));
2228 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2229 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2230 
2231 	if (cmd == RTM_ADD) {
2232 		rt_addrmsg(cmd, ifa, fibnum);
2233 		if (rt != NULL)
2234 			rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
2235 	} else {
2236 		if (rt != NULL)
2237 			rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
2238 		rt_addrmsg(cmd, ifa, fibnum);
2239 	}
2240 }
2241 
2242