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