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