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