xref: /dflybsd-src/sys/net/route.c (revision 6d49aa6ffaff1e5a2ff3abe70c453cc8b47adb73)
1 /*
2  * Copyright (c) 2004, 2005 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Jeffrey M. Hsu.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of The DragonFly Project nor the names of its
16  *    contributors may be used to endorse or promote products derived
17  *    from this software without specific, prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1980, 1986, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *	This product includes software developed by the University of
48  *	California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)route.c	8.3 (Berkeley) 1/9/95
66  * $FreeBSD: src/sys/net/route.c,v 1.59.2.10 2003/01/17 08:04:00 ru Exp $
67  * $DragonFly: src/sys/net/route.c,v 1.28 2007/03/04 18:51:59 swildner Exp $
68  */
69 
70 #include "opt_inet.h"
71 
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/malloc.h>
75 #include <sys/mbuf.h>
76 #include <sys/socket.h>
77 #include <sys/domain.h>
78 #include <sys/kernel.h>
79 #include <sys/sysctl.h>
80 #include <sys/globaldata.h>
81 #include <sys/thread.h>
82 #include <sys/thread2.h>
83 #include <sys/msgport2.h>
84 
85 #include <net/if.h>
86 #include <net/route.h>
87 #include <net/netisr.h>
88 
89 #include <netinet/in.h>
90 #include <net/ip_mroute/ip_mroute.h>
91 
92 static struct rtstatistics rtstatistics_percpu[MAXCPU];
93 #ifdef SMP
94 #define rtstat	rtstatistics_percpu[mycpuid]
95 #else
96 #define rtstat	rtstatistics_percpu[0]
97 #endif
98 
99 struct radix_node_head *rt_tables[MAXCPU][AF_MAX+1];
100 struct lwkt_port *rt_ports[MAXCPU];
101 
102 static void	rt_maskedcopy (struct sockaddr *, struct sockaddr *,
103 			       struct sockaddr *);
104 static void rtable_init(void);
105 static void rtable_service_loop(void *dummy);
106 static void rtinit_rtrequest_callback(int, int, struct rt_addrinfo *,
107 				      struct rtentry *, void *);
108 
109 #ifdef SMP
110 static int rtredirect_msghandler(struct lwkt_msg *lmsg);
111 static int rtrequest1_msghandler(struct lwkt_msg *lmsg);
112 #endif
113 
114 SYSCTL_NODE(_net, OID_AUTO, route, CTLFLAG_RW, 0, "Routing");
115 
116 #ifdef ROUTE_DEBUG
117 static int route_debug = 1;
118 SYSCTL_INT(_net_route, OID_AUTO, route_debug, CTLFLAG_RW,
119            &route_debug, 0, "");
120 #endif
121 
122 /*
123  * Initialize the route table(s) for protocol domains and
124  * create a helper thread which will be responsible for updating
125  * route table entries on each cpu.
126  */
127 void
128 route_init(void)
129 {
130 	int cpu, origcpu;
131 	thread_t rtd;
132 
133 	for (cpu = 0; cpu < ncpus; ++cpu)
134 		bzero(&rtstatistics_percpu[cpu], sizeof(struct rtstatistics));
135 	rn_init();      /* initialize all zeroes, all ones, mask table */
136 	origcpu = mycpuid;
137 	for (cpu = 0; cpu < ncpus; cpu++) {
138 		lwkt_migratecpu(cpu);
139 		rtable_init();
140 		lwkt_create(rtable_service_loop, NULL, &rtd, NULL,
141 			    TDF_STOPREQ, cpu, "rtable_cpu %d", cpu);
142 		rt_ports[cpu] = &rtd->td_msgport;
143 		lwkt_schedule(rtd);
144 	}
145 	lwkt_migratecpu(origcpu);
146 }
147 
148 static void
149 rtable_init(void)
150 {
151 	struct domain *dom;
152 
153 	SLIST_FOREACH(dom, &domains, dom_next) {
154 		if (dom->dom_rtattach) {
155 			dom->dom_rtattach(
156 				(void **)&rt_tables[mycpuid][dom->dom_family],
157 			        dom->dom_rtoffset);
158 		}
159 	}
160 }
161 
162 /*
163  * Our per-cpu table management protocol thread.  All route table operations
164  * are chained through all cpus in order starting at cpu #0 in order to
165  * maintain duplicate route tables on each cpu.  Having a spearate route
166  * table management thread allows the protocol and interrupt threads to
167  * issue route table changes.
168  */
169 static void
170 rtable_service_loop(void *dummy __unused)
171 {
172 	struct lwkt_msg *lmsg;
173 	thread_t td = curthread;
174 
175 	while ((lmsg = lwkt_waitport(&td->td_msgport, NULL)) != NULL) {
176 		lmsg->ms_cmd.cm_func(lmsg);
177 	}
178 }
179 
180 /*
181  * Routing statistics.
182  */
183 #ifdef SMP
184 static int
185 sysctl_rtstatistics(SYSCTL_HANDLER_ARGS)
186 {
187 	int cpu, error = 0;
188 
189 	for (cpu = 0; cpu < ncpus; ++cpu) {
190 		if ((error = SYSCTL_OUT(req, &rtstatistics_percpu[cpu],
191 					sizeof(struct rtstatistics))))
192 				break;
193 		if ((error = SYSCTL_IN(req, &rtstatistics_percpu[cpu],
194 					sizeof(struct rtstatistics))))
195 				break;
196 	}
197 
198 	return (error);
199 }
200 SYSCTL_PROC(_net_route, OID_AUTO, stats, (CTLTYPE_OPAQUE|CTLFLAG_RW),
201 	0, 0, sysctl_rtstatistics, "S,rtstatistics", "Routing statistics");
202 #else
203 SYSCTL_STRUCT(_net_route, OID_AUTO, stats, CTLFLAG_RW, &rtstat, rtstatistics,
204 "Routing statistics");
205 #endif
206 
207 /*
208  * Packet routing routines.
209  */
210 
211 /*
212  * Look up and fill in the "ro_rt" rtentry field in a route structure given
213  * an address in the "ro_dst" field.  Always send a report on a miss and
214  * always clone routes.
215  */
216 void
217 rtalloc(struct route *ro)
218 {
219 	rtalloc_ign(ro, 0UL);
220 }
221 
222 /*
223  * Look up and fill in the "ro_rt" rtentry field in a route structure given
224  * an address in the "ro_dst" field.  Always send a report on a miss and
225  * optionally clone routes when RTF_CLONING or RTF_PRCLONING are not being
226  * ignored.
227  */
228 void
229 rtalloc_ign(struct route *ro, u_long ignoreflags)
230 {
231 	if (ro->ro_rt != NULL) {
232 		if (ro->ro_rt->rt_ifp != NULL && ro->ro_rt->rt_flags & RTF_UP)
233 			return;
234 		rtfree(ro->ro_rt);
235 		ro->ro_rt = NULL;
236 	}
237 	ro->ro_rt = _rtlookup(&ro->ro_dst, RTL_REPORTMSG, ignoreflags);
238 }
239 
240 /*
241  * Look up the route that matches the given "dst" address.
242  *
243  * Route lookup can have the side-effect of creating and returning
244  * a cloned route instead when "dst" matches a cloning route and the
245  * RTF_CLONING and RTF_PRCLONING flags are not being ignored.
246  *
247  * Any route returned has its reference count incremented.
248  */
249 struct rtentry *
250 _rtlookup(struct sockaddr *dst, boolean_t generate_report, u_long ignore)
251 {
252 	struct radix_node_head *rnh = rt_tables[mycpuid][dst->sa_family];
253 	struct rtentry *rt;
254 
255 	if (rnh == NULL)
256 		goto unreach;
257 
258 	/*
259 	 * Look up route in the radix tree.
260 	 */
261 	rt = (struct rtentry *) rnh->rnh_matchaddr((char *)dst, rnh);
262 	if (rt == NULL)
263 		goto unreach;
264 
265 	/*
266 	 * Handle cloning routes.
267 	 */
268 	if ((rt->rt_flags & ~ignore & (RTF_CLONING | RTF_PRCLONING)) != 0) {
269 		struct rtentry *clonedroute;
270 		int error;
271 
272 		clonedroute = rt;	/* copy in/copy out parameter */
273 		error = rtrequest(RTM_RESOLVE, dst, NULL, NULL, 0,
274 				  &clonedroute);	/* clone the route */
275 		if (error != 0) {	/* cloning failed */
276 			if (generate_report)
277 				rt_dstmsg(RTM_MISS, dst, error);
278 			rt->rt_refcnt++;
279 			return (rt);	/* return the uncloned route */
280 		}
281 		if (generate_report) {
282 			if (clonedroute->rt_flags & RTF_XRESOLVE)
283 				rt_dstmsg(RTM_RESOLVE, dst, 0);
284 			else
285 				rt_rtmsg(RTM_ADD, clonedroute,
286 					 clonedroute->rt_ifp, 0);
287 		}
288 		return (clonedroute);	/* return cloned route */
289 	}
290 
291 	/*
292 	 * Increment the reference count of the matched route and return.
293 	 */
294 	rt->rt_refcnt++;
295 	return (rt);
296 
297 unreach:
298 	rtstat.rts_unreach++;
299 	if (generate_report)
300 		rt_dstmsg(RTM_MISS, dst, 0);
301 	return (NULL);
302 }
303 
304 void
305 rtfree(struct rtentry *rt)
306 {
307 	KASSERT(rt->rt_refcnt > 0, ("rtfree: rt_refcnt %ld", rt->rt_refcnt));
308 
309 	--rt->rt_refcnt;
310 	if (rt->rt_refcnt == 0) {
311 		struct radix_node_head *rnh =
312 		    rt_tables[mycpuid][rt_key(rt)->sa_family];
313 
314 		if (rnh->rnh_close)
315 			rnh->rnh_close((struct radix_node *)rt, rnh);
316 		if (!(rt->rt_flags & RTF_UP)) {
317 			/* deallocate route */
318 			if (rt->rt_ifa != NULL)
319 				IFAFREE(rt->rt_ifa);
320 			if (rt->rt_parent != NULL)
321 				RTFREE(rt->rt_parent);	/* recursive call! */
322 			Free(rt_key(rt));
323 			Free(rt);
324 		}
325 	}
326 }
327 
328 static int
329 rtredirect_oncpu(struct sockaddr *dst, struct sockaddr *gateway,
330 		 struct sockaddr *netmask, int flags, struct sockaddr *src)
331 {
332 	struct rtentry *rt = NULL;
333 	struct rt_addrinfo rtinfo;
334 	struct ifaddr *ifa;
335 	u_long *stat = NULL;
336 	int error;
337 
338 	/* verify the gateway is directly reachable */
339 	if ((ifa = ifa_ifwithnet(gateway)) == NULL) {
340 		error = ENETUNREACH;
341 		goto out;
342 	}
343 
344 	/*
345 	 * If the redirect isn't from our current router for this destination,
346 	 * it's either old or wrong.
347 	 */
348 	if (!(flags & RTF_DONE) &&		/* XXX JH */
349 	    (rt = rtpurelookup(dst)) != NULL &&
350 	    (!sa_equal(src, rt->rt_gateway) || rt->rt_ifa != ifa)) {
351 		error = EINVAL;
352 		goto done;
353 	}
354 
355 	/*
356 	 * If it redirects us to ourselves, we have a routing loop,
357 	 * perhaps as a result of an interface going down recently.
358 	 */
359 	if (ifa_ifwithaddr(gateway)) {
360 		error = EHOSTUNREACH;
361 		goto done;
362 	}
363 
364 	/*
365 	 * Create a new entry if the lookup failed or if we got back
366 	 * a wildcard entry for the default route.  This is necessary
367 	 * for hosts which use routing redirects generated by smart
368 	 * gateways to dynamically build the routing tables.
369 	 */
370 	if (rt == NULL)
371 		goto create;
372 	if ((rt_mask(rt) != NULL && rt_mask(rt)->sa_len < 2)) {
373 		rtfree(rt);
374 		goto create;
375 	}
376 
377 	/* Ignore redirects for directly connected hosts. */
378 	if (!(rt->rt_flags & RTF_GATEWAY)) {
379 		error = EHOSTUNREACH;
380 		goto done;
381 	}
382 
383 	if (!(rt->rt_flags & RTF_HOST) && (flags & RTF_HOST)) {
384 		/*
385 		 * Changing from a network route to a host route.
386 		 * Create a new host route rather than smashing the
387 		 * network route.
388 		 */
389 create:
390 		flags |=  RTF_GATEWAY | RTF_DYNAMIC;
391 		bzero(&rtinfo, sizeof(struct rt_addrinfo));
392 		rtinfo.rti_info[RTAX_DST] = dst;
393 		rtinfo.rti_info[RTAX_GATEWAY] = gateway;
394 		rtinfo.rti_info[RTAX_NETMASK] = netmask;
395 		rtinfo.rti_flags = flags;
396 		rtinfo.rti_ifa = ifa;
397 		rt = NULL;	/* copy-in/copy-out parameter */
398 		error = rtrequest1(RTM_ADD, &rtinfo, &rt);
399 		if (rt != NULL)
400 			flags = rt->rt_flags;
401 		stat = &rtstat.rts_dynamic;
402 	} else {
403 		/*
404 		 * Smash the current notion of the gateway to this destination.
405 		 * Should check about netmask!!!
406 		 */
407 		rt->rt_flags |= RTF_MODIFIED;
408 		flags |= RTF_MODIFIED;
409 		rt_setgate(rt, rt_key(rt), gateway);
410 		error = 0;
411 		stat = &rtstat.rts_newgateway;
412 	}
413 
414 done:
415 	if (rt != NULL)
416 		rtfree(rt);
417 out:
418 	if (error != 0)
419 		rtstat.rts_badredirect++;
420 	else if (stat != NULL)
421 		(*stat)++;
422 
423 	return error;
424 }
425 
426 #ifdef SMP
427 
428 struct netmsg_rtredirect {
429 	struct lwkt_msg	lmsg;
430 	struct sockaddr *dst;
431 	struct sockaddr *gateway;
432 	struct sockaddr *netmask;
433 	int		flags;
434 	struct sockaddr *src;
435 };
436 
437 #endif
438 
439 /*
440  * Force a routing table entry to the specified
441  * destination to go through the given gateway.
442  * Normally called as a result of a routing redirect
443  * message from the network layer.
444  *
445  * N.B.: must be called at splnet
446  */
447 void
448 rtredirect(struct sockaddr *dst, struct sockaddr *gateway,
449 	   struct sockaddr *netmask, int flags, struct sockaddr *src)
450 {
451 	struct rt_addrinfo rtinfo;
452 	int error;
453 #ifdef SMP
454 	struct netmsg_rtredirect msg;
455 
456 	lwkt_initmsg(&msg.lmsg, &curthread->td_msgport, 0,
457 		     lwkt_cmd_func(rtredirect_msghandler), lwkt_cmd_op_none);
458 	msg.dst = dst;
459 	msg.gateway = gateway;
460 	msg.netmask = netmask;
461 	msg.flags = flags;
462 	msg.src = src;
463 	error = lwkt_domsg(rtable_portfn(0), &msg.lmsg);
464 #else
465 	error = rtredirect_oncpu(dst, gateway, netmask, flags, src);
466 #endif
467 	bzero(&rtinfo, sizeof(struct rt_addrinfo));
468 	rtinfo.rti_info[RTAX_DST] = dst;
469 	rtinfo.rti_info[RTAX_GATEWAY] = gateway;
470 	rtinfo.rti_info[RTAX_NETMASK] = netmask;
471 	rtinfo.rti_info[RTAX_AUTHOR] = src;
472 	rt_missmsg(RTM_REDIRECT, &rtinfo, flags, error);
473 }
474 
475 #ifdef SMP
476 
477 static int
478 rtredirect_msghandler(struct lwkt_msg *lmsg)
479 {
480 	struct netmsg_rtredirect *msg = (void *)lmsg;
481 	int nextcpu;
482 
483 	rtredirect_oncpu(msg->dst, msg->gateway, msg->netmask,
484 			 msg->flags, msg->src);
485 	nextcpu = mycpuid + 1;
486 	if (nextcpu < ncpus)
487 		lwkt_forwardmsg(rtable_portfn(nextcpu), &msg->lmsg);
488 	else
489 		lwkt_replymsg(&msg->lmsg, 0);
490 	return (0);
491 }
492 
493 #endif
494 
495 /*
496 * Routing table ioctl interface.
497 */
498 int
499 rtioctl(u_long req, caddr_t data, struct ucred *cred)
500 {
501 #ifdef INET
502 	/* Multicast goop, grrr... */
503 	return mrt_ioctl ? mrt_ioctl(req, data) : EOPNOTSUPP;
504 #else
505 	return ENXIO;
506 #endif
507 }
508 
509 struct ifaddr *
510 ifa_ifwithroute(int flags, struct sockaddr *dst, struct sockaddr *gateway)
511 {
512 	struct ifaddr *ifa;
513 
514 	if (!(flags & RTF_GATEWAY)) {
515 		/*
516 		 * If we are adding a route to an interface,
517 		 * and the interface is a point-to-point link,
518 		 * we should search for the destination
519 		 * as our clue to the interface.  Otherwise
520 		 * we can use the local address.
521 		 */
522 		ifa = NULL;
523 		if (flags & RTF_HOST) {
524 			ifa = ifa_ifwithdstaddr(dst);
525 		}
526 		if (ifa == NULL)
527 			ifa = ifa_ifwithaddr(gateway);
528 	} else {
529 		/*
530 		 * If we are adding a route to a remote net
531 		 * or host, the gateway may still be on the
532 		 * other end of a pt to pt link.
533 		 */
534 		ifa = ifa_ifwithdstaddr(gateway);
535 	}
536 	if (ifa == NULL)
537 		ifa = ifa_ifwithnet(gateway);
538 	if (ifa == NULL) {
539 		struct rtentry *rt;
540 
541 		rt = rtpurelookup(gateway);
542 		if (rt == NULL)
543 			return (NULL);
544 		rt->rt_refcnt--;
545 		if ((ifa = rt->rt_ifa) == NULL)
546 			return (NULL);
547 	}
548 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
549 		struct ifaddr *oldifa = ifa;
550 
551 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
552 		if (ifa == NULL)
553 			ifa = oldifa;
554 	}
555 	return (ifa);
556 }
557 
558 static int rt_fixdelete (struct radix_node *, void *);
559 static int rt_fixchange (struct radix_node *, void *);
560 
561 struct rtfc_arg {
562 	struct rtentry *rt0;
563 	struct radix_node_head *rnh;
564 };
565 
566 /*
567  * Set rtinfo->rti_ifa and rtinfo->rti_ifp.
568  */
569 int
570 rt_getifa(struct rt_addrinfo *rtinfo)
571 {
572 	struct sockaddr *gateway = rtinfo->rti_info[RTAX_GATEWAY];
573 	struct sockaddr *dst = rtinfo->rti_info[RTAX_DST];
574 	struct sockaddr *ifaaddr = rtinfo->rti_info[RTAX_IFA];
575 	int flags = rtinfo->rti_flags;
576 
577 	/*
578 	 * ifp may be specified by sockaddr_dl
579 	 * when protocol address is ambiguous.
580 	 */
581 	if (rtinfo->rti_ifp == NULL) {
582 		struct sockaddr *ifpaddr;
583 
584 		ifpaddr = rtinfo->rti_info[RTAX_IFP];
585 		if (ifpaddr != NULL && ifpaddr->sa_family == AF_LINK) {
586 			struct ifaddr *ifa;
587 
588 			ifa = ifa_ifwithnet(ifpaddr);
589 			if (ifa != NULL)
590 				rtinfo->rti_ifp = ifa->ifa_ifp;
591 		}
592 	}
593 
594 	if (rtinfo->rti_ifa == NULL && ifaaddr != NULL)
595 		rtinfo->rti_ifa = ifa_ifwithaddr(ifaaddr);
596 	if (rtinfo->rti_ifa == NULL) {
597 		struct sockaddr *sa;
598 
599 		sa = ifaaddr != NULL ? ifaaddr :
600 		    (gateway != NULL ? gateway : dst);
601 		if (sa != NULL && rtinfo->rti_ifp != NULL)
602 			rtinfo->rti_ifa = ifaof_ifpforaddr(sa, rtinfo->rti_ifp);
603 		else if (dst != NULL && gateway != NULL)
604 			rtinfo->rti_ifa = ifa_ifwithroute(flags, dst, gateway);
605 		else if (sa != NULL)
606 			rtinfo->rti_ifa = ifa_ifwithroute(flags, sa, sa);
607 	}
608 	if (rtinfo->rti_ifa == NULL)
609 		return (ENETUNREACH);
610 
611 	if (rtinfo->rti_ifp == NULL)
612 		rtinfo->rti_ifp = rtinfo->rti_ifa->ifa_ifp;
613 	return (0);
614 }
615 
616 /*
617  * Do appropriate manipulations of a routing tree given
618  * all the bits of info needed
619  */
620 int
621 rtrequest(
622 	int req,
623 	struct sockaddr *dst,
624 	struct sockaddr *gateway,
625 	struct sockaddr *netmask,
626 	int flags,
627 	struct rtentry **ret_nrt)
628 {
629 	struct rt_addrinfo rtinfo;
630 
631 	bzero(&rtinfo, sizeof(struct rt_addrinfo));
632 	rtinfo.rti_info[RTAX_DST] = dst;
633 	rtinfo.rti_info[RTAX_GATEWAY] = gateway;
634 	rtinfo.rti_info[RTAX_NETMASK] = netmask;
635 	rtinfo.rti_flags = flags;
636 	return rtrequest1(req, &rtinfo, ret_nrt);
637 }
638 
639 int
640 rtrequest_global(
641 	int req,
642 	struct sockaddr *dst,
643 	struct sockaddr *gateway,
644 	struct sockaddr *netmask,
645 	int flags)
646 {
647 	struct rt_addrinfo rtinfo;
648 
649 	bzero(&rtinfo, sizeof(struct rt_addrinfo));
650 	rtinfo.rti_info[RTAX_DST] = dst;
651 	rtinfo.rti_info[RTAX_GATEWAY] = gateway;
652 	rtinfo.rti_info[RTAX_NETMASK] = netmask;
653 	rtinfo.rti_flags = flags;
654 	return rtrequest1_global(req, &rtinfo, NULL, NULL);
655 }
656 
657 #ifdef SMP
658 
659 struct netmsg_rtq {
660 	struct lwkt_msg		lmsg;
661 	int			req;
662 	struct rt_addrinfo	*rtinfo;
663 	rtrequest1_callback_func_t callback;
664 	void			*arg;
665 };
666 
667 #endif
668 
669 int
670 rtrequest1_global(int req, struct rt_addrinfo *rtinfo,
671 		  rtrequest1_callback_func_t callback, void *arg)
672 {
673 	int error;
674 #ifdef SMP
675 	struct netmsg_rtq msg;
676 
677 	lwkt_initmsg(&msg.lmsg, &curthread->td_msgport, 0,
678 		     lwkt_cmd_func(rtrequest1_msghandler), lwkt_cmd_op_none);
679 	msg.lmsg.ms_error = -1;
680 	msg.req = req;
681 	msg.rtinfo = rtinfo;
682 	msg.callback = callback;
683 	msg.arg = arg;
684 	error = lwkt_domsg(rtable_portfn(0), &msg.lmsg);
685 #else
686 	struct rtentry *rt = NULL;
687 
688 	error = rtrequest1(req, rtinfo, &rt);
689 	if (rt)
690 		--rt->rt_refcnt;
691 	if (callback)
692 		callback(req, error, rtinfo, rt, arg);
693 #endif
694 	return (error);
695 }
696 
697 /*
698  * Handle a route table request on the current cpu.  Since the route table's
699  * are supposed to be identical on each cpu, an error occuring later in the
700  * message chain is considered system-fatal.
701  */
702 #ifdef SMP
703 
704 static int
705 rtrequest1_msghandler(struct lwkt_msg *lmsg)
706 {
707 	struct netmsg_rtq *msg = (void *)lmsg;
708 	struct rtentry *rt = NULL;
709 	int nextcpu;
710 	int error;
711 
712 	error = rtrequest1(msg->req, msg->rtinfo, &rt);
713 	if (rt)
714 		--rt->rt_refcnt;
715 	if (msg->callback)
716 		msg->callback(msg->req, error, msg->rtinfo, rt, msg->arg);
717 
718 	/*
719 	 * RTM_DELETE's are propogated even if an error occurs, since a
720 	 * cloned route might be undergoing deletion and cloned routes
721 	 * are not necessarily replicated.  An overall error is returned
722 	 * only if no cpus have the route in question.
723 	 */
724 	if (msg->lmsg.ms_error < 0 || error == 0)
725 		msg->lmsg.ms_error = error;
726 
727 	nextcpu = mycpuid + 1;
728 	if (error && msg->req != RTM_DELETE) {
729 		if (mycpuid != 0) {
730 			panic("rtrequest1_msghandler: rtrequest table "
731 			      "error was not on cpu #0: %p", msg->rtinfo);
732 		}
733 		lwkt_replymsg(&msg->lmsg, error);
734 	} else if (nextcpu < ncpus) {
735 		lwkt_forwardmsg(rtable_portfn(nextcpu), &msg->lmsg);
736 	} else {
737 		lwkt_replymsg(&msg->lmsg, msg->lmsg.ms_error);
738 	}
739 	return (0);
740 }
741 
742 #endif
743 
744 int
745 rtrequest1(int req, struct rt_addrinfo *rtinfo, struct rtentry **ret_nrt)
746 {
747 	struct sockaddr *dst = rtinfo->rti_info[RTAX_DST];
748 	struct rtentry *rt;
749 	struct radix_node *rn;
750 	struct radix_node_head *rnh;
751 	struct ifaddr *ifa;
752 	struct sockaddr *ndst;
753 	int error = 0;
754 
755 #define gotoerr(x) { error = x ; goto bad; }
756 
757 #ifdef ROUTE_DEBUG
758 	if (route_debug)
759 		rt_addrinfo_print(req, rtinfo);
760 #endif
761 
762 	crit_enter();
763 	/*
764 	 * Find the correct routing tree to use for this Address Family
765 	 */
766 	if ((rnh = rt_tables[mycpuid][dst->sa_family]) == NULL)
767 		gotoerr(EAFNOSUPPORT);
768 
769 	/*
770 	 * If we are adding a host route then we don't want to put
771 	 * a netmask in the tree, nor do we want to clone it.
772 	 */
773 	if (rtinfo->rti_flags & RTF_HOST) {
774 		rtinfo->rti_info[RTAX_NETMASK] = NULL;
775 		rtinfo->rti_flags &= ~(RTF_CLONING | RTF_PRCLONING);
776 	}
777 
778 	switch (req) {
779 	case RTM_DELETE:
780 		/* Remove the item from the tree. */
781 		rn = rnh->rnh_deladdr((char *)rtinfo->rti_info[RTAX_DST],
782 				      (char *)rtinfo->rti_info[RTAX_NETMASK],
783 				      rnh);
784 		if (rn == NULL)
785 			gotoerr(ESRCH);
786 		KASSERT(!(rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)),
787 			("rnh_deladdr returned flags 0x%x", rn->rn_flags));
788 		rt = (struct rtentry *)rn;
789 
790 		/* ref to prevent a deletion race */
791 		++rt->rt_refcnt;
792 
793 		/* Free any routes cloned from this one. */
794 		if ((rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) &&
795 		    rt_mask(rt) != NULL) {
796 			rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
797 					       (char *)rt_mask(rt),
798 					       rt_fixdelete, rt);
799 		}
800 
801 		if (rt->rt_gwroute != NULL) {
802 			RTFREE(rt->rt_gwroute);
803 			rt->rt_gwroute = NULL;
804 		}
805 
806 		/*
807 		 * NB: RTF_UP must be set during the search above,
808 		 * because we might delete the last ref, causing
809 		 * rt to get freed prematurely.
810 		 */
811 		rt->rt_flags &= ~RTF_UP;
812 
813 #ifdef ROUTE_DEBUG
814 		if (route_debug)
815 			rt_print(rtinfo, rt);
816 #endif
817 
818 		/* Give the protocol a chance to keep things in sync. */
819 		if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
820 			ifa->ifa_rtrequest(RTM_DELETE, rt, rtinfo);
821 
822 		/*
823 		 * If the caller wants it, then it can have it,
824 		 * but it's up to it to free the rtentry as we won't be
825 		 * doing it.
826 		 */
827 		KASSERT(rt->rt_refcnt >= 0,
828 			("rtrequest1(DELETE): refcnt %ld", rt->rt_refcnt));
829 		if (ret_nrt != NULL) {
830 			/* leave ref intact for return */
831 			*ret_nrt = rt;
832 		} else {
833 			/* deref / attempt to destroy */
834 			rtfree(rt);
835 		}
836 		break;
837 
838 	case RTM_RESOLVE:
839 		if (ret_nrt == NULL || (rt = *ret_nrt) == NULL)
840 			gotoerr(EINVAL);
841 		ifa = rt->rt_ifa;
842 		rtinfo->rti_flags =
843 		    rt->rt_flags & ~(RTF_CLONING | RTF_PRCLONING | RTF_STATIC);
844 		rtinfo->rti_flags |= RTF_WASCLONED;
845 		rtinfo->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
846 		if ((rtinfo->rti_info[RTAX_NETMASK] = rt->rt_genmask) == NULL)
847 			rtinfo->rti_flags |= RTF_HOST;
848 		goto makeroute;
849 
850 	case RTM_ADD:
851 		KASSERT(!(rtinfo->rti_flags & RTF_GATEWAY) ||
852 			rtinfo->rti_info[RTAX_GATEWAY] != NULL,
853 		    ("rtrequest: GATEWAY but no gateway"));
854 
855 		if (rtinfo->rti_ifa == NULL && (error = rt_getifa(rtinfo)))
856 			gotoerr(error);
857 		ifa = rtinfo->rti_ifa;
858 makeroute:
859 		R_Malloc(rt, struct rtentry *, sizeof(struct rtentry));
860 		if (rt == NULL)
861 			gotoerr(ENOBUFS);
862 		bzero(rt, sizeof(struct rtentry));
863 		rt->rt_flags = RTF_UP | rtinfo->rti_flags;
864 		error = rt_setgate(rt, dst, rtinfo->rti_info[RTAX_GATEWAY]);
865 		if (error != 0) {
866 			Free(rt);
867 			gotoerr(error);
868 		}
869 
870 		ndst = rt_key(rt);
871 		if (rtinfo->rti_info[RTAX_NETMASK] != NULL)
872 			rt_maskedcopy(dst, ndst,
873 				      rtinfo->rti_info[RTAX_NETMASK]);
874 		else
875 			bcopy(dst, ndst, dst->sa_len);
876 
877 		/*
878 		 * Note that we now have a reference to the ifa.
879 		 * This moved from below so that rnh->rnh_addaddr() can
880 		 * examine the ifa and  ifa->ifa_ifp if it so desires.
881 		 */
882 		IFAREF(ifa);
883 		rt->rt_ifa = ifa;
884 		rt->rt_ifp = ifa->ifa_ifp;
885 		/* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
886 
887 		rn = rnh->rnh_addaddr((char *)ndst,
888 				      (char *)rtinfo->rti_info[RTAX_NETMASK],
889 				      rnh, rt->rt_nodes);
890 		if (rn == NULL) {
891 			struct rtentry *oldrt;
892 
893 			/*
894 			 * We already have one of these in the tree.
895 			 * We do a special hack: if the old route was
896 			 * cloned, then we blow it away and try
897 			 * re-inserting the new one.
898 			 */
899 			oldrt = rtpurelookup(ndst);
900 			if (oldrt != NULL) {
901 				--oldrt->rt_refcnt;
902 				if (oldrt->rt_flags & RTF_WASCLONED) {
903 					rtrequest(RTM_DELETE, rt_key(oldrt),
904 						  oldrt->rt_gateway,
905 						  rt_mask(oldrt),
906 						  oldrt->rt_flags, NULL);
907 					rn = rnh->rnh_addaddr((char *)ndst,
908 					    (char *)
909 						rtinfo->rti_info[RTAX_NETMASK],
910 					    rnh, rt->rt_nodes);
911 				}
912 			}
913 		}
914 
915 		/*
916 		 * If it still failed to go into the tree,
917 		 * then un-make it (this should be a function).
918 		 */
919 		if (rn == NULL) {
920 			if (rt->rt_gwroute != NULL)
921 				rtfree(rt->rt_gwroute);
922 			IFAFREE(ifa);
923 			Free(rt_key(rt));
924 			Free(rt);
925 			gotoerr(EEXIST);
926 		}
927 
928 		/*
929 		 * If we got here from RESOLVE, then we are cloning
930 		 * so clone the rest, and note that we
931 		 * are a clone (and increment the parent's references)
932 		 */
933 		if (req == RTM_RESOLVE) {
934 			rt->rt_rmx = (*ret_nrt)->rt_rmx;    /* copy metrics */
935 			rt->rt_rmx.rmx_pksent = 0;  /* reset packet counter */
936 			if ((*ret_nrt)->rt_flags &
937 				       (RTF_CLONING | RTF_PRCLONING)) {
938 				rt->rt_parent = *ret_nrt;
939 				(*ret_nrt)->rt_refcnt++;
940 			}
941 		}
942 
943 		/*
944 		 * if this protocol has something to add to this then
945 		 * allow it to do that as well.
946 		 */
947 		if (ifa->ifa_rtrequest != NULL)
948 			ifa->ifa_rtrequest(req, rt, rtinfo);
949 
950 		/*
951 		 * We repeat the same procedure from rt_setgate() here because
952 		 * it doesn't fire when we call it there because the node
953 		 * hasn't been added to the tree yet.
954 		 */
955 		if (req == RTM_ADD && !(rt->rt_flags & RTF_HOST) &&
956 		    rt_mask(rt) != NULL) {
957 			struct rtfc_arg arg = { rt, rnh };
958 
959 			rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
960 					       (char *)rt_mask(rt),
961 					       rt_fixchange, &arg);
962 		}
963 
964 #ifdef ROUTE_DEBUG
965 		if (route_debug)
966 			rt_print(rtinfo, rt);
967 #endif
968 		/*
969 		 * Return the resulting rtentry,
970 		 * increasing the number of references by one.
971 		 */
972 		if (ret_nrt != NULL) {
973 			rt->rt_refcnt++;
974 			*ret_nrt = rt;
975 		}
976 		break;
977 	default:
978 		error = EOPNOTSUPP;
979 	}
980 bad:
981 #ifdef ROUTE_DEBUG
982 	if (route_debug) {
983 		if (error)
984 			kprintf("rti %p failed error %d\n", rtinfo, error);
985 		else
986 			kprintf("rti %p succeeded\n", rtinfo);
987 	}
988 #endif
989 	crit_exit();
990 	return (error);
991 }
992 
993 /*
994  * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
995  * (i.e., the routes related to it by the operation of cloning).  This
996  * routine is iterated over all potential former-child-routes by way of
997  * rnh->rnh_walktree_from() above, and those that actually are children of
998  * the late parent (passed in as VP here) are themselves deleted.
999  */
1000 static int
1001 rt_fixdelete(struct radix_node *rn, void *vp)
1002 {
1003 	struct rtentry *rt = (struct rtentry *)rn;
1004 	struct rtentry *rt0 = vp;
1005 
1006 	if (rt->rt_parent == rt0 &&
1007 	    !(rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1008 		return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1009 				 rt->rt_flags, NULL);
1010 	}
1011 	return 0;
1012 }
1013 
1014 /*
1015  * This routine is called from rt_setgate() to do the analogous thing for
1016  * adds and changes.  There is the added complication in this case of a
1017  * middle insert; i.e., insertion of a new network route between an older
1018  * network route and (cloned) host routes.  For this reason, a simple check
1019  * of rt->rt_parent is insufficient; each candidate route must be tested
1020  * against the (mask, value) of the new route (passed as before in vp)
1021  * to see if the new route matches it.
1022  *
1023  * XXX - it may be possible to do fixdelete() for changes and reserve this
1024  * routine just for adds.  I'm not sure why I thought it was necessary to do
1025  * changes this way.
1026  */
1027 #ifdef DEBUG
1028 static int rtfcdebug = 0;
1029 #endif
1030 
1031 static int
1032 rt_fixchange(struct radix_node *rn, void *vp)
1033 {
1034 	struct rtentry *rt = (struct rtentry *)rn;
1035 	struct rtfc_arg *ap = vp;
1036 	struct rtentry *rt0 = ap->rt0;
1037 	struct radix_node_head *rnh = ap->rnh;
1038 	u_char *xk1, *xm1, *xk2, *xmp;
1039 	int i, len, mlen;
1040 
1041 #ifdef DEBUG
1042 	if (rtfcdebug)
1043 		kprintf("rt_fixchange: rt %p, rt0 %p\n", rt, rt0);
1044 #endif
1045 
1046 	if (rt->rt_parent == NULL ||
1047 	    (rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1048 #ifdef DEBUG
1049 		if (rtfcdebug) kprintf("no parent, pinned or cloning\n");
1050 #endif
1051 		return 0;
1052 	}
1053 
1054 	if (rt->rt_parent == rt0) {
1055 #ifdef DEBUG
1056 		if (rtfcdebug) kprintf("parent match\n");
1057 #endif
1058 		return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1059 				 rt->rt_flags, NULL);
1060 	}
1061 
1062 	/*
1063 	 * There probably is a function somewhere which does this...
1064 	 * if not, there should be.
1065 	 */
1066 	len = imin(rt_key(rt0)->sa_len, rt_key(rt)->sa_len);
1067 
1068 	xk1 = (u_char *)rt_key(rt0);
1069 	xm1 = (u_char *)rt_mask(rt0);
1070 	xk2 = (u_char *)rt_key(rt);
1071 
1072 	/* avoid applying a less specific route */
1073 	xmp = (u_char *)rt_mask(rt->rt_parent);
1074 	mlen = rt_key(rt->rt_parent)->sa_len;
1075 	if (mlen > rt_key(rt0)->sa_len) {
1076 #ifdef DEBUG
1077 		if (rtfcdebug)
1078 			kprintf("rt_fixchange: inserting a less "
1079 			       "specific route\n");
1080 #endif
1081 		return 0;
1082 	}
1083 	for (i = rnh->rnh_treetop->rn_offset; i < mlen; i++) {
1084 		if ((xmp[i] & ~(xmp[i] ^ xm1[i])) != xmp[i]) {
1085 #ifdef DEBUG
1086 			if (rtfcdebug)
1087 				kprintf("rt_fixchange: inserting a less "
1088 				       "specific route\n");
1089 #endif
1090 			return 0;
1091 		}
1092 	}
1093 
1094 	for (i = rnh->rnh_treetop->rn_offset; i < len; i++) {
1095 		if ((xk2[i] & xm1[i]) != xk1[i]) {
1096 #ifdef DEBUG
1097 			if (rtfcdebug) kprintf("no match\n");
1098 #endif
1099 			return 0;
1100 		}
1101 	}
1102 
1103 	/*
1104 	 * OK, this node is a clone, and matches the node currently being
1105 	 * changed/added under the node's mask.  So, get rid of it.
1106 	 */
1107 #ifdef DEBUG
1108 	if (rtfcdebug) kprintf("deleting\n");
1109 #endif
1110 	return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1111 			 rt->rt_flags, NULL);
1112 }
1113 
1114 #define ROUNDUP(a) (a>0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
1115 
1116 int
1117 rt_setgate(struct rtentry *rt0, struct sockaddr *dst, struct sockaddr *gate)
1118 {
1119 	char *space, *oldspace;
1120 	int dlen = ROUNDUP(dst->sa_len), glen = ROUNDUP(gate->sa_len);
1121 	struct rtentry *rt = rt0;
1122 	struct radix_node_head *rnh = rt_tables[mycpuid][dst->sa_family];
1123 
1124 	/*
1125 	 * A host route with the destination equal to the gateway
1126 	 * will interfere with keeping LLINFO in the routing
1127 	 * table, so disallow it.
1128 	 */
1129 	if (((rt0->rt_flags & (RTF_HOST | RTF_GATEWAY | RTF_LLINFO)) ==
1130 			      (RTF_HOST | RTF_GATEWAY)) &&
1131 	    dst->sa_len == gate->sa_len &&
1132 	    sa_equal(dst, gate)) {
1133 		/*
1134 		 * The route might already exist if this is an RTM_CHANGE
1135 		 * or a routing redirect, so try to delete it.
1136 		 */
1137 		if (rt_key(rt0) != NULL)
1138 			rtrequest(RTM_DELETE, rt_key(rt0), rt0->rt_gateway,
1139 				  rt_mask(rt0), rt0->rt_flags, NULL);
1140 		return EADDRNOTAVAIL;
1141 	}
1142 
1143 	/*
1144 	 * Both dst and gateway are stored in the same malloc'ed chunk
1145 	 * (If I ever get my hands on....)
1146 	 * if we need to malloc a new chunk, then keep the old one around
1147 	 * till we don't need it any more.
1148 	 */
1149 	if (rt->rt_gateway == NULL || glen > ROUNDUP(rt->rt_gateway->sa_len)) {
1150 		oldspace = (char *)rt_key(rt);
1151 		R_Malloc(space, char *, dlen + glen);
1152 		if (space == NULL)
1153 			return ENOBUFS;
1154 		rt->rt_nodes->rn_key = space;
1155 	} else {
1156 		space = (char *)rt_key(rt);	/* Just use the old space. */
1157 		oldspace = NULL;
1158 	}
1159 
1160 	/* Set the gateway value. */
1161 	rt->rt_gateway = (struct sockaddr *)(space + dlen);
1162 	bcopy(gate, rt->rt_gateway, glen);
1163 
1164 	if (oldspace != NULL) {
1165 		/*
1166 		 * If we allocated a new chunk, preserve the original dst.
1167 		 * This way, rt_setgate() really just sets the gate
1168 		 * and leaves the dst field alone.
1169 		 */
1170 		bcopy(dst, space, dlen);
1171 		Free(oldspace);
1172 	}
1173 
1174 	/*
1175 	 * If there is already a gwroute, it's now almost definitely wrong
1176 	 * so drop it.
1177 	 */
1178 	if (rt->rt_gwroute != NULL) {
1179 		RTFREE(rt->rt_gwroute);
1180 		rt->rt_gwroute = NULL;
1181 	}
1182 	if (rt->rt_flags & RTF_GATEWAY) {
1183 		/*
1184 		 * Cloning loop avoidance: In the presence of
1185 		 * protocol-cloning and bad configuration, it is
1186 		 * possible to get stuck in bottomless mutual recursion
1187 		 * (rtrequest rt_setgate rtlookup).  We avoid this
1188 		 * by not allowing protocol-cloning to operate for
1189 		 * gateways (which is probably the correct choice
1190 		 * anyway), and avoid the resulting reference loops
1191 		 * by disallowing any route to run through itself as
1192 		 * a gateway.  This is obviously mandatory when we
1193 		 * get rt->rt_output().
1194 		 *
1195 		 * This breaks TTCP for hosts outside the gateway!  XXX JH
1196 		 */
1197 		rt->rt_gwroute = _rtlookup(gate, RTL_REPORTMSG, RTF_PRCLONING);
1198 		if (rt->rt_gwroute == rt) {
1199 			rt->rt_gwroute = NULL;
1200 			--rt->rt_refcnt;
1201 			return EDQUOT; /* failure */
1202 		}
1203 	}
1204 
1205 	/*
1206 	 * This isn't going to do anything useful for host routes, so
1207 	 * don't bother.  Also make sure we have a reasonable mask
1208 	 * (we don't yet have one during adds).
1209 	 */
1210 	if (!(rt->rt_flags & RTF_HOST) && rt_mask(rt) != NULL) {
1211 		struct rtfc_arg arg = { rt, rnh };
1212 
1213 		rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
1214 				       (char *)rt_mask(rt),
1215 				       rt_fixchange, &arg);
1216 	}
1217 
1218 	return 0;
1219 }
1220 
1221 static void
1222 rt_maskedcopy(
1223 	struct sockaddr *src,
1224 	struct sockaddr *dst,
1225 	struct sockaddr *netmask)
1226 {
1227 	u_char *cp1 = (u_char *)src;
1228 	u_char *cp2 = (u_char *)dst;
1229 	u_char *cp3 = (u_char *)netmask;
1230 	u_char *cplim = cp2 + *cp3;
1231 	u_char *cplim2 = cp2 + *cp1;
1232 
1233 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1234 	cp3 += 2;
1235 	if (cplim > cplim2)
1236 		cplim = cplim2;
1237 	while (cp2 < cplim)
1238 		*cp2++ = *cp1++ & *cp3++;
1239 	if (cp2 < cplim2)
1240 		bzero(cp2, cplim2 - cp2);
1241 }
1242 
1243 int
1244 rt_llroute(struct sockaddr *dst, struct rtentry *rt0, struct rtentry **drt)
1245 {
1246 	struct rtentry *up_rt, *rt;
1247 
1248 	if (!(rt0->rt_flags & RTF_UP)) {
1249 		up_rt = rtlookup(dst);
1250 		if (up_rt == NULL)
1251 			return (EHOSTUNREACH);
1252 		up_rt->rt_refcnt--;
1253 	} else
1254 		up_rt = rt0;
1255 	if (up_rt->rt_flags & RTF_GATEWAY) {
1256 		if (up_rt->rt_gwroute == NULL) {
1257 			up_rt->rt_gwroute = rtlookup(up_rt->rt_gateway);
1258 			if (up_rt->rt_gwroute == NULL)
1259 				return (EHOSTUNREACH);
1260 		} else if (!(up_rt->rt_gwroute->rt_flags & RTF_UP)) {
1261 			rtfree(up_rt->rt_gwroute);
1262 			up_rt->rt_gwroute = rtlookup(up_rt->rt_gateway);
1263 			if (up_rt->rt_gwroute == NULL)
1264 				return (EHOSTUNREACH);
1265 		}
1266 		rt = up_rt->rt_gwroute;
1267 	} else
1268 		rt = up_rt;
1269 	if (rt->rt_flags & RTF_REJECT &&
1270 	    (rt->rt_rmx.rmx_expire == 0 ||		/* rt doesn't expire */
1271 	     time_second < rt->rt_rmx.rmx_expire))	/* rt not expired */
1272 		return (rt->rt_flags & RTF_HOST ?  EHOSTDOWN : EHOSTUNREACH);
1273 	*drt = rt;
1274 	return 0;
1275 }
1276 
1277 #ifdef ROUTE_DEBUG
1278 
1279 /*
1280  * Print out a route table entry
1281  */
1282 void
1283 rt_print(struct rt_addrinfo *rtinfo, struct rtentry *rn)
1284 {
1285 	kprintf("rti %p cpu %d route %p flags %08lx: ",
1286 		rtinfo, mycpuid, rn, rn->rt_flags);
1287 	sockaddr_print(rt_key(rn));
1288 	kprintf(" mask ");
1289 	sockaddr_print(rt_mask(rn));
1290 	kprintf(" gw ");
1291 	sockaddr_print(rn->rt_gateway);
1292 	kprintf(" ifc \"%s\"", rn->rt_ifp ? rn->rt_ifp->if_dname : "?");
1293 	kprintf(" ifa %p\n", rn->rt_ifa);
1294 }
1295 
1296 void
1297 rt_addrinfo_print(int cmd, struct rt_addrinfo *rti)
1298 {
1299 	int didit = 0;
1300 	int i;
1301 
1302 #ifdef ROUTE_DEBUG
1303 	if (cmd == RTM_DELETE && route_debug > 1)
1304 		db_print_backtrace();
1305 #endif
1306 
1307 	switch(cmd) {
1308 	case RTM_ADD:
1309 		kprintf("ADD ");
1310 		break;
1311 	case RTM_RESOLVE:
1312 		kprintf("RES ");
1313 		break;
1314 	case RTM_DELETE:
1315 		kprintf("DEL ");
1316 		break;
1317 	default:
1318 		kprintf("C%02d ", cmd);
1319 		break;
1320 	}
1321 	kprintf("rti %p cpu %d ", rti, mycpuid);
1322 	for (i = 0; i < rti->rti_addrs; ++i) {
1323 		if (rti->rti_info[i] == NULL)
1324 			continue;
1325 		if (didit)
1326 			kprintf(" ,");
1327 		switch(i) {
1328 		case RTAX_DST:
1329 			kprintf("(DST ");
1330 			break;
1331 		case RTAX_GATEWAY:
1332 			kprintf("(GWY ");
1333 			break;
1334 		case RTAX_NETMASK:
1335 			kprintf("(MSK ");
1336 			break;
1337 		case RTAX_GENMASK:
1338 			kprintf("(GEN ");
1339 			break;
1340 		case RTAX_IFP:
1341 			kprintf("(IFP ");
1342 			break;
1343 		case RTAX_IFA:
1344 			kprintf("(IFA ");
1345 			break;
1346 		case RTAX_AUTHOR:
1347 			kprintf("(AUT ");
1348 			break;
1349 		case RTAX_BRD:
1350 			kprintf("(BRD ");
1351 			break;
1352 		default:
1353 			kprintf("(?%02d ", i);
1354 			break;
1355 		}
1356 		sockaddr_print(rti->rti_info[i]);
1357 		kprintf(")");
1358 		didit = 1;
1359 	}
1360 	kprintf("\n");
1361 }
1362 
1363 void
1364 sockaddr_print(struct sockaddr *sa)
1365 {
1366 	struct sockaddr_in *sa4;
1367 	struct sockaddr_in6 *sa6;
1368 	int len;
1369 	int i;
1370 
1371 	if (sa == NULL) {
1372 		kprintf("NULL");
1373 		return;
1374 	}
1375 
1376 	len = sa->sa_len - offsetof(struct sockaddr, sa_data[0]);
1377 
1378 	switch(sa->sa_family) {
1379 	case AF_INET:
1380 	case AF_INET6:
1381 	default:
1382 		switch(sa->sa_family) {
1383 		case AF_INET:
1384 			sa4 = (struct sockaddr_in *)sa;
1385 			kprintf("INET %d %d.%d.%d.%d",
1386 				ntohs(sa4->sin_port),
1387 				(ntohl(sa4->sin_addr.s_addr) >> 24) & 255,
1388 				(ntohl(sa4->sin_addr.s_addr) >> 16) & 255,
1389 				(ntohl(sa4->sin_addr.s_addr) >> 8) & 255,
1390 				(ntohl(sa4->sin_addr.s_addr) >> 0) & 255
1391 			);
1392 			break;
1393 		case AF_INET6:
1394 			sa6 = (struct sockaddr_in6 *)sa;
1395 			kprintf("INET6 %d %04x:%04x%04x:%04x:%04x:%04x:%04x:%04x",
1396 				ntohs(sa6->sin6_port),
1397 				sa6->sin6_addr.s6_addr16[0],
1398 				sa6->sin6_addr.s6_addr16[1],
1399 				sa6->sin6_addr.s6_addr16[2],
1400 				sa6->sin6_addr.s6_addr16[3],
1401 				sa6->sin6_addr.s6_addr16[4],
1402 				sa6->sin6_addr.s6_addr16[5],
1403 				sa6->sin6_addr.s6_addr16[6],
1404 				sa6->sin6_addr.s6_addr16[7]
1405 			);
1406 			break;
1407 		default:
1408 			kprintf("AF%d ", sa->sa_family);
1409 			while (len > 0 && sa->sa_data[len-1] == 0)
1410 				--len;
1411 
1412 			for (i = 0; i < len; ++i) {
1413 				if (i)
1414 					kprintf(".");
1415 				kprintf("%d", (unsigned char)sa->sa_data[i]);
1416 			}
1417 			break;
1418 		}
1419 	}
1420 }
1421 
1422 #endif
1423 
1424 /*
1425  * Set up a routing table entry, normally for an interface.
1426  */
1427 int
1428 rtinit(struct ifaddr *ifa, int cmd, int flags)
1429 {
1430 	struct sockaddr *dst, *deldst, *netmask;
1431 	struct mbuf *m = NULL;
1432 	struct radix_node_head *rnh;
1433 	struct radix_node *rn;
1434 	struct rt_addrinfo rtinfo;
1435 	int error;
1436 
1437 	if (flags & RTF_HOST) {
1438 		dst = ifa->ifa_dstaddr;
1439 		netmask = NULL;
1440 	} else {
1441 		dst = ifa->ifa_addr;
1442 		netmask = ifa->ifa_netmask;
1443 	}
1444 	/*
1445 	 * If it's a delete, check that if it exists, it's on the correct
1446 	 * interface or we might scrub a route to another ifa which would
1447 	 * be confusing at best and possibly worse.
1448 	 */
1449 	if (cmd == RTM_DELETE) {
1450 		/*
1451 		 * It's a delete, so it should already exist..
1452 		 * If it's a net, mask off the host bits
1453 		 * (Assuming we have a mask)
1454 		 */
1455 		if (netmask != NULL) {
1456 			m = m_get(MB_DONTWAIT, MT_SONAME);
1457 			if (m == NULL)
1458 				return (ENOBUFS);
1459 			deldst = mtod(m, struct sockaddr *);
1460 			rt_maskedcopy(dst, deldst, netmask);
1461 			dst = deldst;
1462 		}
1463 		/*
1464 		 * Look up an rtentry that is in the routing tree and
1465 		 * contains the correct info.
1466 		 */
1467 		if ((rnh = rt_tables[mycpuid][dst->sa_family]) == NULL ||
1468 		    (rn = rnh->rnh_lookup((char *)dst,
1469 					  (char *)netmask, rnh)) == NULL ||
1470 		    ((struct rtentry *)rn)->rt_ifa != ifa ||
1471 		    !sa_equal((struct sockaddr *)rn->rn_key, dst)) {
1472 			if (m != NULL)
1473 				m_free(m);
1474 			return (flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1475 		}
1476 		/* XXX */
1477 #if 0
1478 		else {
1479 			/*
1480 			 * One would think that as we are deleting, and we know
1481 			 * it doesn't exist, we could just return at this point
1482 			 * with an "ELSE" clause, but apparently not..
1483 			 */
1484 			return (flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1485 		}
1486 #endif
1487 	}
1488 	/*
1489 	 * Do the actual request
1490 	 */
1491 	bzero(&rtinfo, sizeof(struct rt_addrinfo));
1492 	rtinfo.rti_info[RTAX_DST] = dst;
1493 	rtinfo.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1494 	rtinfo.rti_info[RTAX_NETMASK] = netmask;
1495 	rtinfo.rti_flags = flags | ifa->ifa_flags;
1496 	rtinfo.rti_ifa = ifa;
1497 	error = rtrequest1_global(cmd, &rtinfo, rtinit_rtrequest_callback, ifa);
1498 	if (m != NULL)
1499 		m_free(m);
1500 	return (error);
1501 }
1502 
1503 static void
1504 rtinit_rtrequest_callback(int cmd, int error,
1505 			  struct rt_addrinfo *rtinfo, struct rtentry *rt,
1506 			  void *arg)
1507 {
1508 	struct ifaddr *ifa = arg;
1509 
1510 	if (error == 0 && rt) {
1511 		if (mycpuid == 0) {
1512 			++rt->rt_refcnt;
1513 			rt_newaddrmsg(cmd, ifa, error, rt);
1514 			--rt->rt_refcnt;
1515 		}
1516 		if (cmd == RTM_DELETE) {
1517 			if (rt->rt_refcnt == 0) {
1518 				++rt->rt_refcnt;
1519 				rtfree(rt);
1520 			}
1521 		}
1522 	}
1523 }
1524 
1525 /* This must be before ip6_init2(), which is now SI_ORDER_MIDDLE */
1526 SYSINIT(route, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
1527