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