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