xref: /freebsd/sys/net/route.c (revision 6ab38b8e25f31df8140b99c09160d0207f912ef3)
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_mrouting.h"
41 #include "opt_mpath.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/syslog.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_dl.h>
58 #include <net/route.h>
59 #include <net/vnet.h>
60 #include <net/flowtable.h>
61 
62 #ifdef RADIX_MPATH
63 #include <net/radix_mpath.h>
64 #endif
65 
66 #include <netinet/in.h>
67 #include <netinet/ip_mroute.h>
68 
69 #include <vm/uma.h>
70 
71 #define	RT_MAXFIBS	UINT16_MAX
72 
73 /* Kernel config default option. */
74 #ifdef ROUTETABLES
75 #if ROUTETABLES <= 0
76 #error "ROUTETABLES defined too low"
77 #endif
78 #if ROUTETABLES > RT_MAXFIBS
79 #error "ROUTETABLES defined too big"
80 #endif
81 #define	RT_NUMFIBS	ROUTETABLES
82 #endif /* ROUTETABLES */
83 /* Initialize to default if not otherwise set. */
84 #ifndef	RT_NUMFIBS
85 #define	RT_NUMFIBS	1
86 #endif
87 
88 /* This is read-only.. */
89 u_int rt_numfibs = RT_NUMFIBS;
90 SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RD, &rt_numfibs, 0, "");
91 /* and this can be set too big but will be fixed before it is used */
92 TUNABLE_INT("net.fibs", &rt_numfibs);
93 
94 /*
95  * By default add routes to all fibs for new interfaces.
96  * Once this is set to 0 then only allocate routes on interface
97  * changes for the FIB of the caller when adding a new set of addresses
98  * to an interface.  XXX this is a shotgun aproach to a problem that needs
99  * a more fine grained solution.. that will come.
100  * XXX also has the problems getting the FIB from curthread which will not
101  * always work given the fib can be overridden and prefixes can be added
102  * from the network stack context.
103  */
104 u_int rt_add_addr_allfibs = 1;
105 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RW,
106     &rt_add_addr_allfibs, 0, "");
107 TUNABLE_INT("net.add_addr_allfibs", &rt_add_addr_allfibs);
108 
109 VNET_DEFINE(struct rtstat, rtstat);
110 #define	V_rtstat	VNET(rtstat)
111 
112 VNET_DEFINE(struct radix_node_head *, rt_tables);
113 #define	V_rt_tables	VNET(rt_tables)
114 
115 VNET_DEFINE(int, rttrash);		/* routes not in table but not freed */
116 #define	V_rttrash	VNET(rttrash)
117 
118 
119 /* compare two sockaddr structures */
120 #define	sa_equal(a1, a2) (bcmp((a1), (a2), (a1)->sa_len) == 0)
121 
122 /*
123  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
124  * The operation can be done safely (in this code) because a
125  * 'struct rtentry' starts with two 'struct radix_node''s, the first
126  * one representing leaf nodes in the routing tree, which is
127  * what the code in radix.c passes us as a 'struct radix_node'.
128  *
129  * But because there are a lot of assumptions in this conversion,
130  * do not cast explicitly, but always use the macro below.
131  */
132 #define RNTORT(p)	((struct rtentry *)(p))
133 
134 static VNET_DEFINE(uma_zone_t, rtzone);		/* Routing table UMA zone. */
135 #define	V_rtzone	VNET(rtzone)
136 
137 /*
138  * handler for net.my_fibnum
139  */
140 static int
141 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
142 {
143         int fibnum;
144         int error;
145 
146         fibnum = curthread->td_proc->p_fibnum;
147         error = sysctl_handle_int(oidp, &fibnum, 0, req);
148         return (error);
149 }
150 
151 SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
152             NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
153 
154 static __inline struct radix_node_head **
155 rt_tables_get_rnh_ptr(int table, int fam)
156 {
157 	struct radix_node_head **rnh;
158 
159 	KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
160 	    __func__));
161 	KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
162 	    __func__));
163 
164 	/* rnh is [fib=0][af=0]. */
165 	rnh = (struct radix_node_head **)V_rt_tables;
166 	/* Get the offset to the requested table and fam. */
167 	rnh += table * (AF_MAX+1) + fam;
168 
169 	return (rnh);
170 }
171 
172 struct radix_node_head *
173 rt_tables_get_rnh(int table, int fam)
174 {
175 
176 	return (*rt_tables_get_rnh_ptr(table, fam));
177 }
178 
179 /*
180  * route initialization must occur before ip6_init2(), which happenas at
181  * SI_ORDER_MIDDLE.
182  */
183 static void
184 route_init(void)
185 {
186 
187 	/* whack the tunable ints into  line. */
188 	if (rt_numfibs > RT_MAXFIBS)
189 		rt_numfibs = RT_MAXFIBS;
190 	if (rt_numfibs == 0)
191 		rt_numfibs = 1;
192 }
193 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
194 
195 static void
196 vnet_route_init(const void *unused __unused)
197 {
198 	struct domain *dom;
199 	struct radix_node_head **rnh;
200 	int table;
201 	int fam;
202 
203 	V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
204 	    sizeof(struct radix_node_head *), M_RTABLE, M_WAITOK|M_ZERO);
205 
206 	V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry), NULL, NULL,
207 	    NULL, NULL, UMA_ALIGN_PTR, 0);
208 	for (dom = domains; dom; dom = dom->dom_next) {
209 		if (dom->dom_rtattach == NULL)
210 			continue;
211 
212 		for  (table = 0; table < rt_numfibs; table++) {
213 			fam = dom->dom_family;
214 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
215 				break;
216 
217 			/*
218 			 * XXX MRT rtattach will be also called from
219 			 * vfs_export.c but the offset will be 0 (only for
220 			 * AF_INET and AF_INET6 which don't need it anyhow).
221 			 */
222 			rnh = rt_tables_get_rnh_ptr(table, fam);
223 			if (rnh == NULL)
224 				panic("%s: rnh NULL", __func__);
225 			dom->dom_rtattach((void **)rnh, dom->dom_rtoffset);
226 		}
227 	}
228 }
229 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
230     vnet_route_init, 0);
231 
232 #ifdef VIMAGE
233 static void
234 vnet_route_uninit(const void *unused __unused)
235 {
236 	int table;
237 	int fam;
238 	struct domain *dom;
239 	struct radix_node_head **rnh;
240 
241 	for (dom = domains; dom; dom = dom->dom_next) {
242 		if (dom->dom_rtdetach == NULL)
243 			continue;
244 
245 		for (table = 0; table < rt_numfibs; table++) {
246 			fam = dom->dom_family;
247 
248 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
249 				break;
250 
251 			rnh = rt_tables_get_rnh_ptr(table, fam);
252 			if (rnh == NULL)
253 				panic("%s: rnh NULL", __func__);
254 			dom->dom_rtdetach((void **)rnh, dom->dom_rtoffset);
255 		}
256 	}
257 }
258 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
259     vnet_route_uninit, 0);
260 #endif
261 
262 #ifndef _SYS_SYSPROTO_H_
263 struct setfib_args {
264 	int     fibnum;
265 };
266 #endif
267 int
268 sys_setfib(struct thread *td, struct setfib_args *uap)
269 {
270 	if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
271 		return EINVAL;
272 	td->td_proc->p_fibnum = uap->fibnum;
273 	return (0);
274 }
275 
276 /*
277  * Packet routing routines.
278  */
279 void
280 rtalloc(struct route *ro)
281 {
282 
283 	rtalloc_ign_fib(ro, 0UL, RT_DEFAULT_FIB);
284 }
285 
286 void
287 rtalloc_fib(struct route *ro, u_int fibnum)
288 {
289 	rtalloc_ign_fib(ro, 0UL, fibnum);
290 }
291 
292 void
293 rtalloc_ign(struct route *ro, u_long ignore)
294 {
295 	struct rtentry *rt;
296 
297 	if ((rt = ro->ro_rt) != NULL) {
298 		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
299 			return;
300 		RTFREE(rt);
301 		ro->ro_rt = NULL;
302 	}
303 	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, RT_DEFAULT_FIB);
304 	if (ro->ro_rt)
305 		RT_UNLOCK(ro->ro_rt);
306 }
307 
308 void
309 rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
310 {
311 	struct rtentry *rt;
312 
313 	if ((rt = ro->ro_rt) != NULL) {
314 		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
315 			return;
316 		RTFREE(rt);
317 		ro->ro_rt = NULL;
318 	}
319 	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
320 	if (ro->ro_rt)
321 		RT_UNLOCK(ro->ro_rt);
322 }
323 
324 /*
325  * Look up the route that matches the address given
326  * Or, at least try.. Create a cloned route if needed.
327  *
328  * The returned route, if any, is locked.
329  */
330 struct rtentry *
331 rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
332 {
333 
334 	return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
335 }
336 
337 struct rtentry *
338 rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
339 		    u_int fibnum)
340 {
341 	struct radix_node_head *rnh;
342 	struct radix_node *rn;
343 	struct rtentry *newrt;
344 	struct rt_addrinfo info;
345 	int err = 0, msgtype = RTM_MISS;
346 	int needlock;
347 
348 	KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
349 	switch (dst->sa_family) {
350 	case AF_INET6:
351 	case AF_INET:
352 		/* We support multiple FIBs. */
353 		break;
354 	default:
355 		fibnum = RT_DEFAULT_FIB;
356 		break;
357 	}
358 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
359 	newrt = NULL;
360 	if (rnh == NULL)
361 		goto miss;
362 
363 	/*
364 	 * Look up the address in the table for that Address Family
365 	 */
366 	needlock = !(ignflags & RTF_RNH_LOCKED);
367 	if (needlock)
368 		RADIX_NODE_HEAD_RLOCK(rnh);
369 #ifdef INVARIANTS
370 	else
371 		RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
372 #endif
373 	rn = rnh->rnh_matchaddr(dst, rnh);
374 	if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
375 		newrt = RNTORT(rn);
376 		RT_LOCK(newrt);
377 		RT_ADDREF(newrt);
378 		if (needlock)
379 			RADIX_NODE_HEAD_RUNLOCK(rnh);
380 		goto done;
381 
382 	} else if (needlock)
383 		RADIX_NODE_HEAD_RUNLOCK(rnh);
384 
385 	/*
386 	 * Either we hit the root or couldn't find any match,
387 	 * Which basically means
388 	 * "caint get there frm here"
389 	 */
390 miss:
391 	V_rtstat.rts_unreach++;
392 
393 	if (report) {
394 		/*
395 		 * If required, report the failure to the supervising
396 		 * Authorities.
397 		 * For a delete, this is not an error. (report == 0)
398 		 */
399 		bzero(&info, sizeof(info));
400 		info.rti_info[RTAX_DST] = dst;
401 		rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
402 	}
403 done:
404 	if (newrt)
405 		RT_LOCK_ASSERT(newrt);
406 	return (newrt);
407 }
408 
409 /*
410  * Remove a reference count from an rtentry.
411  * If the count gets low enough, take it out of the routing table
412  */
413 void
414 rtfree(struct rtentry *rt)
415 {
416 	struct radix_node_head *rnh;
417 
418 	KASSERT(rt != NULL,("%s: NULL rt", __func__));
419 	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
420 	KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
421 
422 	RT_LOCK_ASSERT(rt);
423 
424 	/*
425 	 * The callers should use RTFREE_LOCKED() or RTFREE(), so
426 	 * we should come here exactly with the last reference.
427 	 */
428 	RT_REMREF(rt);
429 	if (rt->rt_refcnt > 0) {
430 		log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
431 		goto done;
432 	}
433 
434 	/*
435 	 * On last reference give the "close method" a chance
436 	 * to cleanup private state.  This also permits (for
437 	 * IPv4 and IPv6) a chance to decide if the routing table
438 	 * entry should be purged immediately or at a later time.
439 	 * When an immediate purge is to happen the close routine
440 	 * typically calls rtexpunge which clears the RTF_UP flag
441 	 * on the entry so that the code below reclaims the storage.
442 	 */
443 	if (rt->rt_refcnt == 0 && rnh->rnh_close)
444 		rnh->rnh_close((struct radix_node *)rt, rnh);
445 
446 	/*
447 	 * If we are no longer "up" (and ref == 0)
448 	 * then we can free the resources associated
449 	 * with the route.
450 	 */
451 	if ((rt->rt_flags & RTF_UP) == 0) {
452 		if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
453 			panic("rtfree 2");
454 		/*
455 		 * the rtentry must have been removed from the routing table
456 		 * so it is represented in rttrash.. remove that now.
457 		 */
458 		V_rttrash--;
459 #ifdef	DIAGNOSTIC
460 		if (rt->rt_refcnt < 0) {
461 			printf("rtfree: %p not freed (neg refs)\n", rt);
462 			goto done;
463 		}
464 #endif
465 		/*
466 		 * release references on items we hold them on..
467 		 * e.g other routes and ifaddrs.
468 		 */
469 		if (rt->rt_ifa)
470 			ifa_free(rt->rt_ifa);
471 		/*
472 		 * The key is separatly alloc'd so free it (see rt_setgate()).
473 		 * This also frees the gateway, as they are always malloc'd
474 		 * together.
475 		 */
476 		Free(rt_key(rt));
477 
478 		/*
479 		 * and the rtentry itself of course
480 		 */
481 		RT_LOCK_DESTROY(rt);
482 		uma_zfree(V_rtzone, rt);
483 		return;
484 	}
485 done:
486 	RT_UNLOCK(rt);
487 }
488 
489 
490 /*
491  * Force a routing table entry to the specified
492  * destination to go through the given gateway.
493  * Normally called as a result of a routing redirect
494  * message from the network layer.
495  */
496 void
497 rtredirect(struct sockaddr *dst,
498 	struct sockaddr *gateway,
499 	struct sockaddr *netmask,
500 	int flags,
501 	struct sockaddr *src)
502 {
503 
504 	rtredirect_fib(dst, gateway, netmask, flags, src, RT_DEFAULT_FIB);
505 }
506 
507 void
508 rtredirect_fib(struct sockaddr *dst,
509 	struct sockaddr *gateway,
510 	struct sockaddr *netmask,
511 	int flags,
512 	struct sockaddr *src,
513 	u_int fibnum)
514 {
515 	struct rtentry *rt, *rt0 = NULL;
516 	int error = 0;
517 	short *stat = NULL;
518 	struct rt_addrinfo info;
519 	struct ifaddr *ifa;
520 	struct radix_node_head *rnh;
521 
522 	ifa = NULL;
523 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
524 	if (rnh == NULL) {
525 		error = EAFNOSUPPORT;
526 		goto out;
527 	}
528 
529 	/* verify the gateway is directly reachable */
530 	if ((ifa = ifa_ifwithnet(gateway, 0)) == NULL) {
531 		error = ENETUNREACH;
532 		goto out;
533 	}
534 	rt = rtalloc1_fib(dst, 0, 0UL, fibnum);	/* NB: rt is locked */
535 	/*
536 	 * If the redirect isn't from our current router for this dst,
537 	 * it's either old or wrong.  If it redirects us to ourselves,
538 	 * we have a routing loop, perhaps as a result of an interface
539 	 * going down recently.
540 	 */
541 	if (!(flags & RTF_DONE) && rt &&
542 	     (!sa_equal(src, rt->rt_gateway) || rt->rt_ifa != ifa))
543 		error = EINVAL;
544 	else if (ifa_ifwithaddr_check(gateway))
545 		error = EHOSTUNREACH;
546 	if (error)
547 		goto done;
548 	/*
549 	 * Create a new entry if we just got back a wildcard entry
550 	 * or the lookup failed.  This is necessary for hosts
551 	 * which use routing redirects generated by smart gateways
552 	 * to dynamically build the routing tables.
553 	 */
554 	if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
555 		goto create;
556 	/*
557 	 * Don't listen to the redirect if it's
558 	 * for a route to an interface.
559 	 */
560 	if (rt->rt_flags & RTF_GATEWAY) {
561 		if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
562 			/*
563 			 * Changing from route to net => route to host.
564 			 * Create new route, rather than smashing route to net.
565 			 */
566 		create:
567 			rt0 = rt;
568 			rt = NULL;
569 
570 			flags |=  RTF_GATEWAY | RTF_DYNAMIC;
571 			bzero((caddr_t)&info, sizeof(info));
572 			info.rti_info[RTAX_DST] = dst;
573 			info.rti_info[RTAX_GATEWAY] = gateway;
574 			info.rti_info[RTAX_NETMASK] = netmask;
575 			info.rti_ifa = ifa;
576 			info.rti_flags = flags;
577 			if (rt0 != NULL)
578 				RT_UNLOCK(rt0);	/* drop lock to avoid LOR with RNH */
579 			error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
580 			if (rt != NULL) {
581 				RT_LOCK(rt);
582 				if (rt0 != NULL)
583 					EVENTHANDLER_INVOKE(route_redirect_event, rt0, rt, dst);
584 				flags = rt->rt_flags;
585 			}
586 			if (rt0 != NULL)
587 				RTFREE(rt0);
588 
589 			stat = &V_rtstat.rts_dynamic;
590 		} else {
591 			struct rtentry *gwrt;
592 
593 			/*
594 			 * Smash the current notion of the gateway to
595 			 * this destination.  Should check about netmask!!!
596 			 */
597 			rt->rt_flags |= RTF_MODIFIED;
598 			flags |= RTF_MODIFIED;
599 			stat = &V_rtstat.rts_newgateway;
600 			/*
601 			 * add the key and gateway (in one malloc'd chunk).
602 			 */
603 			RT_UNLOCK(rt);
604 			RADIX_NODE_HEAD_LOCK(rnh);
605 			RT_LOCK(rt);
606 			rt_setgate(rt, rt_key(rt), gateway);
607 			gwrt = rtalloc1(gateway, 1, RTF_RNH_LOCKED);
608 			RADIX_NODE_HEAD_UNLOCK(rnh);
609 			EVENTHANDLER_INVOKE(route_redirect_event, rt, gwrt, dst);
610 			RTFREE_LOCKED(gwrt);
611 		}
612 	} else
613 		error = EHOSTUNREACH;
614 done:
615 	if (rt)
616 		RTFREE_LOCKED(rt);
617 out:
618 	if (error)
619 		V_rtstat.rts_badredirect++;
620 	else if (stat != NULL)
621 		(*stat)++;
622 	bzero((caddr_t)&info, sizeof(info));
623 	info.rti_info[RTAX_DST] = dst;
624 	info.rti_info[RTAX_GATEWAY] = gateway;
625 	info.rti_info[RTAX_NETMASK] = netmask;
626 	info.rti_info[RTAX_AUTHOR] = src;
627 	rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
628 	if (ifa != NULL)
629 		ifa_free(ifa);
630 }
631 
632 int
633 rtioctl(u_long req, caddr_t data)
634 {
635 
636 	return (rtioctl_fib(req, data, RT_DEFAULT_FIB));
637 }
638 
639 /*
640  * Routing table ioctl interface.
641  */
642 int
643 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
644 {
645 
646 	/*
647 	 * If more ioctl commands are added here, make sure the proper
648 	 * super-user checks are being performed because it is possible for
649 	 * prison-root to make it this far if raw sockets have been enabled
650 	 * in jails.
651 	 */
652 #ifdef INET
653 	/* Multicast goop, grrr... */
654 	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
655 #else /* INET */
656 	return ENXIO;
657 #endif /* INET */
658 }
659 
660 /*
661  * For both ifa_ifwithroute() routines, 'ifa' is returned referenced.
662  */
663 struct ifaddr *
664 ifa_ifwithroute(int flags, struct sockaddr *dst, struct sockaddr *gateway)
665 {
666 
667 	return (ifa_ifwithroute_fib(flags, dst, gateway, RT_DEFAULT_FIB));
668 }
669 
670 struct ifaddr *
671 ifa_ifwithroute_fib(int flags, struct sockaddr *dst, struct sockaddr *gateway,
672 				u_int fibnum)
673 {
674 	register struct ifaddr *ifa;
675 	int not_found = 0;
676 
677 	if ((flags & RTF_GATEWAY) == 0) {
678 		/*
679 		 * If we are adding a route to an interface,
680 		 * and the interface is a pt to pt link
681 		 * we should search for the destination
682 		 * as our clue to the interface.  Otherwise
683 		 * we can use the local address.
684 		 */
685 		ifa = NULL;
686 		if (flags & RTF_HOST)
687 			ifa = ifa_ifwithdstaddr(dst);
688 		if (ifa == NULL)
689 			ifa = ifa_ifwithaddr(gateway);
690 	} else {
691 		/*
692 		 * If we are adding a route to a remote net
693 		 * or host, the gateway may still be on the
694 		 * other end of a pt to pt link.
695 		 */
696 		ifa = ifa_ifwithdstaddr(gateway);
697 	}
698 	if (ifa == NULL)
699 		ifa = ifa_ifwithnet(gateway, 0);
700 	if (ifa == NULL) {
701 		struct rtentry *rt = rtalloc1_fib(gateway, 0, RTF_RNH_LOCKED, fibnum);
702 		if (rt == NULL)
703 			return (NULL);
704 		/*
705 		 * dismiss a gateway that is reachable only
706 		 * through the default router
707 		 */
708 		switch (gateway->sa_family) {
709 		case AF_INET:
710 			if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
711 				not_found = 1;
712 			break;
713 		case AF_INET6:
714 			if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
715 				not_found = 1;
716 			break;
717 		default:
718 			break;
719 		}
720 		if (!not_found && rt->rt_ifa != NULL) {
721 			ifa = rt->rt_ifa;
722 			ifa_ref(ifa);
723 		}
724 		RT_REMREF(rt);
725 		RT_UNLOCK(rt);
726 		if (not_found || ifa == NULL)
727 			return (NULL);
728 	}
729 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
730 		struct ifaddr *oifa = ifa;
731 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
732 		if (ifa == NULL)
733 			ifa = oifa;
734 		else
735 			ifa_free(oifa);
736 	}
737 	return (ifa);
738 }
739 
740 /*
741  * Do appropriate manipulations of a routing tree given
742  * all the bits of info needed
743  */
744 int
745 rtrequest(int req,
746 	struct sockaddr *dst,
747 	struct sockaddr *gateway,
748 	struct sockaddr *netmask,
749 	int flags,
750 	struct rtentry **ret_nrt)
751 {
752 
753 	return (rtrequest_fib(req, dst, gateway, netmask, flags, ret_nrt,
754 	    RT_DEFAULT_FIB));
755 }
756 
757 int
758 rtrequest_fib(int req,
759 	struct sockaddr *dst,
760 	struct sockaddr *gateway,
761 	struct sockaddr *netmask,
762 	int flags,
763 	struct rtentry **ret_nrt,
764 	u_int fibnum)
765 {
766 	struct rt_addrinfo info;
767 
768 	if (dst->sa_len == 0)
769 		return(EINVAL);
770 
771 	bzero((caddr_t)&info, sizeof(info));
772 	info.rti_flags = flags;
773 	info.rti_info[RTAX_DST] = dst;
774 	info.rti_info[RTAX_GATEWAY] = gateway;
775 	info.rti_info[RTAX_NETMASK] = netmask;
776 	return rtrequest1_fib(req, &info, ret_nrt, fibnum);
777 }
778 
779 /*
780  * These (questionable) definitions of apparent local variables apply
781  * to the next two functions.  XXXXXX!!!
782  */
783 #define	dst	info->rti_info[RTAX_DST]
784 #define	gateway	info->rti_info[RTAX_GATEWAY]
785 #define	netmask	info->rti_info[RTAX_NETMASK]
786 #define	ifaaddr	info->rti_info[RTAX_IFA]
787 #define	ifpaddr	info->rti_info[RTAX_IFP]
788 #define	flags	info->rti_flags
789 
790 int
791 rt_getifa(struct rt_addrinfo *info)
792 {
793 
794 	return (rt_getifa_fib(info, RT_DEFAULT_FIB));
795 }
796 
797 /*
798  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
799  * it will be referenced so the caller must free it.
800  */
801 int
802 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
803 {
804 	struct ifaddr *ifa;
805 	int error = 0;
806 
807 	/*
808 	 * ifp may be specified by sockaddr_dl
809 	 * when protocol address is ambiguous.
810 	 */
811 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
812 	    ifpaddr->sa_family == AF_LINK &&
813 	    (ifa = ifa_ifwithnet(ifpaddr, 0)) != NULL) {
814 		info->rti_ifp = ifa->ifa_ifp;
815 		ifa_free(ifa);
816 	}
817 	if (info->rti_ifa == NULL && ifaaddr != NULL)
818 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
819 	if (info->rti_ifa == NULL) {
820 		struct sockaddr *sa;
821 
822 		sa = ifaaddr != NULL ? ifaaddr :
823 		    (gateway != NULL ? gateway : dst);
824 		if (sa != NULL && info->rti_ifp != NULL)
825 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
826 		else if (dst != NULL && gateway != NULL)
827 			info->rti_ifa = ifa_ifwithroute_fib(flags, dst, gateway,
828 							fibnum);
829 		else if (sa != NULL)
830 			info->rti_ifa = ifa_ifwithroute_fib(flags, sa, sa,
831 							fibnum);
832 	}
833 	if ((ifa = info->rti_ifa) != NULL) {
834 		if (info->rti_ifp == NULL)
835 			info->rti_ifp = ifa->ifa_ifp;
836 	} else
837 		error = ENETUNREACH;
838 	return (error);
839 }
840 
841 /*
842  * Expunges references to a route that's about to be reclaimed.
843  * The route must be locked.
844  */
845 int
846 rtexpunge(struct rtentry *rt)
847 {
848 #if !defined(RADIX_MPATH)
849 	struct radix_node *rn;
850 #else
851 	struct rt_addrinfo info;
852 	int fib;
853 	struct rtentry *rt0;
854 #endif
855 	struct radix_node_head *rnh;
856 	struct ifaddr *ifa;
857 	int error = 0;
858 
859 	/*
860 	 * Find the correct routing tree to use for this Address Family
861 	 */
862 	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
863 	RT_LOCK_ASSERT(rt);
864 	if (rnh == NULL)
865 		return (EAFNOSUPPORT);
866 	RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
867 
868 #ifdef RADIX_MPATH
869 	fib = rt->rt_fibnum;
870 	bzero(&info, sizeof(info));
871 	info.rti_ifp = rt->rt_ifp;
872 	info.rti_flags = RTF_RNH_LOCKED;
873 	info.rti_info[RTAX_DST] = rt_key(rt);
874 	info.rti_info[RTAX_GATEWAY] = rt->rt_ifa->ifa_addr;
875 
876 	RT_UNLOCK(rt);
877 	error = rtrequest1_fib(RTM_DELETE, &info, &rt0, fib);
878 
879 	if (error == 0 && rt0 != NULL) {
880 		rt = rt0;
881 		RT_LOCK(rt);
882 	} else if (error != 0) {
883 		RT_LOCK(rt);
884 		return (error);
885 	}
886 #else
887 	/*
888 	 * Remove the item from the tree; it should be there,
889 	 * but when callers invoke us blindly it may not (sigh).
890 	 */
891 	rn = rnh->rnh_deladdr(rt_key(rt), rt_mask(rt), rnh);
892 	if (rn == NULL) {
893 		error = ESRCH;
894 		goto bad;
895 	}
896 	KASSERT((rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)) == 0,
897 		("unexpected flags 0x%x", rn->rn_flags));
898 	KASSERT(rt == RNTORT(rn),
899 		("lookup mismatch, rt %p rn %p", rt, rn));
900 #endif /* RADIX_MPATH */
901 
902 	rt->rt_flags &= ~RTF_UP;
903 
904 	/*
905 	 * Give the protocol a chance to keep things in sync.
906 	 */
907 	if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest) {
908 		struct rt_addrinfo info;
909 
910 		bzero((caddr_t)&info, sizeof(info));
911 		info.rti_flags = rt->rt_flags;
912 		info.rti_info[RTAX_DST] = rt_key(rt);
913 		info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
914 		info.rti_info[RTAX_NETMASK] = rt_mask(rt);
915 		ifa->ifa_rtrequest(RTM_DELETE, rt, &info);
916 	}
917 
918 	/*
919 	 * one more rtentry floating around that is not
920 	 * linked to the routing table.
921 	 */
922 	V_rttrash++;
923 #if !defined(RADIX_MPATH)
924 bad:
925 #endif
926 	return (error);
927 }
928 
929 #ifdef RADIX_MPATH
930 static int
931 rn_mpath_update(int req, struct rt_addrinfo *info,
932     struct radix_node_head *rnh, struct rtentry **ret_nrt)
933 {
934 	/*
935 	 * if we got multipath routes, we require users to specify
936 	 * a matching RTAX_GATEWAY.
937 	 */
938 	struct rtentry *rt, *rto = NULL;
939 	register struct radix_node *rn;
940 	int error = 0;
941 
942 	rn = rnh->rnh_matchaddr(dst, rnh);
943 	if (rn == NULL)
944 		return (ESRCH);
945 	rto = rt = RNTORT(rn);
946 	rt = rt_mpath_matchgate(rt, gateway);
947 	if (rt == NULL)
948 		return (ESRCH);
949 	/*
950 	 * this is the first entry in the chain
951 	 */
952 	if (rto == rt) {
953 		rn = rn_mpath_next((struct radix_node *)rt);
954 		/*
955 		 * there is another entry, now it's active
956 		 */
957 		if (rn) {
958 			rto = RNTORT(rn);
959 			RT_LOCK(rto);
960 			rto->rt_flags |= RTF_UP;
961 			RT_UNLOCK(rto);
962 		} else if (rt->rt_flags & RTF_GATEWAY) {
963 			/*
964 			 * For gateway routes, we need to
965 			 * make sure that we we are deleting
966 			 * the correct gateway.
967 			 * rt_mpath_matchgate() does not
968 			 * check the case when there is only
969 			 * one route in the chain.
970 			 */
971 			if (gateway &&
972 			    (rt->rt_gateway->sa_len != gateway->sa_len ||
973 				memcmp(rt->rt_gateway, gateway, gateway->sa_len)))
974 				error = ESRCH;
975 			else {
976 				/*
977 				 * remove from tree before returning it
978 				 * to the caller
979 				 */
980 				rn = rnh->rnh_deladdr(dst, netmask, rnh);
981 				KASSERT(rt == RNTORT(rn), ("radix node disappeared"));
982 				goto gwdelete;
983 			}
984 
985 		}
986 		/*
987 		 * use the normal delete code to remove
988 		 * the first entry
989 		 */
990 		if (req != RTM_DELETE)
991 			goto nondelete;
992 
993 		error = ENOENT;
994 		goto done;
995 	}
996 
997 	/*
998 	 * if the entry is 2nd and on up
999 	 */
1000 	if ((req == RTM_DELETE) && !rt_mpath_deldup(rto, rt))
1001 		panic ("rtrequest1: rt_mpath_deldup");
1002 gwdelete:
1003 	RT_LOCK(rt);
1004 	RT_ADDREF(rt);
1005 	if (req == RTM_DELETE) {
1006 		rt->rt_flags &= ~RTF_UP;
1007 		/*
1008 		 * One more rtentry floating around that is not
1009 		 * linked to the routing table. rttrash will be decremented
1010 		 * when RTFREE(rt) is eventually called.
1011 		 */
1012 		V_rttrash++;
1013 	}
1014 
1015 nondelete:
1016 	if (req != RTM_DELETE)
1017 		panic("unrecognized request %d", req);
1018 
1019 
1020 	/*
1021 	 * If the caller wants it, then it can have it,
1022 	 * but it's up to it to free the rtentry as we won't be
1023 	 * doing it.
1024 	 */
1025 	if (ret_nrt) {
1026 		*ret_nrt = rt;
1027 		RT_UNLOCK(rt);
1028 	} else
1029 		RTFREE_LOCKED(rt);
1030 done:
1031 	return (error);
1032 }
1033 #endif
1034 
1035 int
1036 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1037 				u_int fibnum)
1038 {
1039 	int error = 0, needlock = 0;
1040 	register struct rtentry *rt;
1041 #ifdef FLOWTABLE
1042 	register struct rtentry *rt0;
1043 #endif
1044 	register struct radix_node *rn;
1045 	register struct radix_node_head *rnh;
1046 	struct ifaddr *ifa;
1047 	struct sockaddr *ndst;
1048 	struct sockaddr_storage mdst;
1049 #define senderr(x) { error = x ; goto bad; }
1050 
1051 	KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1052 	switch (dst->sa_family) {
1053 	case AF_INET6:
1054 	case AF_INET:
1055 		/* We support multiple FIBs. */
1056 		break;
1057 	default:
1058 		fibnum = RT_DEFAULT_FIB;
1059 		break;
1060 	}
1061 
1062 	/*
1063 	 * Find the correct routing tree to use for this Address Family
1064 	 */
1065 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1066 	if (rnh == NULL)
1067 		return (EAFNOSUPPORT);
1068 	needlock = ((flags & RTF_RNH_LOCKED) == 0);
1069 	flags &= ~RTF_RNH_LOCKED;
1070 	if (needlock)
1071 		RADIX_NODE_HEAD_LOCK(rnh);
1072 	else
1073 		RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1074 	/*
1075 	 * If we are adding a host route then we don't want to put
1076 	 * a netmask in the tree, nor do we want to clone it.
1077 	 */
1078 	if (flags & RTF_HOST)
1079 		netmask = NULL;
1080 
1081 	switch (req) {
1082 	case RTM_DELETE:
1083 		if (netmask) {
1084 			rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1085 			dst = (struct sockaddr *)&mdst;
1086 		}
1087 #ifdef RADIX_MPATH
1088 		if (rn_mpath_capable(rnh)) {
1089 			error = rn_mpath_update(req, info, rnh, ret_nrt);
1090 			/*
1091 			 * "bad" holds true for the success case
1092 			 * as well
1093 			 */
1094 			if (error != ENOENT)
1095 				goto bad;
1096 			error = 0;
1097 		}
1098 #endif
1099 		if ((flags & RTF_PINNED) == 0) {
1100 			/* Check if target route can be deleted */
1101 			rt = (struct rtentry *)rnh->rnh_lookup(dst,
1102 			    netmask, rnh);
1103 			if ((rt != NULL) && (rt->rt_flags & RTF_PINNED))
1104 				senderr(EADDRINUSE);
1105 		}
1106 
1107 		/*
1108 		 * Remove the item from the tree and return it.
1109 		 * Complain if it is not there and do no more processing.
1110 		 */
1111 		rn = rnh->rnh_deladdr(dst, netmask, rnh);
1112 		if (rn == NULL)
1113 			senderr(ESRCH);
1114 		if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1115 			panic ("rtrequest delete");
1116 		rt = RNTORT(rn);
1117 		RT_LOCK(rt);
1118 		RT_ADDREF(rt);
1119 		rt->rt_flags &= ~RTF_UP;
1120 
1121 		/*
1122 		 * give the protocol a chance to keep things in sync.
1123 		 */
1124 		if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
1125 			ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1126 
1127 		/*
1128 		 * One more rtentry floating around that is not
1129 		 * linked to the routing table. rttrash will be decremented
1130 		 * when RTFREE(rt) is eventually called.
1131 		 */
1132 		V_rttrash++;
1133 
1134 		/*
1135 		 * If the caller wants it, then it can have it,
1136 		 * but it's up to it to free the rtentry as we won't be
1137 		 * doing it.
1138 		 */
1139 		if (ret_nrt) {
1140 			*ret_nrt = rt;
1141 			RT_UNLOCK(rt);
1142 		} else
1143 			RTFREE_LOCKED(rt);
1144 		break;
1145 	case RTM_RESOLVE:
1146 		/*
1147 		 * resolve was only used for route cloning
1148 		 * here for compat
1149 		 */
1150 		break;
1151 	case RTM_ADD:
1152 		if ((flags & RTF_GATEWAY) && !gateway)
1153 			senderr(EINVAL);
1154 		if (dst && gateway && (dst->sa_family != gateway->sa_family) &&
1155 		    (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1156 			senderr(EINVAL);
1157 
1158 		if (info->rti_ifa == NULL) {
1159 			error = rt_getifa_fib(info, fibnum);
1160 			if (error)
1161 				senderr(error);
1162 		} else
1163 			ifa_ref(info->rti_ifa);
1164 		ifa = info->rti_ifa;
1165 		rt = uma_zalloc(V_rtzone, M_NOWAIT | M_ZERO);
1166 		if (rt == NULL) {
1167 			ifa_free(ifa);
1168 			senderr(ENOBUFS);
1169 		}
1170 		RT_LOCK_INIT(rt);
1171 		rt->rt_flags = RTF_UP | flags;
1172 		rt->rt_fibnum = fibnum;
1173 		/*
1174 		 * Add the gateway. Possibly re-malloc-ing the storage for it.
1175 		 */
1176 		RT_LOCK(rt);
1177 		if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1178 			RT_LOCK_DESTROY(rt);
1179 			ifa_free(ifa);
1180 			uma_zfree(V_rtzone, rt);
1181 			senderr(error);
1182 		}
1183 
1184 		/*
1185 		 * point to the (possibly newly malloc'd) dest address.
1186 		 */
1187 		ndst = (struct sockaddr *)rt_key(rt);
1188 
1189 		/*
1190 		 * make sure it contains the value we want (masked if needed).
1191 		 */
1192 		if (netmask) {
1193 			rt_maskedcopy(dst, ndst, netmask);
1194 		} else
1195 			bcopy(dst, ndst, dst->sa_len);
1196 
1197 		/*
1198 		 * We use the ifa reference returned by rt_getifa_fib().
1199 		 * This moved from below so that rnh->rnh_addaddr() can
1200 		 * examine the ifa and  ifa->ifa_ifp if it so desires.
1201 		 */
1202 		rt->rt_ifa = ifa;
1203 		rt->rt_ifp = ifa->ifa_ifp;
1204 		rt->rt_rmx.rmx_weight = 1;
1205 
1206 #ifdef RADIX_MPATH
1207 		/* do not permit exactly the same dst/mask/gw pair */
1208 		if (rn_mpath_capable(rnh) &&
1209 			rt_mpath_conflict(rnh, rt, netmask)) {
1210 			ifa_free(rt->rt_ifa);
1211 			Free(rt_key(rt));
1212 			RT_LOCK_DESTROY(rt);
1213 			uma_zfree(V_rtzone, rt);
1214 			senderr(EEXIST);
1215 		}
1216 #endif
1217 
1218 #ifdef FLOWTABLE
1219 		rt0 = NULL;
1220 		/* "flow-table" only supports IPv6 and IPv4 at the moment. */
1221 		switch (dst->sa_family) {
1222 #ifdef INET6
1223 		case AF_INET6:
1224 #endif
1225 #ifdef INET
1226 		case AF_INET:
1227 #endif
1228 #if defined(INET6) || defined(INET)
1229 			rn = rnh->rnh_matchaddr(dst, rnh);
1230 			if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
1231 				struct sockaddr *mask;
1232 				u_char *m, *n;
1233 				int len;
1234 
1235 				/*
1236 				 * compare mask to see if the new route is
1237 				 * more specific than the existing one
1238 				 */
1239 				rt0 = RNTORT(rn);
1240 				RT_LOCK(rt0);
1241 				RT_ADDREF(rt0);
1242 				RT_UNLOCK(rt0);
1243 				/*
1244 				 * A host route is already present, so
1245 				 * leave the flow-table entries as is.
1246 				 */
1247 				if (rt0->rt_flags & RTF_HOST) {
1248 					RTFREE(rt0);
1249 					rt0 = NULL;
1250 				} else if (!(flags & RTF_HOST) && netmask) {
1251 					mask = rt_mask(rt0);
1252 					len = mask->sa_len;
1253 					m = (u_char *)mask;
1254 					n = (u_char *)netmask;
1255 					while (len-- > 0) {
1256 						if (*n != *m)
1257 							break;
1258 						n++;
1259 						m++;
1260 					}
1261 					if (len == 0 || (*n < *m)) {
1262 						RTFREE(rt0);
1263 						rt0 = NULL;
1264 					}
1265 				}
1266 			}
1267 #endif/* INET6 || INET */
1268 		}
1269 #endif /* FLOWTABLE */
1270 
1271 		/* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1272 		rn = rnh->rnh_addaddr(ndst, netmask, rnh, rt->rt_nodes);
1273 		/*
1274 		 * If it still failed to go into the tree,
1275 		 * then un-make it (this should be a function)
1276 		 */
1277 		if (rn == NULL) {
1278 			ifa_free(rt->rt_ifa);
1279 			Free(rt_key(rt));
1280 			RT_LOCK_DESTROY(rt);
1281 			uma_zfree(V_rtzone, rt);
1282 #ifdef FLOWTABLE
1283 			if (rt0 != NULL)
1284 				RTFREE(rt0);
1285 #endif
1286 			senderr(EEXIST);
1287 		}
1288 #ifdef FLOWTABLE
1289 		else if (rt0 != NULL) {
1290 			switch (dst->sa_family) {
1291 #ifdef INET6
1292 			case AF_INET6:
1293 				flowtable_route_flush(V_ip6_ft, rt0);
1294 				break;
1295 #endif
1296 #ifdef INET
1297 			case AF_INET:
1298 				flowtable_route_flush(V_ip_ft, rt0);
1299 				break;
1300 #endif
1301 			}
1302 			RTFREE(rt0);
1303 		}
1304 #endif
1305 
1306 		/*
1307 		 * If this protocol has something to add to this then
1308 		 * allow it to do that as well.
1309 		 */
1310 		if (ifa->ifa_rtrequest)
1311 			ifa->ifa_rtrequest(req, rt, info);
1312 
1313 		/*
1314 		 * actually return a resultant rtentry and
1315 		 * give the caller a single reference.
1316 		 */
1317 		if (ret_nrt) {
1318 			*ret_nrt = rt;
1319 			RT_ADDREF(rt);
1320 		}
1321 		RT_UNLOCK(rt);
1322 		break;
1323 	default:
1324 		error = EOPNOTSUPP;
1325 	}
1326 bad:
1327 	if (needlock)
1328 		RADIX_NODE_HEAD_UNLOCK(rnh);
1329 	return (error);
1330 #undef senderr
1331 }
1332 
1333 #undef dst
1334 #undef gateway
1335 #undef netmask
1336 #undef ifaaddr
1337 #undef ifpaddr
1338 #undef flags
1339 
1340 int
1341 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1342 {
1343 	/* XXX dst may be overwritten, can we move this to below */
1344 	int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1345 #ifdef INVARIANTS
1346 	struct radix_node_head *rnh;
1347 
1348 	rnh = rt_tables_get_rnh(rt->rt_fibnum, dst->sa_family);
1349 #endif
1350 
1351 	RT_LOCK_ASSERT(rt);
1352 	RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1353 
1354 	/*
1355 	 * Prepare to store the gateway in rt->rt_gateway.
1356 	 * Both dst and gateway are stored one after the other in the same
1357 	 * malloc'd chunk. If we have room, we can reuse the old buffer,
1358 	 * rt_gateway already points to the right place.
1359 	 * Otherwise, malloc a new block and update the 'dst' address.
1360 	 */
1361 	if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1362 		caddr_t new;
1363 
1364 		R_Malloc(new, caddr_t, dlen + glen);
1365 		if (new == NULL)
1366 			return ENOBUFS;
1367 		/*
1368 		 * XXX note, we copy from *dst and not *rt_key(rt) because
1369 		 * rt_setgate() can be called to initialize a newly
1370 		 * allocated route entry, in which case rt_key(rt) == NULL
1371 		 * (and also rt->rt_gateway == NULL).
1372 		 * Free()/free() handle a NULL argument just fine.
1373 		 */
1374 		bcopy(dst, new, dlen);
1375 		Free(rt_key(rt));	/* free old block, if any */
1376 		rt_key(rt) = (struct sockaddr *)new;
1377 		rt->rt_gateway = (struct sockaddr *)(new + dlen);
1378 	}
1379 
1380 	/*
1381 	 * Copy the new gateway value into the memory chunk.
1382 	 */
1383 	bcopy(gate, rt->rt_gateway, glen);
1384 
1385 	return (0);
1386 }
1387 
1388 void
1389 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1390 {
1391 	register u_char *cp1 = (u_char *)src;
1392 	register u_char *cp2 = (u_char *)dst;
1393 	register u_char *cp3 = (u_char *)netmask;
1394 	u_char *cplim = cp2 + *cp3;
1395 	u_char *cplim2 = cp2 + *cp1;
1396 
1397 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1398 	cp3 += 2;
1399 	if (cplim > cplim2)
1400 		cplim = cplim2;
1401 	while (cp2 < cplim)
1402 		*cp2++ = *cp1++ & *cp3++;
1403 	if (cp2 < cplim2)
1404 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1405 }
1406 
1407 /*
1408  * Set up a routing table entry, normally
1409  * for an interface.
1410  */
1411 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1412 static inline  int
1413 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1414 {
1415 	struct sockaddr *dst;
1416 	struct sockaddr *netmask;
1417 	struct rtentry *rt = NULL;
1418 	struct rt_addrinfo info;
1419 	int error = 0;
1420 	int startfib, endfib;
1421 	char tempbuf[_SOCKADDR_TMPSIZE];
1422 	int didwork = 0;
1423 	int a_failure = 0;
1424 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1425 	struct radix_node_head *rnh;
1426 
1427 	if (flags & RTF_HOST) {
1428 		dst = ifa->ifa_dstaddr;
1429 		netmask = NULL;
1430 	} else {
1431 		dst = ifa->ifa_addr;
1432 		netmask = ifa->ifa_netmask;
1433 	}
1434 	if (dst->sa_len == 0)
1435 		return(EINVAL);
1436 	switch (dst->sa_family) {
1437 	case AF_INET6:
1438 	case AF_INET:
1439 		/* We support multiple FIBs. */
1440 		break;
1441 	default:
1442 		fibnum = RT_DEFAULT_FIB;
1443 		break;
1444 	}
1445 	if (fibnum == -1) {
1446 		if (rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD) {
1447 			startfib = endfib = curthread->td_proc->p_fibnum;
1448 		} else {
1449 			startfib = 0;
1450 			endfib = rt_numfibs - 1;
1451 		}
1452 	} else {
1453 		KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1454 		startfib = fibnum;
1455 		endfib = fibnum;
1456 	}
1457 
1458 	/*
1459 	 * If it's a delete, check that if it exists,
1460 	 * it's on the correct interface or we might scrub
1461 	 * a route to another ifa which would
1462 	 * be confusing at best and possibly worse.
1463 	 */
1464 	if (cmd == RTM_DELETE) {
1465 		/*
1466 		 * It's a delete, so it should already exist..
1467 		 * If it's a net, mask off the host bits
1468 		 * (Assuming we have a mask)
1469 		 * XXX this is kinda inet specific..
1470 		 */
1471 		if (netmask != NULL) {
1472 			rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
1473 			dst = (struct sockaddr *)tempbuf;
1474 		}
1475 	}
1476 	/*
1477 	 * Now go through all the requested tables (fibs) and do the
1478 	 * requested action. Realistically, this will either be fib 0
1479 	 * for protocols that don't do multiple tables or all the
1480 	 * tables for those that do.
1481 	 */
1482 	for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
1483 		if (cmd == RTM_DELETE) {
1484 			struct radix_node *rn;
1485 			/*
1486 			 * Look up an rtentry that is in the routing tree and
1487 			 * contains the correct info.
1488 			 */
1489 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1490 			if (rnh == NULL)
1491 				/* this table doesn't exist but others might */
1492 				continue;
1493 			RADIX_NODE_HEAD_RLOCK(rnh);
1494 #ifdef RADIX_MPATH
1495 			if (rn_mpath_capable(rnh)) {
1496 
1497 				rn = rnh->rnh_matchaddr(dst, rnh);
1498 				if (rn == NULL)
1499 					error = ESRCH;
1500 				else {
1501 					rt = RNTORT(rn);
1502 					/*
1503 					 * for interface route the
1504 					 * rt->rt_gateway is sockaddr_intf
1505 					 * for cloning ARP entries, so
1506 					 * rt_mpath_matchgate must use the
1507 					 * interface address
1508 					 */
1509 					rt = rt_mpath_matchgate(rt,
1510 					    ifa->ifa_addr);
1511 					if (!rt)
1512 						error = ESRCH;
1513 				}
1514 			}
1515 			else
1516 #endif
1517 			rn = rnh->rnh_lookup(dst, netmask, rnh);
1518 			error = (rn == NULL ||
1519 			    (rn->rn_flags & RNF_ROOT) ||
1520 			    RNTORT(rn)->rt_ifa != ifa ||
1521 			    !sa_equal((struct sockaddr *)rn->rn_key, dst));
1522 			RADIX_NODE_HEAD_RUNLOCK(rnh);
1523 			if (error) {
1524 				/* this is only an error if bad on ALL tables */
1525 				continue;
1526 			}
1527 		}
1528 		/*
1529 		 * Do the actual request
1530 		 */
1531 		bzero((caddr_t)&info, sizeof(info));
1532 		info.rti_ifa = ifa;
1533 		info.rti_flags = flags |
1534 		    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1535 		info.rti_info[RTAX_DST] = dst;
1536 		/*
1537 		 * doing this for compatibility reasons
1538 		 */
1539 		if (cmd == RTM_ADD)
1540 			info.rti_info[RTAX_GATEWAY] =
1541 			    (struct sockaddr *)&null_sdl;
1542 		else
1543 			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1544 		info.rti_info[RTAX_NETMASK] = netmask;
1545 		error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1546 
1547 		if ((error == EEXIST) && (cmd == RTM_ADD)) {
1548 			/*
1549 			 * Interface route addition failed.
1550 			 * Atomically delete current prefix generating
1551 			 * RTM_DELETE message, and retry adding
1552 			 * interface prefix.
1553 			 */
1554 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1555 			RADIX_NODE_HEAD_LOCK(rnh);
1556 
1557 			/* Delete old prefix */
1558 			info.rti_ifa = NULL;
1559 			info.rti_flags = RTF_RNH_LOCKED;
1560 
1561 			error = rtrequest1_fib(RTM_DELETE, &info, NULL, fibnum);
1562 			if (error == 0) {
1563 				info.rti_ifa = ifa;
1564 				info.rti_flags = flags | RTF_RNH_LOCKED |
1565 				    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1566 				error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1567 			}
1568 
1569 			RADIX_NODE_HEAD_UNLOCK(rnh);
1570 		}
1571 
1572 
1573 		if (error == 0 && rt != NULL) {
1574 			/*
1575 			 * notify any listening routing agents of the change
1576 			 */
1577 			RT_LOCK(rt);
1578 #ifdef RADIX_MPATH
1579 			/*
1580 			 * in case address alias finds the first address
1581 			 * e.g. ifconfig bge0 192.0.2.246/24
1582 			 * e.g. ifconfig bge0 192.0.2.247/24
1583 			 * the address set in the route is 192.0.2.246
1584 			 * so we need to replace it with 192.0.2.247
1585 			 */
1586 			if (memcmp(rt->rt_ifa->ifa_addr,
1587 			    ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
1588 				ifa_free(rt->rt_ifa);
1589 				ifa_ref(ifa);
1590 				rt->rt_ifp = ifa->ifa_ifp;
1591 				rt->rt_ifa = ifa;
1592 			}
1593 #endif
1594 			/*
1595 			 * doing this for compatibility reasons
1596 			 */
1597 			if (cmd == RTM_ADD) {
1598 			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
1599 				rt->rt_ifp->if_type;
1600 			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1601 				rt->rt_ifp->if_index;
1602 			}
1603 			RT_ADDREF(rt);
1604 			RT_UNLOCK(rt);
1605 			rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
1606 			RT_LOCK(rt);
1607 			RT_REMREF(rt);
1608 			if (cmd == RTM_DELETE) {
1609 				/*
1610 				 * If we are deleting, and we found an entry,
1611 				 * then it's been removed from the tree..
1612 				 * now throw it away.
1613 				 */
1614 				RTFREE_LOCKED(rt);
1615 			} else {
1616 				if (cmd == RTM_ADD) {
1617 					/*
1618 					 * We just wanted to add it..
1619 					 * we don't actually need a reference.
1620 					 */
1621 					RT_REMREF(rt);
1622 				}
1623 				RT_UNLOCK(rt);
1624 			}
1625 			didwork = 1;
1626 		}
1627 		if (error)
1628 			a_failure = error;
1629 	}
1630 	if (cmd == RTM_DELETE) {
1631 		if (didwork) {
1632 			error = 0;
1633 		} else {
1634 			/* we only give an error if it wasn't in any table */
1635 			error = ((flags & RTF_HOST) ?
1636 			    EHOSTUNREACH : ENETUNREACH);
1637 		}
1638 	} else {
1639 		if (a_failure) {
1640 			/* return an error if any of them failed */
1641 			error = a_failure;
1642 		}
1643 	}
1644 	return (error);
1645 }
1646 
1647 #ifndef BURN_BRIDGES
1648 /* special one for inet internal use. may not use. */
1649 int
1650 rtinit_fib(struct ifaddr *ifa, int cmd, int flags)
1651 {
1652 	return (rtinit1(ifa, cmd, flags, -1));
1653 }
1654 #endif
1655 
1656 /*
1657  * Set up a routing table entry, normally
1658  * for an interface.
1659  */
1660 int
1661 rtinit(struct ifaddr *ifa, int cmd, int flags)
1662 {
1663 	struct sockaddr *dst;
1664 	int fib = RT_DEFAULT_FIB;
1665 
1666 	if (flags & RTF_HOST) {
1667 		dst = ifa->ifa_dstaddr;
1668 	} else {
1669 		dst = ifa->ifa_addr;
1670 	}
1671 
1672 	switch (dst->sa_family) {
1673 	case AF_INET6:
1674 	case AF_INET:
1675 		/* We do support multiple FIBs. */
1676 		fib = -1;
1677 		break;
1678 	}
1679 	return (rtinit1(ifa, cmd, flags, fib));
1680 }
1681