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