xref: /freebsd/sys/net/route.c (revision 97bd480fe38abb5950359b9d864a62037b4ab5f7)
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/syslog.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/sysproto.h>
53 #include <sys/proc.h>
54 #include <sys/domain.h>
55 #include <sys/kernel.h>
56 
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #include <net/if_dl.h>
60 #include <net/route.h>
61 #include <net/vnet.h>
62 #include <net/flowtable.h>
63 
64 #ifdef RADIX_MPATH
65 #include <net/radix_mpath.h>
66 #endif
67 
68 #include <netinet/in.h>
69 #include <netinet/ip_mroute.h>
70 
71 #include <vm/uma.h>
72 
73 #define	RT_MAXFIBS	UINT16_MAX
74 
75 /* Kernel config default option. */
76 #ifdef ROUTETABLES
77 #if ROUTETABLES <= 0
78 #error "ROUTETABLES defined too low"
79 #endif
80 #if ROUTETABLES > RT_MAXFIBS
81 #error "ROUTETABLES defined too big"
82 #endif
83 #define	RT_NUMFIBS	ROUTETABLES
84 #endif /* ROUTETABLES */
85 /* Initialize to default if not otherwise set. */
86 #ifndef	RT_NUMFIBS
87 #define	RT_NUMFIBS	1
88 #endif
89 
90 #if defined(INET) || defined(INET6)
91 #ifdef SCTP
92 extern void sctp_addr_change(struct ifaddr *ifa, int cmd);
93 #endif /* SCTP */
94 #endif
95 
96 
97 /* This is read-only.. */
98 u_int rt_numfibs = RT_NUMFIBS;
99 SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RD, &rt_numfibs, 0, "");
100 /* and this can be set too big but will be fixed before it is used */
101 TUNABLE_INT("net.fibs", &rt_numfibs);
102 
103 /*
104  * By default add routes to all fibs for new interfaces.
105  * Once this is set to 0 then only allocate routes on interface
106  * changes for the FIB of the caller when adding a new set of addresses
107  * to an interface.  XXX this is a shotgun aproach to a problem that needs
108  * a more fine grained solution.. that will come.
109  * XXX also has the problems getting the FIB from curthread which will not
110  * always work given the fib can be overridden and prefixes can be added
111  * from the network stack context.
112  */
113 u_int rt_add_addr_allfibs = 1;
114 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RW,
115     &rt_add_addr_allfibs, 0, "");
116 TUNABLE_INT("net.add_addr_allfibs", &rt_add_addr_allfibs);
117 
118 VNET_DEFINE(struct rtstat, rtstat);
119 #define	V_rtstat	VNET(rtstat)
120 
121 VNET_DEFINE(struct radix_node_head *, rt_tables);
122 #define	V_rt_tables	VNET(rt_tables)
123 
124 VNET_DEFINE(int, rttrash);		/* routes not in table but not freed */
125 #define	V_rttrash	VNET(rttrash)
126 
127 
128 /* compare two sockaddr structures */
129 #define	sa_equal(a1, a2) (((a1)->sa_len == (a2)->sa_len) && \
130     (bcmp((a1), (a2), (a1)->sa_len) == 0))
131 
132 /*
133  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
134  * The operation can be done safely (in this code) because a
135  * 'struct rtentry' starts with two 'struct radix_node''s, the first
136  * one representing leaf nodes in the routing tree, which is
137  * what the code in radix.c passes us as a 'struct radix_node'.
138  *
139  * But because there are a lot of assumptions in this conversion,
140  * do not cast explicitly, but always use the macro below.
141  */
142 #define RNTORT(p)	((struct rtentry *)(p))
143 
144 static VNET_DEFINE(uma_zone_t, rtzone);		/* Routing table UMA zone. */
145 #define	V_rtzone	VNET(rtzone)
146 
147 /*
148  * handler for net.my_fibnum
149  */
150 static int
151 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
152 {
153         int fibnum;
154         int error;
155 
156         fibnum = curthread->td_proc->p_fibnum;
157         error = sysctl_handle_int(oidp, &fibnum, 0, req);
158         return (error);
159 }
160 
161 SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
162             NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
163 
164 static __inline struct radix_node_head **
165 rt_tables_get_rnh_ptr(int table, int fam)
166 {
167 	struct radix_node_head **rnh;
168 
169 	KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
170 	    __func__));
171 	KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
172 	    __func__));
173 
174 	/* rnh is [fib=0][af=0]. */
175 	rnh = (struct radix_node_head **)V_rt_tables;
176 	/* Get the offset to the requested table and fam. */
177 	rnh += table * (AF_MAX+1) + fam;
178 
179 	return (rnh);
180 }
181 
182 struct radix_node_head *
183 rt_tables_get_rnh(int table, int fam)
184 {
185 
186 	return (*rt_tables_get_rnh_ptr(table, fam));
187 }
188 
189 /*
190  * route initialization must occur before ip6_init2(), which happenas at
191  * SI_ORDER_MIDDLE.
192  */
193 static void
194 route_init(void)
195 {
196 
197 	/* whack the tunable ints into  line. */
198 	if (rt_numfibs > RT_MAXFIBS)
199 		rt_numfibs = RT_MAXFIBS;
200 	if (rt_numfibs == 0)
201 		rt_numfibs = 1;
202 }
203 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
204 
205 static int
206 rtentry_zinit(void *mem, int size, int how)
207 {
208 	struct rtentry *rt = mem;
209 
210 	rt->rt_pksent = counter_u64_alloc(how);
211 	if (rt->rt_pksent == NULL)
212 		return (ENOMEM);
213 
214 	RT_LOCK_INIT(rt);
215 
216 	return (0);
217 }
218 
219 static void
220 rtentry_zfini(void *mem, int size)
221 {
222 	struct rtentry *rt = mem;
223 
224 	RT_LOCK_DESTROY(rt);
225 	counter_u64_free(rt->rt_pksent);
226 }
227 
228 static int
229 rtentry_ctor(void *mem, int size, void *arg, int how)
230 {
231 	struct rtentry *rt = mem;
232 
233 	bzero(rt, offsetof(struct rtentry, rt_endzero));
234 	counter_u64_zero(rt->rt_pksent);
235 
236 	return (0);
237 }
238 
239 static void
240 rtentry_dtor(void *mem, int size, void *arg)
241 {
242 	struct rtentry *rt = mem;
243 
244 	RT_UNLOCK_COND(rt);
245 }
246 
247 static void
248 vnet_route_init(const void *unused __unused)
249 {
250 	struct domain *dom;
251 	struct radix_node_head **rnh;
252 	int table;
253 	int fam;
254 
255 	V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
256 	    sizeof(struct radix_node_head *), M_RTABLE, M_WAITOK|M_ZERO);
257 
258 	V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
259 	    rtentry_ctor, rtentry_dtor,
260 	    rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
261 	for (dom = domains; dom; dom = dom->dom_next) {
262 		if (dom->dom_rtattach == NULL)
263 			continue;
264 
265 		for  (table = 0; table < rt_numfibs; table++) {
266 			fam = dom->dom_family;
267 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
268 				break;
269 
270 			/*
271 			 * XXX MRT rtattach will be also called from
272 			 * vfs_export.c but the offset will be 0 (only for
273 			 * AF_INET and AF_INET6 which don't need it anyhow).
274 			 */
275 			rnh = rt_tables_get_rnh_ptr(table, fam);
276 			if (rnh == NULL)
277 				panic("%s: rnh NULL", __func__);
278 			dom->dom_rtattach((void **)rnh, dom->dom_rtoffset);
279 		}
280 	}
281 }
282 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
283     vnet_route_init, 0);
284 
285 #ifdef VIMAGE
286 static void
287 vnet_route_uninit(const void *unused __unused)
288 {
289 	int table;
290 	int fam;
291 	struct domain *dom;
292 	struct radix_node_head **rnh;
293 
294 	for (dom = domains; dom; dom = dom->dom_next) {
295 		if (dom->dom_rtdetach == NULL)
296 			continue;
297 
298 		for (table = 0; table < rt_numfibs; table++) {
299 			fam = dom->dom_family;
300 
301 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
302 				break;
303 
304 			rnh = rt_tables_get_rnh_ptr(table, fam);
305 			if (rnh == NULL)
306 				panic("%s: rnh NULL", __func__);
307 			dom->dom_rtdetach((void **)rnh, dom->dom_rtoffset);
308 		}
309 	}
310 
311 	free(V_rt_tables, M_RTABLE);
312 	uma_zdestroy(V_rtzone);
313 }
314 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
315     vnet_route_uninit, 0);
316 #endif
317 
318 #ifndef _SYS_SYSPROTO_H_
319 struct setfib_args {
320 	int     fibnum;
321 };
322 #endif
323 int
324 sys_setfib(struct thread *td, struct setfib_args *uap)
325 {
326 	if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
327 		return EINVAL;
328 	td->td_proc->p_fibnum = uap->fibnum;
329 	return (0);
330 }
331 
332 /*
333  * Packet routing routines.
334  */
335 void
336 rtalloc(struct route *ro)
337 {
338 
339 	rtalloc_ign_fib(ro, 0UL, RT_DEFAULT_FIB);
340 }
341 
342 void
343 rtalloc_fib(struct route *ro, u_int fibnum)
344 {
345 	rtalloc_ign_fib(ro, 0UL, fibnum);
346 }
347 
348 void
349 rtalloc_ign(struct route *ro, u_long ignore)
350 {
351 	struct rtentry *rt;
352 
353 	if ((rt = ro->ro_rt) != NULL) {
354 		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
355 			return;
356 		RTFREE(rt);
357 		ro->ro_rt = NULL;
358 	}
359 	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, RT_DEFAULT_FIB);
360 	if (ro->ro_rt)
361 		RT_UNLOCK(ro->ro_rt);
362 }
363 
364 void
365 rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
366 {
367 	struct rtentry *rt;
368 
369 	if ((rt = ro->ro_rt) != NULL) {
370 		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
371 			return;
372 		RTFREE(rt);
373 		ro->ro_rt = NULL;
374 	}
375 	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
376 	if (ro->ro_rt)
377 		RT_UNLOCK(ro->ro_rt);
378 }
379 
380 /*
381  * Look up the route that matches the address given
382  * Or, at least try.. Create a cloned route if needed.
383  *
384  * The returned route, if any, is locked.
385  */
386 struct rtentry *
387 rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
388 {
389 
390 	return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
391 }
392 
393 struct rtentry *
394 rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
395 		    u_int fibnum)
396 {
397 	struct radix_node_head *rnh;
398 	struct radix_node *rn;
399 	struct rtentry *newrt;
400 	struct rt_addrinfo info;
401 	int err = 0, msgtype = RTM_MISS;
402 	int needlock;
403 
404 	KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
405 	switch (dst->sa_family) {
406 	case AF_INET6:
407 	case AF_INET:
408 		/* We support multiple FIBs. */
409 		break;
410 	default:
411 		fibnum = RT_DEFAULT_FIB;
412 		break;
413 	}
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 	needlock = !(ignflags & RTF_RNH_LOCKED);
423 	if (needlock)
424 		RADIX_NODE_HEAD_RLOCK(rnh);
425 #ifdef INVARIANTS
426 	else
427 		RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
428 #endif
429 	rn = rnh->rnh_matchaddr(dst, rnh);
430 	if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
431 		newrt = RNTORT(rn);
432 		RT_LOCK(newrt);
433 		RT_ADDREF(newrt);
434 		if (needlock)
435 			RADIX_NODE_HEAD_RUNLOCK(rnh);
436 		goto done;
437 
438 	} else if (needlock)
439 		RADIX_NODE_HEAD_RUNLOCK(rnh);
440 
441 	/*
442 	 * Either we hit the root or couldn't find any match,
443 	 * Which basically means
444 	 * "caint get there frm here"
445 	 */
446 miss:
447 	V_rtstat.rts_unreach++;
448 
449 	if (report) {
450 		/*
451 		 * If required, report the failure to the supervising
452 		 * Authorities.
453 		 * For a delete, this is not an error. (report == 0)
454 		 */
455 		bzero(&info, sizeof(info));
456 		info.rti_info[RTAX_DST] = dst;
457 		rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
458 	}
459 done:
460 	if (newrt)
461 		RT_LOCK_ASSERT(newrt);
462 	return (newrt);
463 }
464 
465 /*
466  * Remove a reference count from an rtentry.
467  * If the count gets low enough, take it out of the routing table
468  */
469 void
470 rtfree(struct rtentry *rt)
471 {
472 	struct radix_node_head *rnh;
473 
474 	KASSERT(rt != NULL,("%s: NULL rt", __func__));
475 	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
476 	KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
477 
478 	RT_LOCK_ASSERT(rt);
479 
480 	/*
481 	 * The callers should use RTFREE_LOCKED() or RTFREE(), so
482 	 * we should come here exactly with the last reference.
483 	 */
484 	RT_REMREF(rt);
485 	if (rt->rt_refcnt > 0) {
486 		log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
487 		goto done;
488 	}
489 
490 	/*
491 	 * On last reference give the "close method" a chance
492 	 * to cleanup private state.  This also permits (for
493 	 * IPv4 and IPv6) a chance to decide if the routing table
494 	 * entry should be purged immediately or at a later time.
495 	 * When an immediate purge is to happen the close routine
496 	 * typically calls rtexpunge which clears the RTF_UP flag
497 	 * on the entry so that the code below reclaims the storage.
498 	 */
499 	if (rt->rt_refcnt == 0 && rnh->rnh_close)
500 		rnh->rnh_close((struct radix_node *)rt, rnh);
501 
502 	/*
503 	 * If we are no longer "up" (and ref == 0)
504 	 * then we can free the resources associated
505 	 * with the route.
506 	 */
507 	if ((rt->rt_flags & RTF_UP) == 0) {
508 		if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
509 			panic("rtfree 2");
510 		/*
511 		 * the rtentry must have been removed from the routing table
512 		 * so it is represented in rttrash.. remove that now.
513 		 */
514 		V_rttrash--;
515 #ifdef	DIAGNOSTIC
516 		if (rt->rt_refcnt < 0) {
517 			printf("rtfree: %p not freed (neg refs)\n", rt);
518 			goto done;
519 		}
520 #endif
521 		/*
522 		 * release references on items we hold them on..
523 		 * e.g other routes and ifaddrs.
524 		 */
525 		if (rt->rt_ifa)
526 			ifa_free(rt->rt_ifa);
527 		/*
528 		 * The key is separatly alloc'd so free it (see rt_setgate()).
529 		 * This also frees the gateway, as they are always malloc'd
530 		 * together.
531 		 */
532 		Free(rt_key(rt));
533 
534 		/*
535 		 * and the rtentry itself of course
536 		 */
537 		uma_zfree(V_rtzone, rt);
538 		return;
539 	}
540 done:
541 	RT_UNLOCK(rt);
542 }
543 
544 
545 /*
546  * Force a routing table entry to the specified
547  * destination to go through the given gateway.
548  * Normally called as a result of a routing redirect
549  * message from the network layer.
550  */
551 void
552 rtredirect(struct sockaddr *dst,
553 	struct sockaddr *gateway,
554 	struct sockaddr *netmask,
555 	int flags,
556 	struct sockaddr *src)
557 {
558 
559 	rtredirect_fib(dst, gateway, netmask, flags, src, RT_DEFAULT_FIB);
560 }
561 
562 void
563 rtredirect_fib(struct sockaddr *dst,
564 	struct sockaddr *gateway,
565 	struct sockaddr *netmask,
566 	int flags,
567 	struct sockaddr *src,
568 	u_int fibnum)
569 {
570 	struct rtentry *rt, *rt0 = NULL;
571 	int error = 0;
572 	short *stat = NULL;
573 	struct rt_addrinfo info;
574 	struct ifaddr *ifa;
575 	struct radix_node_head *rnh;
576 
577 	ifa = NULL;
578 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
579 	if (rnh == NULL) {
580 		error = EAFNOSUPPORT;
581 		goto out;
582 	}
583 
584 	/* verify the gateway is directly reachable */
585 	if ((ifa = ifa_ifwithnet(gateway, 0)) == NULL) {
586 		error = ENETUNREACH;
587 		goto out;
588 	}
589 	rt = rtalloc1_fib(dst, 0, 0UL, fibnum);	/* NB: rt is locked */
590 	/*
591 	 * If the redirect isn't from our current router for this dst,
592 	 * it's either old or wrong.  If it redirects us to ourselves,
593 	 * we have a routing loop, perhaps as a result of an interface
594 	 * going down recently.
595 	 */
596 	if (!(flags & RTF_DONE) && rt &&
597 	     (!sa_equal(src, rt->rt_gateway) || rt->rt_ifa != ifa))
598 		error = EINVAL;
599 	else if (ifa_ifwithaddr_check(gateway))
600 		error = EHOSTUNREACH;
601 	if (error)
602 		goto done;
603 	/*
604 	 * Create a new entry if we just got back a wildcard entry
605 	 * or the lookup failed.  This is necessary for hosts
606 	 * which use routing redirects generated by smart gateways
607 	 * to dynamically build the routing tables.
608 	 */
609 	if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
610 		goto create;
611 	/*
612 	 * Don't listen to the redirect if it's
613 	 * for a route to an interface.
614 	 */
615 	if (rt->rt_flags & RTF_GATEWAY) {
616 		if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
617 			/*
618 			 * Changing from route to net => route to host.
619 			 * Create new route, rather than smashing route to net.
620 			 */
621 		create:
622 			rt0 = rt;
623 			rt = NULL;
624 
625 			flags |=  RTF_GATEWAY | RTF_DYNAMIC;
626 			bzero((caddr_t)&info, sizeof(info));
627 			info.rti_info[RTAX_DST] = dst;
628 			info.rti_info[RTAX_GATEWAY] = gateway;
629 			info.rti_info[RTAX_NETMASK] = netmask;
630 			info.rti_ifa = ifa;
631 			info.rti_flags = flags;
632 			if (rt0 != NULL)
633 				RT_UNLOCK(rt0);	/* drop lock to avoid LOR with RNH */
634 			error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
635 			if (rt != NULL) {
636 				RT_LOCK(rt);
637 				if (rt0 != NULL)
638 					EVENTHANDLER_INVOKE(route_redirect_event, rt0, rt, dst);
639 				flags = rt->rt_flags;
640 			}
641 			if (rt0 != NULL)
642 				RTFREE(rt0);
643 
644 			stat = &V_rtstat.rts_dynamic;
645 		} else {
646 			struct rtentry *gwrt;
647 
648 			/*
649 			 * Smash the current notion of the gateway to
650 			 * this destination.  Should check about netmask!!!
651 			 */
652 			rt->rt_flags |= RTF_MODIFIED;
653 			flags |= RTF_MODIFIED;
654 			stat = &V_rtstat.rts_newgateway;
655 			/*
656 			 * add the key and gateway (in one malloc'd chunk).
657 			 */
658 			RT_UNLOCK(rt);
659 			RADIX_NODE_HEAD_LOCK(rnh);
660 			RT_LOCK(rt);
661 			rt_setgate(rt, rt_key(rt), gateway);
662 			gwrt = rtalloc1(gateway, 1, RTF_RNH_LOCKED);
663 			RADIX_NODE_HEAD_UNLOCK(rnh);
664 			EVENTHANDLER_INVOKE(route_redirect_event, rt, gwrt, dst);
665 			RTFREE_LOCKED(gwrt);
666 		}
667 	} else
668 		error = EHOSTUNREACH;
669 done:
670 	if (rt)
671 		RTFREE_LOCKED(rt);
672 out:
673 	if (error)
674 		V_rtstat.rts_badredirect++;
675 	else if (stat != NULL)
676 		(*stat)++;
677 	bzero((caddr_t)&info, sizeof(info));
678 	info.rti_info[RTAX_DST] = dst;
679 	info.rti_info[RTAX_GATEWAY] = gateway;
680 	info.rti_info[RTAX_NETMASK] = netmask;
681 	info.rti_info[RTAX_AUTHOR] = src;
682 	rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
683 	if (ifa != NULL)
684 		ifa_free(ifa);
685 }
686 
687 int
688 rtioctl(u_long req, caddr_t data)
689 {
690 
691 	return (rtioctl_fib(req, data, RT_DEFAULT_FIB));
692 }
693 
694 /*
695  * Routing table ioctl interface.
696  */
697 int
698 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
699 {
700 
701 	/*
702 	 * If more ioctl commands are added here, make sure the proper
703 	 * super-user checks are being performed because it is possible for
704 	 * prison-root to make it this far if raw sockets have been enabled
705 	 * in jails.
706 	 */
707 #ifdef INET
708 	/* Multicast goop, grrr... */
709 	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
710 #else /* INET */
711 	return ENXIO;
712 #endif /* INET */
713 }
714 
715 /*
716  * For both ifa_ifwithroute() routines, 'ifa' is returned referenced.
717  */
718 struct ifaddr *
719 ifa_ifwithroute(int flags, struct sockaddr *dst, struct sockaddr *gateway)
720 {
721 
722 	return (ifa_ifwithroute_fib(flags, dst, gateway, RT_DEFAULT_FIB));
723 }
724 
725 struct ifaddr *
726 ifa_ifwithroute_fib(int flags, struct sockaddr *dst, struct sockaddr *gateway,
727 				u_int fibnum)
728 {
729 	register struct ifaddr *ifa;
730 	int not_found = 0;
731 
732 	if ((flags & RTF_GATEWAY) == 0) {
733 		/*
734 		 * If we are adding a route to an interface,
735 		 * and the interface is a pt to pt link
736 		 * we should search for the destination
737 		 * as our clue to the interface.  Otherwise
738 		 * we can use the local address.
739 		 */
740 		ifa = NULL;
741 		if (flags & RTF_HOST)
742 			ifa = ifa_ifwithdstaddr(dst);
743 		if (ifa == NULL)
744 			ifa = ifa_ifwithaddr(gateway);
745 	} else {
746 		/*
747 		 * If we are adding a route to a remote net
748 		 * or host, the gateway may still be on the
749 		 * other end of a pt to pt link.
750 		 */
751 		ifa = ifa_ifwithdstaddr(gateway);
752 	}
753 	if (ifa == NULL)
754 		ifa = ifa_ifwithnet(gateway, 0);
755 	if (ifa == NULL) {
756 		struct rtentry *rt = rtalloc1_fib(gateway, 0, RTF_RNH_LOCKED, fibnum);
757 		if (rt == NULL)
758 			return (NULL);
759 		/*
760 		 * dismiss a gateway that is reachable only
761 		 * through the default router
762 		 */
763 		switch (gateway->sa_family) {
764 		case AF_INET:
765 			if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
766 				not_found = 1;
767 			break;
768 		case AF_INET6:
769 			if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
770 				not_found = 1;
771 			break;
772 		default:
773 			break;
774 		}
775 		if (!not_found && rt->rt_ifa != NULL) {
776 			ifa = rt->rt_ifa;
777 			ifa_ref(ifa);
778 		}
779 		RT_REMREF(rt);
780 		RT_UNLOCK(rt);
781 		if (not_found || ifa == NULL)
782 			return (NULL);
783 	}
784 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
785 		struct ifaddr *oifa = ifa;
786 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
787 		if (ifa == NULL)
788 			ifa = oifa;
789 		else
790 			ifa_free(oifa);
791 	}
792 	return (ifa);
793 }
794 
795 /*
796  * Do appropriate manipulations of a routing tree given
797  * all the bits of info needed
798  */
799 int
800 rtrequest(int req,
801 	struct sockaddr *dst,
802 	struct sockaddr *gateway,
803 	struct sockaddr *netmask,
804 	int flags,
805 	struct rtentry **ret_nrt)
806 {
807 
808 	return (rtrequest_fib(req, dst, gateway, netmask, flags, ret_nrt,
809 	    RT_DEFAULT_FIB));
810 }
811 
812 int
813 rtrequest_fib(int req,
814 	struct sockaddr *dst,
815 	struct sockaddr *gateway,
816 	struct sockaddr *netmask,
817 	int flags,
818 	struct rtentry **ret_nrt,
819 	u_int fibnum)
820 {
821 	struct rt_addrinfo info;
822 
823 	if (dst->sa_len == 0)
824 		return(EINVAL);
825 
826 	bzero((caddr_t)&info, sizeof(info));
827 	info.rti_flags = flags;
828 	info.rti_info[RTAX_DST] = dst;
829 	info.rti_info[RTAX_GATEWAY] = gateway;
830 	info.rti_info[RTAX_NETMASK] = netmask;
831 	return rtrequest1_fib(req, &info, ret_nrt, fibnum);
832 }
833 
834 /*
835  * These (questionable) definitions of apparent local variables apply
836  * to the next two functions.  XXXXXX!!!
837  */
838 #define	dst	info->rti_info[RTAX_DST]
839 #define	gateway	info->rti_info[RTAX_GATEWAY]
840 #define	netmask	info->rti_info[RTAX_NETMASK]
841 #define	ifaaddr	info->rti_info[RTAX_IFA]
842 #define	ifpaddr	info->rti_info[RTAX_IFP]
843 #define	flags	info->rti_flags
844 
845 int
846 rt_getifa(struct rt_addrinfo *info)
847 {
848 
849 	return (rt_getifa_fib(info, RT_DEFAULT_FIB));
850 }
851 
852 /*
853  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
854  * it will be referenced so the caller must free it.
855  */
856 int
857 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
858 {
859 	struct ifaddr *ifa;
860 	int error = 0;
861 
862 	/*
863 	 * ifp may be specified by sockaddr_dl
864 	 * when protocol address is ambiguous.
865 	 */
866 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
867 	    ifpaddr->sa_family == AF_LINK &&
868 	    (ifa = ifa_ifwithnet(ifpaddr, 0)) != NULL) {
869 		info->rti_ifp = ifa->ifa_ifp;
870 		ifa_free(ifa);
871 	}
872 	if (info->rti_ifa == NULL && ifaaddr != NULL)
873 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
874 	if (info->rti_ifa == NULL) {
875 		struct sockaddr *sa;
876 
877 		sa = ifaaddr != NULL ? ifaaddr :
878 		    (gateway != NULL ? gateway : dst);
879 		if (sa != NULL && info->rti_ifp != NULL)
880 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
881 		else if (dst != NULL && gateway != NULL)
882 			info->rti_ifa = ifa_ifwithroute_fib(flags, dst, gateway,
883 							fibnum);
884 		else if (sa != NULL)
885 			info->rti_ifa = ifa_ifwithroute_fib(flags, sa, sa,
886 							fibnum);
887 	}
888 	if ((ifa = info->rti_ifa) != NULL) {
889 		if (info->rti_ifp == NULL)
890 			info->rti_ifp = ifa->ifa_ifp;
891 	} else
892 		error = ENETUNREACH;
893 	return (error);
894 }
895 
896 /*
897  * Expunges references to a route that's about to be reclaimed.
898  * The route must be locked.
899  */
900 int
901 rtexpunge(struct rtentry *rt)
902 {
903 #if !defined(RADIX_MPATH)
904 	struct radix_node *rn;
905 #else
906 	struct rt_addrinfo info;
907 	int fib;
908 	struct rtentry *rt0;
909 #endif
910 	struct radix_node_head *rnh;
911 	struct ifaddr *ifa;
912 	int error = 0;
913 
914 	/*
915 	 * Find the correct routing tree to use for this Address Family
916 	 */
917 	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
918 	RT_LOCK_ASSERT(rt);
919 	if (rnh == NULL)
920 		return (EAFNOSUPPORT);
921 	RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
922 
923 #ifdef RADIX_MPATH
924 	fib = rt->rt_fibnum;
925 	bzero(&info, sizeof(info));
926 	info.rti_ifp = rt->rt_ifp;
927 	info.rti_flags = RTF_RNH_LOCKED;
928 	info.rti_info[RTAX_DST] = rt_key(rt);
929 	info.rti_info[RTAX_GATEWAY] = rt->rt_ifa->ifa_addr;
930 
931 	RT_UNLOCK(rt);
932 	error = rtrequest1_fib(RTM_DELETE, &info, &rt0, fib);
933 
934 	if (error == 0 && rt0 != NULL) {
935 		rt = rt0;
936 		RT_LOCK(rt);
937 	} else if (error != 0) {
938 		RT_LOCK(rt);
939 		return (error);
940 	}
941 #else
942 	/*
943 	 * Remove the item from the tree; it should be there,
944 	 * but when callers invoke us blindly it may not (sigh).
945 	 */
946 	rn = rnh->rnh_deladdr(rt_key(rt), rt_mask(rt), rnh);
947 	if (rn == NULL) {
948 		error = ESRCH;
949 		goto bad;
950 	}
951 	KASSERT((rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)) == 0,
952 		("unexpected flags 0x%x", rn->rn_flags));
953 	KASSERT(rt == RNTORT(rn),
954 		("lookup mismatch, rt %p rn %p", rt, rn));
955 #endif /* RADIX_MPATH */
956 
957 	rt->rt_flags &= ~RTF_UP;
958 
959 	/*
960 	 * Give the protocol a chance to keep things in sync.
961 	 */
962 	if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest) {
963 		struct rt_addrinfo info;
964 
965 		bzero((caddr_t)&info, sizeof(info));
966 		info.rti_flags = rt->rt_flags;
967 		info.rti_info[RTAX_DST] = rt_key(rt);
968 		info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
969 		info.rti_info[RTAX_NETMASK] = rt_mask(rt);
970 		ifa->ifa_rtrequest(RTM_DELETE, rt, &info);
971 	}
972 
973 	/*
974 	 * one more rtentry floating around that is not
975 	 * linked to the routing table.
976 	 */
977 	V_rttrash++;
978 #if !defined(RADIX_MPATH)
979 bad:
980 #endif
981 	return (error);
982 }
983 
984 #if 0
985 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
986 int rt_print(char *buf, int buflen, struct rtentry *rt);
987 
988 int
989 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
990 {
991 	void *paddr = NULL;
992 
993 	switch (s->sa_family) {
994 	case AF_INET:
995 		paddr = &((struct sockaddr_in *)s)->sin_addr;
996 		break;
997 	case AF_INET6:
998 		paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
999 		break;
1000 	}
1001 
1002 	if (paddr == NULL)
1003 		return (0);
1004 
1005 	if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
1006 		return (0);
1007 
1008 	return (strlen(buf));
1009 }
1010 
1011 int
1012 rt_print(char *buf, int buflen, struct rtentry *rt)
1013 {
1014 	struct sockaddr *addr, *mask;
1015 	int i = 0;
1016 
1017 	addr = rt_key(rt);
1018 	mask = rt_mask(rt);
1019 
1020 	i = p_sockaddr(buf, buflen, addr);
1021 	if (!(rt->rt_flags & RTF_HOST)) {
1022 		buf[i++] = '/';
1023 		i += p_sockaddr(buf + i, buflen - i, mask);
1024 	}
1025 
1026 	if (rt->rt_flags & RTF_GATEWAY) {
1027 		buf[i++] = '>';
1028 		i += p_sockaddr(buf + i, buflen - i, rt->rt_gateway);
1029 	}
1030 
1031 	return (i);
1032 }
1033 #endif
1034 
1035 #ifdef RADIX_MPATH
1036 static int
1037 rn_mpath_update(int req, struct rt_addrinfo *info,
1038     struct radix_node_head *rnh, struct rtentry **ret_nrt)
1039 {
1040 	/*
1041 	 * if we got multipath routes, we require users to specify
1042 	 * a matching RTAX_GATEWAY.
1043 	 */
1044 	struct rtentry *rt, *rto = NULL;
1045 	register struct radix_node *rn;
1046 	int error = 0;
1047 
1048 	rn = rnh->rnh_lookup(dst, netmask, rnh);
1049 	if (rn == NULL)
1050 		return (ESRCH);
1051 	rto = rt = RNTORT(rn);
1052 
1053 	rt = rt_mpath_matchgate(rt, gateway);
1054 	if (rt == NULL)
1055 		return (ESRCH);
1056 	/*
1057 	 * this is the first entry in the chain
1058 	 */
1059 	if (rto == rt) {
1060 		rn = rn_mpath_next((struct radix_node *)rt);
1061 		/*
1062 		 * there is another entry, now it's active
1063 		 */
1064 		if (rn) {
1065 			rto = RNTORT(rn);
1066 			RT_LOCK(rto);
1067 			rto->rt_flags |= RTF_UP;
1068 			RT_UNLOCK(rto);
1069 		} else if (rt->rt_flags & RTF_GATEWAY) {
1070 			/*
1071 			 * For gateway routes, we need to
1072 			 * make sure that we we are deleting
1073 			 * the correct gateway.
1074 			 * rt_mpath_matchgate() does not
1075 			 * check the case when there is only
1076 			 * one route in the chain.
1077 			 */
1078 			if (gateway &&
1079 			    (rt->rt_gateway->sa_len != gateway->sa_len ||
1080 				memcmp(rt->rt_gateway, gateway, gateway->sa_len)))
1081 				error = ESRCH;
1082 			else {
1083 				/*
1084 				 * remove from tree before returning it
1085 				 * to the caller
1086 				 */
1087 				rn = rnh->rnh_deladdr(dst, netmask, rnh);
1088 				KASSERT(rt == RNTORT(rn), ("radix node disappeared"));
1089 				goto gwdelete;
1090 			}
1091 
1092 		}
1093 		/*
1094 		 * use the normal delete code to remove
1095 		 * the first entry
1096 		 */
1097 		if (req != RTM_DELETE)
1098 			goto nondelete;
1099 
1100 		error = ENOENT;
1101 		goto done;
1102 	}
1103 
1104 	/*
1105 	 * if the entry is 2nd and on up
1106 	 */
1107 	if ((req == RTM_DELETE) && !rt_mpath_deldup(rto, rt))
1108 		panic ("rtrequest1: rt_mpath_deldup");
1109 gwdelete:
1110 	RT_LOCK(rt);
1111 	RT_ADDREF(rt);
1112 	if (req == RTM_DELETE) {
1113 		rt->rt_flags &= ~RTF_UP;
1114 		/*
1115 		 * One more rtentry floating around that is not
1116 		 * linked to the routing table. rttrash will be decremented
1117 		 * when RTFREE(rt) is eventually called.
1118 		 */
1119 		V_rttrash++;
1120 	}
1121 
1122 nondelete:
1123 	if (req != RTM_DELETE)
1124 		panic("unrecognized request %d", req);
1125 
1126 
1127 	/*
1128 	 * If the caller wants it, then it can have it,
1129 	 * but it's up to it to free the rtentry as we won't be
1130 	 * doing it.
1131 	 */
1132 	if (ret_nrt) {
1133 		*ret_nrt = rt;
1134 		RT_UNLOCK(rt);
1135 	} else
1136 		RTFREE_LOCKED(rt);
1137 done:
1138 	return (error);
1139 }
1140 #endif
1141 
1142 int
1143 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1144 				u_int fibnum)
1145 {
1146 	int error = 0, needlock = 0;
1147 	register struct rtentry *rt;
1148 #ifdef FLOWTABLE
1149 	register struct rtentry *rt0;
1150 #endif
1151 	register struct radix_node *rn;
1152 	register struct radix_node_head *rnh;
1153 	struct ifaddr *ifa;
1154 	struct sockaddr *ndst;
1155 	struct sockaddr_storage mdst;
1156 #define senderr(x) { error = x ; goto bad; }
1157 
1158 	KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1159 	switch (dst->sa_family) {
1160 	case AF_INET6:
1161 	case AF_INET:
1162 		/* We support multiple FIBs. */
1163 		break;
1164 	default:
1165 		fibnum = RT_DEFAULT_FIB;
1166 		break;
1167 	}
1168 
1169 	/*
1170 	 * Find the correct routing tree to use for this Address Family
1171 	 */
1172 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1173 	if (rnh == NULL)
1174 		return (EAFNOSUPPORT);
1175 	needlock = ((flags & RTF_RNH_LOCKED) == 0);
1176 	flags &= ~RTF_RNH_LOCKED;
1177 	if (needlock)
1178 		RADIX_NODE_HEAD_LOCK(rnh);
1179 	else
1180 		RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1181 	/*
1182 	 * If we are adding a host route then we don't want to put
1183 	 * a netmask in the tree, nor do we want to clone it.
1184 	 */
1185 	if (flags & RTF_HOST)
1186 		netmask = NULL;
1187 
1188 	switch (req) {
1189 	case RTM_DELETE:
1190 		if (netmask) {
1191 			rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1192 			dst = (struct sockaddr *)&mdst;
1193 		}
1194 #ifdef RADIX_MPATH
1195 		if (rn_mpath_capable(rnh)) {
1196 			error = rn_mpath_update(req, info, rnh, ret_nrt);
1197 			/*
1198 			 * "bad" holds true for the success case
1199 			 * as well
1200 			 */
1201 			if (error != ENOENT)
1202 				goto bad;
1203 			error = 0;
1204 		}
1205 #endif
1206 		if ((flags & RTF_PINNED) == 0) {
1207 			/* Check if target route can be deleted */
1208 			rt = (struct rtentry *)rnh->rnh_lookup(dst,
1209 			    netmask, rnh);
1210 			if ((rt != NULL) && (rt->rt_flags & RTF_PINNED))
1211 				senderr(EADDRINUSE);
1212 		}
1213 
1214 		/*
1215 		 * Remove the item from the tree and return it.
1216 		 * Complain if it is not there and do no more processing.
1217 		 */
1218 		rn = rnh->rnh_deladdr(dst, netmask, rnh);
1219 		if (rn == NULL)
1220 			senderr(ESRCH);
1221 		if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1222 			panic ("rtrequest delete");
1223 		rt = RNTORT(rn);
1224 		RT_LOCK(rt);
1225 		RT_ADDREF(rt);
1226 		rt->rt_flags &= ~RTF_UP;
1227 
1228 		/*
1229 		 * give the protocol a chance to keep things in sync.
1230 		 */
1231 		if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
1232 			ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1233 
1234 		/*
1235 		 * One more rtentry floating around that is not
1236 		 * linked to the routing table. rttrash will be decremented
1237 		 * when RTFREE(rt) is eventually called.
1238 		 */
1239 		V_rttrash++;
1240 
1241 		/*
1242 		 * If the caller wants it, then it can have it,
1243 		 * but it's up to it to free the rtentry as we won't be
1244 		 * doing it.
1245 		 */
1246 		if (ret_nrt) {
1247 			*ret_nrt = rt;
1248 			RT_UNLOCK(rt);
1249 		} else
1250 			RTFREE_LOCKED(rt);
1251 		break;
1252 	case RTM_RESOLVE:
1253 		/*
1254 		 * resolve was only used for route cloning
1255 		 * here for compat
1256 		 */
1257 		break;
1258 	case RTM_ADD:
1259 		if ((flags & RTF_GATEWAY) && !gateway)
1260 			senderr(EINVAL);
1261 		if (dst && gateway && (dst->sa_family != gateway->sa_family) &&
1262 		    (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1263 			senderr(EINVAL);
1264 
1265 		if (info->rti_ifa == NULL) {
1266 			error = rt_getifa_fib(info, fibnum);
1267 			if (error)
1268 				senderr(error);
1269 		} else
1270 			ifa_ref(info->rti_ifa);
1271 		ifa = info->rti_ifa;
1272 		rt = uma_zalloc(V_rtzone, M_NOWAIT);
1273 		if (rt == NULL) {
1274 			ifa_free(ifa);
1275 			senderr(ENOBUFS);
1276 		}
1277 		rt->rt_flags = RTF_UP | flags;
1278 		rt->rt_fibnum = fibnum;
1279 		/*
1280 		 * Add the gateway. Possibly re-malloc-ing the storage for it.
1281 		 */
1282 		RT_LOCK(rt);
1283 		if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1284 			ifa_free(ifa);
1285 			uma_zfree(V_rtzone, rt);
1286 			senderr(error);
1287 		}
1288 
1289 		/*
1290 		 * point to the (possibly newly malloc'd) dest address.
1291 		 */
1292 		ndst = (struct sockaddr *)rt_key(rt);
1293 
1294 		/*
1295 		 * make sure it contains the value we want (masked if needed).
1296 		 */
1297 		if (netmask) {
1298 			rt_maskedcopy(dst, ndst, netmask);
1299 		} else
1300 			bcopy(dst, ndst, dst->sa_len);
1301 
1302 		/*
1303 		 * We use the ifa reference returned by rt_getifa_fib().
1304 		 * This moved from below so that rnh->rnh_addaddr() can
1305 		 * examine the ifa and  ifa->ifa_ifp if it so desires.
1306 		 */
1307 		rt->rt_ifa = ifa;
1308 		rt->rt_ifp = ifa->ifa_ifp;
1309 		rt->rt_weight = 1;
1310 
1311 #ifdef RADIX_MPATH
1312 		/* do not permit exactly the same dst/mask/gw pair */
1313 		if (rn_mpath_capable(rnh) &&
1314 			rt_mpath_conflict(rnh, rt, netmask)) {
1315 			ifa_free(rt->rt_ifa);
1316 			Free(rt_key(rt));
1317 			uma_zfree(V_rtzone, rt);
1318 			senderr(EEXIST);
1319 		}
1320 #endif
1321 
1322 #ifdef FLOWTABLE
1323 		rt0 = NULL;
1324 		/* "flow-table" only supports IPv6 and IPv4 at the moment. */
1325 		switch (dst->sa_family) {
1326 #ifdef INET6
1327 		case AF_INET6:
1328 #endif
1329 #ifdef INET
1330 		case AF_INET:
1331 #endif
1332 #if defined(INET6) || defined(INET)
1333 			rn = rnh->rnh_matchaddr(dst, rnh);
1334 			if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
1335 				struct sockaddr *mask;
1336 				u_char *m, *n;
1337 				int len;
1338 
1339 				/*
1340 				 * compare mask to see if the new route is
1341 				 * more specific than the existing one
1342 				 */
1343 				rt0 = RNTORT(rn);
1344 				RT_LOCK(rt0);
1345 				RT_ADDREF(rt0);
1346 				RT_UNLOCK(rt0);
1347 				/*
1348 				 * A host route is already present, so
1349 				 * leave the flow-table entries as is.
1350 				 */
1351 				if (rt0->rt_flags & RTF_HOST) {
1352 					RTFREE(rt0);
1353 					rt0 = NULL;
1354 				} else if (!(flags & RTF_HOST) && netmask) {
1355 					mask = rt_mask(rt0);
1356 					len = mask->sa_len;
1357 					m = (u_char *)mask;
1358 					n = (u_char *)netmask;
1359 					while (len-- > 0) {
1360 						if (*n != *m)
1361 							break;
1362 						n++;
1363 						m++;
1364 					}
1365 					if (len == 0 || (*n < *m)) {
1366 						RTFREE(rt0);
1367 						rt0 = NULL;
1368 					}
1369 				}
1370 			}
1371 #endif/* INET6 || INET */
1372 		}
1373 #endif /* FLOWTABLE */
1374 
1375 		/* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1376 		rn = rnh->rnh_addaddr(ndst, netmask, rnh, rt->rt_nodes);
1377 		/*
1378 		 * If it still failed to go into the tree,
1379 		 * then un-make it (this should be a function)
1380 		 */
1381 		if (rn == NULL) {
1382 			ifa_free(rt->rt_ifa);
1383 			Free(rt_key(rt));
1384 			uma_zfree(V_rtzone, rt);
1385 #ifdef FLOWTABLE
1386 			if (rt0 != NULL)
1387 				RTFREE(rt0);
1388 #endif
1389 			senderr(EEXIST);
1390 		}
1391 #ifdef FLOWTABLE
1392 		else if (rt0 != NULL) {
1393 			flowtable_route_flush(dst->sa_family, rt0);
1394 			RTFREE(rt0);
1395 		}
1396 #endif
1397 
1398 		/*
1399 		 * If this protocol has something to add to this then
1400 		 * allow it to do that as well.
1401 		 */
1402 		if (ifa->ifa_rtrequest)
1403 			ifa->ifa_rtrequest(req, rt, info);
1404 
1405 		/*
1406 		 * actually return a resultant rtentry and
1407 		 * give the caller a single reference.
1408 		 */
1409 		if (ret_nrt) {
1410 			*ret_nrt = rt;
1411 			RT_ADDREF(rt);
1412 		}
1413 		RT_UNLOCK(rt);
1414 		break;
1415 	default:
1416 		error = EOPNOTSUPP;
1417 	}
1418 bad:
1419 	if (needlock)
1420 		RADIX_NODE_HEAD_UNLOCK(rnh);
1421 	return (error);
1422 #undef senderr
1423 }
1424 
1425 #undef dst
1426 #undef gateway
1427 #undef netmask
1428 #undef ifaaddr
1429 #undef ifpaddr
1430 #undef flags
1431 
1432 int
1433 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1434 {
1435 	/* XXX dst may be overwritten, can we move this to below */
1436 	int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1437 #ifdef INVARIANTS
1438 	struct radix_node_head *rnh;
1439 
1440 	rnh = rt_tables_get_rnh(rt->rt_fibnum, dst->sa_family);
1441 #endif
1442 
1443 	RT_LOCK_ASSERT(rt);
1444 	RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1445 
1446 	/*
1447 	 * Prepare to store the gateway in rt->rt_gateway.
1448 	 * Both dst and gateway are stored one after the other in the same
1449 	 * malloc'd chunk. If we have room, we can reuse the old buffer,
1450 	 * rt_gateway already points to the right place.
1451 	 * Otherwise, malloc a new block and update the 'dst' address.
1452 	 */
1453 	if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1454 		caddr_t new;
1455 
1456 		R_Malloc(new, caddr_t, dlen + glen);
1457 		if (new == NULL)
1458 			return ENOBUFS;
1459 		/*
1460 		 * XXX note, we copy from *dst and not *rt_key(rt) because
1461 		 * rt_setgate() can be called to initialize a newly
1462 		 * allocated route entry, in which case rt_key(rt) == NULL
1463 		 * (and also rt->rt_gateway == NULL).
1464 		 * Free()/free() handle a NULL argument just fine.
1465 		 */
1466 		bcopy(dst, new, dlen);
1467 		Free(rt_key(rt));	/* free old block, if any */
1468 		rt_key(rt) = (struct sockaddr *)new;
1469 		rt->rt_gateway = (struct sockaddr *)(new + dlen);
1470 	}
1471 
1472 	/*
1473 	 * Copy the new gateway value into the memory chunk.
1474 	 */
1475 	bcopy(gate, rt->rt_gateway, glen);
1476 
1477 	return (0);
1478 }
1479 
1480 void
1481 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1482 {
1483 	register u_char *cp1 = (u_char *)src;
1484 	register u_char *cp2 = (u_char *)dst;
1485 	register u_char *cp3 = (u_char *)netmask;
1486 	u_char *cplim = cp2 + *cp3;
1487 	u_char *cplim2 = cp2 + *cp1;
1488 
1489 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1490 	cp3 += 2;
1491 	if (cplim > cplim2)
1492 		cplim = cplim2;
1493 	while (cp2 < cplim)
1494 		*cp2++ = *cp1++ & *cp3++;
1495 	if (cp2 < cplim2)
1496 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1497 }
1498 
1499 /*
1500  * Set up a routing table entry, normally
1501  * for an interface.
1502  */
1503 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1504 static inline  int
1505 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1506 {
1507 	struct sockaddr *dst;
1508 	struct sockaddr *netmask;
1509 	struct rtentry *rt = NULL;
1510 	struct rt_addrinfo info;
1511 	int error = 0;
1512 	int startfib, endfib;
1513 	char tempbuf[_SOCKADDR_TMPSIZE];
1514 	int didwork = 0;
1515 	int a_failure = 0;
1516 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1517 	struct radix_node_head *rnh;
1518 
1519 	if (flags & RTF_HOST) {
1520 		dst = ifa->ifa_dstaddr;
1521 		netmask = NULL;
1522 	} else {
1523 		dst = ifa->ifa_addr;
1524 		netmask = ifa->ifa_netmask;
1525 	}
1526 	if (dst->sa_len == 0)
1527 		return(EINVAL);
1528 	switch (dst->sa_family) {
1529 	case AF_INET6:
1530 	case AF_INET:
1531 		/* We support multiple FIBs. */
1532 		break;
1533 	default:
1534 		fibnum = RT_DEFAULT_FIB;
1535 		break;
1536 	}
1537 	if (fibnum == RT_ALL_FIBS) {
1538 		if (rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD) {
1539 			startfib = endfib = curthread->td_proc->p_fibnum;
1540 		} else {
1541 			startfib = 0;
1542 			endfib = rt_numfibs - 1;
1543 		}
1544 	} else {
1545 		KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1546 		startfib = fibnum;
1547 		endfib = fibnum;
1548 	}
1549 
1550 	/*
1551 	 * If it's a delete, check that if it exists,
1552 	 * it's on the correct interface or we might scrub
1553 	 * a route to another ifa which would
1554 	 * be confusing at best and possibly worse.
1555 	 */
1556 	if (cmd == RTM_DELETE) {
1557 		/*
1558 		 * It's a delete, so it should already exist..
1559 		 * If it's a net, mask off the host bits
1560 		 * (Assuming we have a mask)
1561 		 * XXX this is kinda inet specific..
1562 		 */
1563 		if (netmask != NULL) {
1564 			rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
1565 			dst = (struct sockaddr *)tempbuf;
1566 		}
1567 	}
1568 	/*
1569 	 * Now go through all the requested tables (fibs) and do the
1570 	 * requested action. Realistically, this will either be fib 0
1571 	 * for protocols that don't do multiple tables or all the
1572 	 * tables for those that do.
1573 	 */
1574 	for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
1575 		if (cmd == RTM_DELETE) {
1576 			struct radix_node *rn;
1577 			/*
1578 			 * Look up an rtentry that is in the routing tree and
1579 			 * contains the correct info.
1580 			 */
1581 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1582 			if (rnh == NULL)
1583 				/* this table doesn't exist but others might */
1584 				continue;
1585 			RADIX_NODE_HEAD_RLOCK(rnh);
1586 			rn = rnh->rnh_lookup(dst, netmask, rnh);
1587 #ifdef RADIX_MPATH
1588 			if (rn_mpath_capable(rnh)) {
1589 
1590 				if (rn == NULL)
1591 					error = ESRCH;
1592 				else {
1593 					rt = RNTORT(rn);
1594 					/*
1595 					 * for interface route the
1596 					 * rt->rt_gateway is sockaddr_intf
1597 					 * for cloning ARP entries, so
1598 					 * rt_mpath_matchgate must use the
1599 					 * interface address
1600 					 */
1601 					rt = rt_mpath_matchgate(rt,
1602 					    ifa->ifa_addr);
1603 					if (rt == NULL)
1604 						error = ESRCH;
1605 				}
1606 			}
1607 #endif
1608 			error = (rn == NULL ||
1609 			    (rn->rn_flags & RNF_ROOT) ||
1610 			    RNTORT(rn)->rt_ifa != ifa);
1611 			RADIX_NODE_HEAD_RUNLOCK(rnh);
1612 			if (error) {
1613 				/* this is only an error if bad on ALL tables */
1614 				continue;
1615 			}
1616 		}
1617 		/*
1618 		 * Do the actual request
1619 		 */
1620 		bzero((caddr_t)&info, sizeof(info));
1621 		info.rti_ifa = ifa;
1622 		info.rti_flags = flags |
1623 		    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1624 		info.rti_info[RTAX_DST] = dst;
1625 		/*
1626 		 * doing this for compatibility reasons
1627 		 */
1628 		if (cmd == RTM_ADD)
1629 			info.rti_info[RTAX_GATEWAY] =
1630 			    (struct sockaddr *)&null_sdl;
1631 		else
1632 			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1633 		info.rti_info[RTAX_NETMASK] = netmask;
1634 		error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1635 
1636 		if ((error == EEXIST) && (cmd == RTM_ADD)) {
1637 			/*
1638 			 * Interface route addition failed.
1639 			 * Atomically delete current prefix generating
1640 			 * RTM_DELETE message, and retry adding
1641 			 * interface prefix.
1642 			 */
1643 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1644 			RADIX_NODE_HEAD_LOCK(rnh);
1645 
1646 			/* Delete old prefix */
1647 			info.rti_ifa = NULL;
1648 			info.rti_flags = RTF_RNH_LOCKED;
1649 
1650 			error = rtrequest1_fib(RTM_DELETE, &info, NULL, fibnum);
1651 			if (error == 0) {
1652 				info.rti_ifa = ifa;
1653 				info.rti_flags = flags | RTF_RNH_LOCKED |
1654 				    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1655 				error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1656 			}
1657 
1658 			RADIX_NODE_HEAD_UNLOCK(rnh);
1659 		}
1660 
1661 
1662 		if (error == 0 && rt != NULL) {
1663 			/*
1664 			 * notify any listening routing agents of the change
1665 			 */
1666 			RT_LOCK(rt);
1667 #ifdef RADIX_MPATH
1668 			/*
1669 			 * in case address alias finds the first address
1670 			 * e.g. ifconfig bge0 192.0.2.246/24
1671 			 * e.g. ifconfig bge0 192.0.2.247/24
1672 			 * the address set in the route is 192.0.2.246
1673 			 * so we need to replace it with 192.0.2.247
1674 			 */
1675 			if (memcmp(rt->rt_ifa->ifa_addr,
1676 			    ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
1677 				ifa_free(rt->rt_ifa);
1678 				ifa_ref(ifa);
1679 				rt->rt_ifp = ifa->ifa_ifp;
1680 				rt->rt_ifa = ifa;
1681 			}
1682 #endif
1683 			/*
1684 			 * doing this for compatibility reasons
1685 			 */
1686 			if (cmd == RTM_ADD) {
1687 			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
1688 				rt->rt_ifp->if_type;
1689 			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1690 				rt->rt_ifp->if_index;
1691 			}
1692 			RT_ADDREF(rt);
1693 			RT_UNLOCK(rt);
1694 			rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
1695 			RT_LOCK(rt);
1696 			RT_REMREF(rt);
1697 			if (cmd == RTM_DELETE) {
1698 				/*
1699 				 * If we are deleting, and we found an entry,
1700 				 * then it's been removed from the tree..
1701 				 * now throw it away.
1702 				 */
1703 				RTFREE_LOCKED(rt);
1704 			} else {
1705 				if (cmd == RTM_ADD) {
1706 					/*
1707 					 * We just wanted to add it..
1708 					 * we don't actually need a reference.
1709 					 */
1710 					RT_REMREF(rt);
1711 				}
1712 				RT_UNLOCK(rt);
1713 			}
1714 			didwork = 1;
1715 		}
1716 		if (error)
1717 			a_failure = error;
1718 	}
1719 	if (cmd == RTM_DELETE) {
1720 		if (didwork) {
1721 			error = 0;
1722 		} else {
1723 			/* we only give an error if it wasn't in any table */
1724 			error = ((flags & RTF_HOST) ?
1725 			    EHOSTUNREACH : ENETUNREACH);
1726 		}
1727 	} else {
1728 		if (a_failure) {
1729 			/* return an error if any of them failed */
1730 			error = a_failure;
1731 		}
1732 	}
1733 	return (error);
1734 }
1735 
1736 /*
1737  * Set up a routing table entry, normally
1738  * for an interface.
1739  */
1740 int
1741 rtinit(struct ifaddr *ifa, int cmd, int flags)
1742 {
1743 	struct sockaddr *dst;
1744 	int fib = RT_DEFAULT_FIB;
1745 
1746 	if (flags & RTF_HOST) {
1747 		dst = ifa->ifa_dstaddr;
1748 	} else {
1749 		dst = ifa->ifa_addr;
1750 	}
1751 
1752 	switch (dst->sa_family) {
1753 	case AF_INET6:
1754 	case AF_INET:
1755 		/* We do support multiple FIBs. */
1756 		fib = RT_ALL_FIBS;
1757 		break;
1758 	}
1759 	return (rtinit1(ifa, cmd, flags, fib));
1760 }
1761 
1762 /*
1763  * Announce interface address arrival/withdraw
1764  * Returns 0 on success.
1765  */
1766 int
1767 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
1768 {
1769 
1770 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1771 	    ("unexpected cmd %d", cmd));
1772 
1773 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1774 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1775 
1776 	return (rtsock_addrmsg(cmd, ifa, fibnum));
1777 }
1778 
1779 /*
1780  * Announce route addition/removal.
1781  * Users of this function MUST validate input data BEFORE calling.
1782  * However we have to be able to handle invalid data:
1783  * if some userland app sends us "invalid" route message (invalid mask,
1784  * no dst, wrong address families, etc...) we need to pass it back
1785  * to app (and any other rtsock consumers) with rtm_errno field set to
1786  * non-zero value.
1787  * Returns 0 on success.
1788  */
1789 int
1790 rt_routemsg(int cmd, struct ifnet *ifp, int error, struct rtentry *rt,
1791     int fibnum)
1792 {
1793 
1794 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1795 	    ("unexpected cmd %d", cmd));
1796 
1797 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1798 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1799 
1800 	KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
1801 
1802 	return (rtsock_routemsg(cmd, ifp, error, rt, fibnum));
1803 }
1804 
1805 void
1806 rt_newaddrmsg(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt)
1807 {
1808 
1809 	rt_newaddrmsg_fib(cmd, ifa, error, rt, RT_ALL_FIBS);
1810 }
1811 
1812 /*
1813  * This is called to generate messages from the routing socket
1814  * indicating a network interface has had addresses associated with it.
1815  */
1816 void
1817 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt,
1818     int fibnum)
1819 {
1820 
1821 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1822 		("unexpected cmd %u", cmd));
1823 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1824 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1825 
1826 #if defined(INET) || defined(INET6)
1827 #ifdef SCTP
1828 	/*
1829 	 * notify the SCTP stack
1830 	 * this will only get called when an address is added/deleted
1831 	 * XXX pass the ifaddr struct instead if ifa->ifa_addr...
1832 	 */
1833 	sctp_addr_change(ifa, cmd);
1834 #endif /* SCTP */
1835 #endif
1836 	if (cmd == RTM_ADD) {
1837 		rt_addrmsg(cmd, ifa, fibnum);
1838 		if (rt != NULL)
1839 			rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
1840 	} else {
1841 		if (rt != NULL)
1842 			rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
1843 		rt_addrmsg(cmd, ifa, fibnum);
1844 	}
1845 }
1846 
1847