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