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