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