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