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