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