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