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