Merge branch 'master' of git://venus/dragonfly
[dragonfly.git] / sys / net / route.c
1 /*
2  * Copyright (c) 2004, 2005 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Jeffrey M. Hsu.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of The DragonFly Project nor the names of its
16  *    contributors may be used to endorse or promote products derived
17  *    from this software without specific, prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 /*
34  * Copyright (c) 1980, 1986, 1991, 1993
35  *      The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *      This product includes software developed by the University of
48  *      California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *      @(#)route.c     8.3 (Berkeley) 1/9/95
66  * $FreeBSD: src/sys/net/route.c,v 1.59.2.10 2003/01/17 08:04:00 ru Exp $
67  * $DragonFly: src/sys/net/route.c,v 1.41 2008/11/09 10:50:15 sephe Exp $
68  */
69
70 #include "opt_inet.h"
71 #include "opt_mpls.h"
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/socket.h>
78 #include <sys/domain.h>
79 #include <sys/kernel.h>
80 #include <sys/sysctl.h>
81 #include <sys/globaldata.h>
82 #include <sys/thread.h>
83
84 #include <net/if.h>
85 #include <net/route.h>
86 #include <net/netisr.h>
87
88 #include <netinet/in.h>
89 #include <net/ip_mroute/ip_mroute.h>
90
91 #include <sys/thread2.h>
92 #include <sys/msgport2.h>
93 #include <net/netmsg2.h>
94
95 #ifdef MPLS
96 #include <netproto/mpls/mpls.h>
97 #endif
98
99 static struct rtstatistics rtstatistics_percpu[MAXCPU];
100 #ifdef SMP
101 #define rtstat  rtstatistics_percpu[mycpuid]
102 #else
103 #define rtstat  rtstatistics_percpu[0]
104 #endif
105
106 struct radix_node_head *rt_tables[MAXCPU][AF_MAX+1];
107 struct lwkt_port *rt_ports[MAXCPU];
108
109 static void     rt_maskedcopy (struct sockaddr *, struct sockaddr *,
110                                struct sockaddr *);
111 static void rtable_init(void);
112 static void rtable_service_loop(void *dummy);
113 static void rtinit_rtrequest_callback(int, int, struct rt_addrinfo *,
114                                       struct rtentry *, void *);
115
116 #ifdef SMP
117 static void rtredirect_msghandler(struct netmsg *netmsg);
118 static void rtrequest1_msghandler(struct netmsg *netmsg);
119 #endif
120 static void rtsearch_msghandler(struct netmsg *netmsg);
121
122 static void rtmask_add_msghandler(struct netmsg *netmsg);
123
124 static int rt_setshims(struct rtentry *, struct sockaddr **);
125
126 SYSCTL_NODE(_net, OID_AUTO, route, CTLFLAG_RW, 0, "Routing");
127
128 #ifdef ROUTE_DEBUG
129 static int route_debug = 1;
130 SYSCTL_INT(_net_route, OID_AUTO, route_debug, CTLFLAG_RW,
131            &route_debug, 0, "");
132 #endif
133
134 int route_assert_owner_access = 0;
135 SYSCTL_INT(_net_route, OID_AUTO, assert_owner_access, CTLFLAG_RW,
136            &route_assert_owner_access, 0, "");
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                 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
478                 /* We only need to report rtmsg on CPU0 */
479                 rt_setgate(rt, rt_key(rt), gateway,
480                            mycpuid == 0 ? RTL_REPORTMSG : RTL_DONTREPORT);
481                 error = 0;
482                 stat = &rtstat.rts_newgateway;
483         }
484
485 done:
486         if (rt != NULL)
487                 rtfree(rt);
488 out:
489         if (error != 0)
490                 rtstat.rts_badredirect++;
491         else if (stat != NULL)
492                 (*stat)++;
493
494         return error;
495 }
496
497 #ifdef SMP
498
499 struct netmsg_rtredirect {
500         struct netmsg   netmsg;
501         struct sockaddr *dst;
502         struct sockaddr *gateway;
503         struct sockaddr *netmask;
504         int             flags;
505         struct sockaddr *src;
506 };
507
508 #endif
509
510 /*
511  * Force a routing table entry to the specified
512  * destination to go through the given gateway.
513  * Normally called as a result of a routing redirect
514  * message from the network layer.
515  *
516  * N.B.: must be called at splnet
517  */
518 void
519 rtredirect(struct sockaddr *dst, struct sockaddr *gateway,
520            struct sockaddr *netmask, int flags, struct sockaddr *src)
521 {
522         struct rt_addrinfo rtinfo;
523         int error;
524 #ifdef SMP
525         struct netmsg_rtredirect msg;
526
527         netmsg_init(&msg.netmsg, &curthread->td_msgport, 0,
528                     rtredirect_msghandler);
529         msg.dst = dst;
530         msg.gateway = gateway;
531         msg.netmask = netmask;
532         msg.flags = flags;
533         msg.src = src;
534         error = lwkt_domsg(rtable_portfn(0), &msg.netmsg.nm_lmsg, 0);
535 #else
536         error = rtredirect_oncpu(dst, gateway, netmask, flags, src);
537 #endif
538         bzero(&rtinfo, sizeof(struct rt_addrinfo));
539         rtinfo.rti_info[RTAX_DST] = dst;
540         rtinfo.rti_info[RTAX_GATEWAY] = gateway;
541         rtinfo.rti_info[RTAX_NETMASK] = netmask;
542         rtinfo.rti_info[RTAX_AUTHOR] = src;
543         rt_missmsg(RTM_REDIRECT, &rtinfo, flags, error);
544 }
545
546 #ifdef SMP
547
548 static void
549 rtredirect_msghandler(struct netmsg *netmsg)
550 {
551         struct netmsg_rtredirect *msg = (void *)netmsg;
552         int nextcpu;
553
554         rtredirect_oncpu(msg->dst, msg->gateway, msg->netmask,
555                          msg->flags, msg->src);
556         nextcpu = mycpuid + 1;
557         if (nextcpu < ncpus)
558                 lwkt_forwardmsg(rtable_portfn(nextcpu), &netmsg->nm_lmsg);
559         else
560                 lwkt_replymsg(&netmsg->nm_lmsg, 0);
561 }
562
563 #endif
564
565 /*
566 * Routing table ioctl interface.
567 */
568 int
569 rtioctl(u_long req, caddr_t data, struct ucred *cred)
570 {
571 #ifdef INET
572         /* Multicast goop, grrr... */
573         return mrt_ioctl ? mrt_ioctl(req, data) : EOPNOTSUPP;
574 #else
575         return ENXIO;
576 #endif
577 }
578
579 struct ifaddr *
580 ifa_ifwithroute(int flags, struct sockaddr *dst, struct sockaddr *gateway)
581 {
582         struct ifaddr *ifa;
583
584         if (!(flags & RTF_GATEWAY)) {
585                 /*
586                  * If we are adding a route to an interface,
587                  * and the interface is a point-to-point link,
588                  * we should search for the destination
589                  * as our clue to the interface.  Otherwise
590                  * we can use the local address.
591                  */
592                 ifa = NULL;
593                 if (flags & RTF_HOST) {
594                         ifa = ifa_ifwithdstaddr(dst);
595                 }
596                 if (ifa == NULL)
597                         ifa = ifa_ifwithaddr(gateway);
598         } else {
599                 /*
600                  * If we are adding a route to a remote net
601                  * or host, the gateway may still be on the
602                  * other end of a pt to pt link.
603                  */
604                 ifa = ifa_ifwithdstaddr(gateway);
605         }
606         if (ifa == NULL)
607                 ifa = ifa_ifwithnet(gateway);
608         if (ifa == NULL) {
609                 struct rtentry *rt;
610
611                 rt = rtpurelookup(gateway);
612                 if (rt == NULL)
613                         return (NULL);
614                 rt->rt_refcnt--;
615                 if ((ifa = rt->rt_ifa) == NULL)
616                         return (NULL);
617         }
618         if (ifa->ifa_addr->sa_family != dst->sa_family) {
619                 struct ifaddr *oldifa = ifa;
620
621                 ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
622                 if (ifa == NULL)
623                         ifa = oldifa;
624         }
625         return (ifa);
626 }
627
628 static int rt_fixdelete (struct radix_node *, void *);
629 static int rt_fixchange (struct radix_node *, void *);
630
631 struct rtfc_arg {
632         struct rtentry *rt0;
633         struct radix_node_head *rnh;
634 };
635
636 /*
637  * Set rtinfo->rti_ifa and rtinfo->rti_ifp.
638  */
639 int
640 rt_getifa(struct rt_addrinfo *rtinfo)
641 {
642         struct sockaddr *gateway = rtinfo->rti_info[RTAX_GATEWAY];
643         struct sockaddr *dst = rtinfo->rti_info[RTAX_DST];
644         struct sockaddr *ifaaddr = rtinfo->rti_info[RTAX_IFA];
645         int flags = rtinfo->rti_flags;
646
647         /*
648          * ifp may be specified by sockaddr_dl
649          * when protocol address is ambiguous.
650          */
651         if (rtinfo->rti_ifp == NULL) {
652                 struct sockaddr *ifpaddr;
653
654                 ifpaddr = rtinfo->rti_info[RTAX_IFP];
655                 if (ifpaddr != NULL && ifpaddr->sa_family == AF_LINK) {
656                         struct ifaddr *ifa;
657
658                         ifa = ifa_ifwithnet(ifpaddr);
659                         if (ifa != NULL)
660                                 rtinfo->rti_ifp = ifa->ifa_ifp;
661                 }
662         }
663
664         if (rtinfo->rti_ifa == NULL && ifaaddr != NULL)
665                 rtinfo->rti_ifa = ifa_ifwithaddr(ifaaddr);
666         if (rtinfo->rti_ifa == NULL) {
667                 struct sockaddr *sa;
668
669                 sa = ifaaddr != NULL ? ifaaddr :
670                     (gateway != NULL ? gateway : dst);
671                 if (sa != NULL && rtinfo->rti_ifp != NULL)
672                         rtinfo->rti_ifa = ifaof_ifpforaddr(sa, rtinfo->rti_ifp);
673                 else if (dst != NULL && gateway != NULL)
674                         rtinfo->rti_ifa = ifa_ifwithroute(flags, dst, gateway);
675                 else if (sa != NULL)
676                         rtinfo->rti_ifa = ifa_ifwithroute(flags, sa, sa);
677         }
678         if (rtinfo->rti_ifa == NULL)
679                 return (ENETUNREACH);
680
681         if (rtinfo->rti_ifp == NULL)
682                 rtinfo->rti_ifp = rtinfo->rti_ifa->ifa_ifp;
683         return (0);
684 }
685
686 /*
687  * Do appropriate manipulations of a routing tree given
688  * all the bits of info needed
689  */
690 int
691 rtrequest(
692         int req,
693         struct sockaddr *dst,
694         struct sockaddr *gateway,
695         struct sockaddr *netmask,
696         int flags,
697         struct rtentry **ret_nrt)
698 {
699         struct rt_addrinfo rtinfo;
700
701         bzero(&rtinfo, sizeof(struct rt_addrinfo));
702         rtinfo.rti_info[RTAX_DST] = dst;
703         rtinfo.rti_info[RTAX_GATEWAY] = gateway;
704         rtinfo.rti_info[RTAX_NETMASK] = netmask;
705         rtinfo.rti_flags = flags;
706         return rtrequest1(req, &rtinfo, ret_nrt);
707 }
708
709 int
710 rtrequest_global(
711         int req,
712         struct sockaddr *dst,
713         struct sockaddr *gateway,
714         struct sockaddr *netmask,
715         int flags)
716 {
717         struct rt_addrinfo rtinfo;
718
719         bzero(&rtinfo, sizeof(struct rt_addrinfo));
720         rtinfo.rti_info[RTAX_DST] = dst;
721         rtinfo.rti_info[RTAX_GATEWAY] = gateway;
722         rtinfo.rti_info[RTAX_NETMASK] = netmask;
723         rtinfo.rti_flags = flags;
724         return rtrequest1_global(req, &rtinfo, NULL, NULL);
725 }
726
727 #ifdef SMP
728
729 struct netmsg_rtq {
730         struct netmsg           netmsg;
731         int                     req;
732         struct rt_addrinfo      *rtinfo;
733         rtrequest1_callback_func_t callback;
734         void                    *arg;
735 };
736
737 #endif
738
739 int
740 rtrequest1_global(int req, struct rt_addrinfo *rtinfo, 
741                   rtrequest1_callback_func_t callback, void *arg)
742 {
743         int error;
744 #ifdef SMP
745         struct netmsg_rtq msg;
746
747         netmsg_init(&msg.netmsg, &curthread->td_msgport, 0,
748                     rtrequest1_msghandler);
749         msg.netmsg.nm_lmsg.ms_error = -1;
750         msg.req = req;
751         msg.rtinfo = rtinfo;
752         msg.callback = callback;
753         msg.arg = arg;
754         error = lwkt_domsg(rtable_portfn(0), &msg.netmsg.nm_lmsg, 0);
755 #else
756         struct rtentry *rt = NULL;
757
758         error = rtrequest1(req, rtinfo, &rt);
759         if (rt)
760                 --rt->rt_refcnt;
761         if (callback)
762                 callback(req, error, rtinfo, rt, arg);
763 #endif
764         return (error);
765 }
766
767 /*
768  * Handle a route table request on the current cpu.  Since the route table's
769  * are supposed to be identical on each cpu, an error occuring later in the
770  * message chain is considered system-fatal.
771  */
772 #ifdef SMP
773
774 static void
775 rtrequest1_msghandler(struct netmsg *netmsg)
776 {
777         struct netmsg_rtq *msg = (void *)netmsg;
778         struct rtentry *rt = NULL;
779         int nextcpu;
780         int error;
781
782         error = rtrequest1(msg->req, msg->rtinfo, &rt);
783         if (rt)
784                 --rt->rt_refcnt;
785         if (msg->callback)
786                 msg->callback(msg->req, error, msg->rtinfo, rt, msg->arg);
787
788         /*
789          * RTM_DELETE's are propogated even if an error occurs, since a
790          * cloned route might be undergoing deletion and cloned routes
791          * are not necessarily replicated.  An overall error is returned
792          * only if no cpus have the route in question.
793          */
794         if (msg->netmsg.nm_lmsg.ms_error < 0 || error == 0)
795                 msg->netmsg.nm_lmsg.ms_error = error;
796
797         nextcpu = mycpuid + 1;
798         if (error && msg->req != RTM_DELETE) {
799                 if (mycpuid != 0) {
800                         panic("rtrequest1_msghandler: rtrequest table "
801                               "error was not on cpu #0: %p", msg->rtinfo);
802                 }
803                 lwkt_replymsg(&msg->netmsg.nm_lmsg, error);
804         } else if (nextcpu < ncpus) {
805                 lwkt_forwardmsg(rtable_portfn(nextcpu), &msg->netmsg.nm_lmsg);
806         } else {
807                 lwkt_replymsg(&msg->netmsg.nm_lmsg,
808                               msg->netmsg.nm_lmsg.ms_error);
809         }
810 }
811
812 #endif
813
814 int
815 rtrequest1(int req, struct rt_addrinfo *rtinfo, struct rtentry **ret_nrt)
816 {
817         struct sockaddr *dst = rtinfo->rti_info[RTAX_DST];
818         struct rtentry *rt;
819         struct radix_node *rn;
820         struct radix_node_head *rnh;
821         struct ifaddr *ifa;
822         struct sockaddr *ndst;
823         boolean_t reportmsg;
824         int error = 0;
825
826 #define gotoerr(x) { error = x ; goto bad; }
827
828 #ifdef ROUTE_DEBUG
829         if (route_debug)
830                 rt_addrinfo_print(req, rtinfo);
831 #endif
832
833         crit_enter();
834         /*
835          * Find the correct routing tree to use for this Address Family
836          */
837         if ((rnh = rt_tables[mycpuid][dst->sa_family]) == NULL)
838                 gotoerr(EAFNOSUPPORT);
839
840         /*
841          * If we are adding a host route then we don't want to put
842          * a netmask in the tree, nor do we want to clone it.
843          */
844         if (rtinfo->rti_flags & RTF_HOST) {
845                 rtinfo->rti_info[RTAX_NETMASK] = NULL;
846                 rtinfo->rti_flags &= ~(RTF_CLONING | RTF_PRCLONING);
847         }
848
849         switch (req) {
850         case RTM_DELETE:
851                 /* Remove the item from the tree. */
852                 rn = rnh->rnh_deladdr((char *)rtinfo->rti_info[RTAX_DST],
853                                       (char *)rtinfo->rti_info[RTAX_NETMASK],
854                                       rnh);
855                 if (rn == NULL)
856                         gotoerr(ESRCH);
857                 KASSERT(!(rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)),
858                         ("rnh_deladdr returned flags 0x%x", rn->rn_flags));
859                 rt = (struct rtentry *)rn;
860
861                 /* ref to prevent a deletion race */
862                 ++rt->rt_refcnt;
863
864                 /* Free any routes cloned from this one. */
865                 if ((rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) &&
866                     rt_mask(rt) != NULL) {
867                         rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
868                                                (char *)rt_mask(rt),
869                                                rt_fixdelete, rt);
870                 }
871
872                 if (rt->rt_gwroute != NULL) {
873                         RTFREE(rt->rt_gwroute);
874                         rt->rt_gwroute = NULL;
875                 }
876
877                 /*
878                  * NB: RTF_UP must be set during the search above,
879                  * because we might delete the last ref, causing
880                  * rt to get freed prematurely.
881                  */
882                 rt->rt_flags &= ~RTF_UP;
883
884 #ifdef ROUTE_DEBUG
885                 if (route_debug)
886                         rt_print(rtinfo, rt);
887 #endif
888
889                 /* Give the protocol a chance to keep things in sync. */
890                 if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
891                         ifa->ifa_rtrequest(RTM_DELETE, rt, rtinfo);
892
893                 /*
894                  * If the caller wants it, then it can have it,
895                  * but it's up to it to free the rtentry as we won't be
896                  * doing it.
897                  */
898                 KASSERT(rt->rt_refcnt >= 0,
899                         ("rtrequest1(DELETE): refcnt %ld", rt->rt_refcnt));
900                 if (ret_nrt != NULL) {
901                         /* leave ref intact for return */
902                         *ret_nrt = rt;
903                 } else {
904                         /* deref / attempt to destroy */
905                         rtfree(rt);
906                 }
907                 break;
908
909         case RTM_RESOLVE:
910                 if (ret_nrt == NULL || (rt = *ret_nrt) == NULL)
911                         gotoerr(EINVAL);
912                 ifa = rt->rt_ifa;
913                 rtinfo->rti_flags =
914                     rt->rt_flags & ~(RTF_CLONING | RTF_PRCLONING | RTF_STATIC);
915                 rtinfo->rti_flags |= RTF_WASCLONED;
916                 rtinfo->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
917                 if ((rtinfo->rti_info[RTAX_NETMASK] = rt->rt_genmask) == NULL)
918                         rtinfo->rti_flags |= RTF_HOST;
919                 rtinfo->rti_info[RTAX_MPLS1] = rt->rt_shim[0];
920                 rtinfo->rti_info[RTAX_MPLS2] = rt->rt_shim[1];
921                 rtinfo->rti_info[RTAX_MPLS3] = rt->rt_shim[2];
922                 goto makeroute;
923
924         case RTM_ADD:
925                 KASSERT(!(rtinfo->rti_flags & RTF_GATEWAY) ||
926                         rtinfo->rti_info[RTAX_GATEWAY] != NULL,
927                     ("rtrequest: GATEWAY but no gateway"));
928
929                 if (rtinfo->rti_ifa == NULL && (error = rt_getifa(rtinfo)))
930                         gotoerr(error);
931                 ifa = rtinfo->rti_ifa;
932 makeroute:
933                 R_Malloc(rt, struct rtentry *, sizeof(struct rtentry));
934                 if (rt == NULL)
935                         gotoerr(ENOBUFS);
936                 bzero(rt, sizeof(struct rtentry));
937                 rt->rt_flags = RTF_UP | rtinfo->rti_flags;
938                 rt->rt_cpuid = mycpuid;
939
940                 if (mycpuid != 0 && req == RTM_ADD) {
941                         /* For RTM_ADD, we have already sent rtmsg on CPU0. */
942                         reportmsg = RTL_DONTREPORT;
943                 } else {
944                         /*
945                          * For RTM_ADD, we only send rtmsg on CPU0.
946                          * For RTM_RESOLVE, we always send rtmsg. XXX
947                          */
948                         reportmsg = RTL_REPORTMSG;
949                 }
950                 error = rt_setgate(rt, dst, rtinfo->rti_info[RTAX_GATEWAY],
951                                    reportmsg);
952                 if (error != 0) {
953                         Free(rt);
954                         gotoerr(error);
955                 }
956
957                 ndst = rt_key(rt);
958                 if (rtinfo->rti_info[RTAX_NETMASK] != NULL)
959                         rt_maskedcopy(dst, ndst,
960                                       rtinfo->rti_info[RTAX_NETMASK]);
961                 else
962                         bcopy(dst, ndst, dst->sa_len);
963
964                 if (rtinfo->rti_info[RTAX_MPLS1] != NULL)
965                         rt_setshims(rt, rtinfo->rti_info);
966
967                 /*
968                  * Note that we now have a reference to the ifa.
969                  * This moved from below so that rnh->rnh_addaddr() can
970                  * examine the ifa and  ifa->ifa_ifp if it so desires.
971                  */
972                 IFAREF(ifa);
973                 rt->rt_ifa = ifa;
974                 rt->rt_ifp = ifa->ifa_ifp;
975                 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
976
977                 rn = rnh->rnh_addaddr((char *)ndst,
978                                       (char *)rtinfo->rti_info[RTAX_NETMASK],
979                                       rnh, rt->rt_nodes);
980                 if (rn == NULL) {
981                         struct rtentry *oldrt;
982
983                         /*
984                          * We already have one of these in the tree.
985                          * We do a special hack: if the old route was
986                          * cloned, then we blow it away and try
987                          * re-inserting the new one.
988                          */
989                         oldrt = rtpurelookup(ndst);
990                         if (oldrt != NULL) {
991                                 --oldrt->rt_refcnt;
992                                 if (oldrt->rt_flags & RTF_WASCLONED) {
993                                         rtrequest(RTM_DELETE, rt_key(oldrt),
994                                                   oldrt->rt_gateway,
995                                                   rt_mask(oldrt),
996                                                   oldrt->rt_flags, NULL);
997                                         rn = rnh->rnh_addaddr((char *)ndst,
998                                             (char *)
999                                                 rtinfo->rti_info[RTAX_NETMASK],
1000                                             rnh, rt->rt_nodes);
1001                                 }
1002                         }
1003                 }
1004
1005                 /*
1006                  * If it still failed to go into the tree,
1007                  * then un-make it (this should be a function).
1008                  */
1009                 if (rn == NULL) {
1010                         if (rt->rt_gwroute != NULL)
1011                                 rtfree(rt->rt_gwroute);
1012                         IFAFREE(ifa);
1013                         Free(rt_key(rt));
1014                         Free(rt);
1015                         gotoerr(EEXIST);
1016                 }
1017
1018                 /*
1019                  * If we got here from RESOLVE, then we are cloning
1020                  * so clone the rest, and note that we
1021                  * are a clone (and increment the parent's references)
1022                  */
1023                 if (req == RTM_RESOLVE) {
1024                         rt->rt_rmx = (*ret_nrt)->rt_rmx;    /* copy metrics */
1025                         rt->rt_rmx.rmx_pksent = 0;  /* reset packet counter */
1026                         if ((*ret_nrt)->rt_flags &
1027                                        (RTF_CLONING | RTF_PRCLONING)) {
1028                                 rt->rt_parent = *ret_nrt;
1029                                 (*ret_nrt)->rt_refcnt++;
1030                         }
1031                 }
1032
1033                 /*
1034                  * if this protocol has something to add to this then
1035                  * allow it to do that as well.
1036                  */
1037                 if (ifa->ifa_rtrequest != NULL)
1038                         ifa->ifa_rtrequest(req, rt, rtinfo);
1039
1040                 /*
1041                  * We repeat the same procedure from rt_setgate() here because
1042                  * it doesn't fire when we call it there because the node
1043                  * hasn't been added to the tree yet.
1044                  */
1045                 if (req == RTM_ADD && !(rt->rt_flags & RTF_HOST) &&
1046                     rt_mask(rt) != NULL) {
1047                         struct rtfc_arg arg = { rt, rnh };
1048
1049                         rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
1050                                                (char *)rt_mask(rt),
1051                                                rt_fixchange, &arg);
1052                 }
1053
1054 #ifdef ROUTE_DEBUG
1055                 if (route_debug)
1056                         rt_print(rtinfo, rt);
1057 #endif
1058                 /*
1059                  * Return the resulting rtentry,
1060                  * increasing the number of references by one.
1061                  */
1062                 if (ret_nrt != NULL) {
1063                         rt->rt_refcnt++;
1064                         *ret_nrt = rt;
1065                 }
1066                 break;
1067         default:
1068                 error = EOPNOTSUPP;
1069         }
1070 bad:
1071 #ifdef ROUTE_DEBUG
1072         if (route_debug) {
1073                 if (error)
1074                         kprintf("rti %p failed error %d\n", rtinfo, error);
1075                 else
1076                         kprintf("rti %p succeeded\n", rtinfo);
1077         }
1078 #endif
1079         crit_exit();
1080         return (error);
1081 }
1082
1083 /*
1084  * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
1085  * (i.e., the routes related to it by the operation of cloning).  This
1086  * routine is iterated over all potential former-child-routes by way of
1087  * rnh->rnh_walktree_from() above, and those that actually are children of
1088  * the late parent (passed in as VP here) are themselves deleted.
1089  */
1090 static int
1091 rt_fixdelete(struct radix_node *rn, void *vp)
1092 {
1093         struct rtentry *rt = (struct rtentry *)rn;
1094         struct rtentry *rt0 = vp;
1095
1096         if (rt->rt_parent == rt0 &&
1097             !(rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1098                 return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1099                                  rt->rt_flags, NULL);
1100         }
1101         return 0;
1102 }
1103
1104 /*
1105  * This routine is called from rt_setgate() to do the analogous thing for
1106  * adds and changes.  There is the added complication in this case of a
1107  * middle insert; i.e., insertion of a new network route between an older
1108  * network route and (cloned) host routes.  For this reason, a simple check
1109  * of rt->rt_parent is insufficient; each candidate route must be tested
1110  * against the (mask, value) of the new route (passed as before in vp)
1111  * to see if the new route matches it.
1112  *
1113  * XXX - it may be possible to do fixdelete() for changes and reserve this
1114  * routine just for adds.  I'm not sure why I thought it was necessary to do
1115  * changes this way.
1116  */
1117 #ifdef DEBUG
1118 static int rtfcdebug = 0;
1119 #endif
1120
1121 static int
1122 rt_fixchange(struct radix_node *rn, void *vp)
1123 {
1124         struct rtentry *rt = (struct rtentry *)rn;
1125         struct rtfc_arg *ap = vp;
1126         struct rtentry *rt0 = ap->rt0;
1127         struct radix_node_head *rnh = ap->rnh;
1128         u_char *xk1, *xm1, *xk2, *xmp;
1129         int i, len, mlen;
1130
1131 #ifdef DEBUG
1132         if (rtfcdebug)
1133                 kprintf("rt_fixchange: rt %p, rt0 %p\n", rt, rt0);
1134 #endif
1135
1136         if (rt->rt_parent == NULL ||
1137             (rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1138 #ifdef DEBUG
1139                 if (rtfcdebug) kprintf("no parent, pinned or cloning\n");
1140 #endif
1141                 return 0;
1142         }
1143
1144         if (rt->rt_parent == rt0) {
1145 #ifdef DEBUG
1146                 if (rtfcdebug) kprintf("parent match\n");
1147 #endif
1148                 return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1149                                  rt->rt_flags, NULL);
1150         }
1151
1152         /*
1153          * There probably is a function somewhere which does this...
1154          * if not, there should be.
1155          */
1156         len = imin(rt_key(rt0)->sa_len, rt_key(rt)->sa_len);
1157
1158         xk1 = (u_char *)rt_key(rt0);
1159         xm1 = (u_char *)rt_mask(rt0);
1160         xk2 = (u_char *)rt_key(rt);
1161
1162         /* avoid applying a less specific route */
1163         xmp = (u_char *)rt_mask(rt->rt_parent);
1164         mlen = rt_key(rt->rt_parent)->sa_len;
1165         if (mlen > rt_key(rt0)->sa_len) {
1166 #ifdef DEBUG
1167                 if (rtfcdebug)
1168                         kprintf("rt_fixchange: inserting a less "
1169                                "specific route\n");
1170 #endif
1171                 return 0;
1172         }
1173         for (i = rnh->rnh_treetop->rn_offset; i < mlen; i++) {
1174                 if ((xmp[i] & ~(xmp[i] ^ xm1[i])) != xmp[i]) {
1175 #ifdef DEBUG
1176                         if (rtfcdebug)
1177                                 kprintf("rt_fixchange: inserting a less "
1178                                        "specific route\n");
1179 #endif
1180                         return 0;
1181                 }
1182         }
1183
1184         for (i = rnh->rnh_treetop->rn_offset; i < len; i++) {
1185                 if ((xk2[i] & xm1[i]) != xk1[i]) {
1186 #ifdef DEBUG
1187                         if (rtfcdebug) kprintf("no match\n");
1188 #endif
1189                         return 0;
1190                 }
1191         }
1192
1193         /*
1194          * OK, this node is a clone, and matches the node currently being
1195          * changed/added under the node's mask.  So, get rid of it.
1196          */
1197 #ifdef DEBUG
1198         if (rtfcdebug) kprintf("deleting\n");
1199 #endif
1200         return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1201                          rt->rt_flags, NULL);
1202 }
1203
1204 #define ROUNDUP(a) (a>0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
1205
1206 int
1207 rt_setgate(struct rtentry *rt0, struct sockaddr *dst, struct sockaddr *gate,
1208            boolean_t generate_report)
1209 {
1210         char *space, *oldspace;
1211         int dlen = ROUNDUP(dst->sa_len), glen = ROUNDUP(gate->sa_len);
1212         struct rtentry *rt = rt0;
1213         struct radix_node_head *rnh = rt_tables[mycpuid][dst->sa_family];
1214
1215         /*
1216          * A host route with the destination equal to the gateway
1217          * will interfere with keeping LLINFO in the routing
1218          * table, so disallow it.
1219          */
1220         if (((rt0->rt_flags & (RTF_HOST | RTF_GATEWAY | RTF_LLINFO)) ==
1221                               (RTF_HOST | RTF_GATEWAY)) &&
1222             dst->sa_len == gate->sa_len &&
1223             sa_equal(dst, gate)) {
1224                 /*
1225                  * The route might already exist if this is an RTM_CHANGE
1226                  * or a routing redirect, so try to delete it.
1227                  */
1228                 if (rt_key(rt0) != NULL)
1229                         rtrequest(RTM_DELETE, rt_key(rt0), rt0->rt_gateway,
1230                                   rt_mask(rt0), rt0->rt_flags, NULL);
1231                 return EADDRNOTAVAIL;
1232         }
1233
1234         /*
1235          * Both dst and gateway are stored in the same malloc'ed chunk
1236          * (If I ever get my hands on....)
1237          * if we need to malloc a new chunk, then keep the old one around
1238          * till we don't need it any more.
1239          */
1240         if (rt->rt_gateway == NULL || glen > ROUNDUP(rt->rt_gateway->sa_len)) {
1241                 oldspace = (char *)rt_key(rt);
1242                 R_Malloc(space, char *, dlen + glen);
1243                 if (space == NULL)
1244                         return ENOBUFS;
1245                 rt->rt_nodes->rn_key = space;
1246         } else {
1247                 space = (char *)rt_key(rt);     /* Just use the old space. */
1248                 oldspace = NULL;
1249         }
1250
1251         /* Set the gateway value. */
1252         rt->rt_gateway = (struct sockaddr *)(space + dlen);
1253         bcopy(gate, rt->rt_gateway, glen);
1254
1255         if (oldspace != NULL) {
1256                 /*
1257                  * If we allocated a new chunk, preserve the original dst.
1258                  * This way, rt_setgate() really just sets the gate
1259                  * and leaves the dst field alone.
1260                  */
1261                 bcopy(dst, space, dlen);
1262                 Free(oldspace);
1263         }
1264
1265         /*
1266          * If there is already a gwroute, it's now almost definitely wrong
1267          * so drop it.
1268          */
1269         if (rt->rt_gwroute != NULL) {
1270                 RTFREE(rt->rt_gwroute);
1271                 rt->rt_gwroute = NULL;
1272         }
1273         if (rt->rt_flags & RTF_GATEWAY) {
1274                 /*
1275                  * Cloning loop avoidance: In the presence of
1276                  * protocol-cloning and bad configuration, it is
1277                  * possible to get stuck in bottomless mutual recursion
1278                  * (rtrequest rt_setgate rtlookup).  We avoid this
1279                  * by not allowing protocol-cloning to operate for
1280                  * gateways (which is probably the correct choice
1281                  * anyway), and avoid the resulting reference loops
1282                  * by disallowing any route to run through itself as
1283                  * a gateway.  This is obviously mandatory when we
1284                  * get rt->rt_output().
1285                  *
1286                  * This breaks TTCP for hosts outside the gateway!  XXX JH
1287                  */
1288                 rt->rt_gwroute = _rtlookup(gate, generate_report,
1289                                            RTF_PRCLONING);
1290                 if (rt->rt_gwroute == rt) {
1291                         rt->rt_gwroute = NULL;
1292                         --rt->rt_refcnt;
1293                         return EDQUOT; /* failure */
1294                 }
1295         }
1296
1297         /*
1298          * This isn't going to do anything useful for host routes, so
1299          * don't bother.  Also make sure we have a reasonable mask
1300          * (we don't yet have one during adds).
1301          */
1302         if (!(rt->rt_flags & RTF_HOST) && rt_mask(rt) != NULL) {
1303                 struct rtfc_arg arg = { rt, rnh };
1304
1305                 rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
1306                                        (char *)rt_mask(rt),
1307                                        rt_fixchange, &arg);
1308         }
1309
1310         return 0;
1311 }
1312
1313 static void
1314 rt_maskedcopy(
1315         struct sockaddr *src,
1316         struct sockaddr *dst,
1317         struct sockaddr *netmask)
1318 {
1319         u_char *cp1 = (u_char *)src;
1320         u_char *cp2 = (u_char *)dst;
1321         u_char *cp3 = (u_char *)netmask;
1322         u_char *cplim = cp2 + *cp3;
1323         u_char *cplim2 = cp2 + *cp1;
1324
1325         *cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1326         cp3 += 2;
1327         if (cplim > cplim2)
1328                 cplim = cplim2;
1329         while (cp2 < cplim)
1330                 *cp2++ = *cp1++ & *cp3++;
1331         if (cp2 < cplim2)
1332                 bzero(cp2, cplim2 - cp2);
1333 }
1334
1335 int
1336 rt_llroute(struct sockaddr *dst, struct rtentry *rt0, struct rtentry **drt)
1337 {
1338         struct rtentry *up_rt, *rt;
1339
1340         if (!(rt0->rt_flags & RTF_UP)) {
1341                 up_rt = rtlookup(dst);
1342                 if (up_rt == NULL)
1343                         return (EHOSTUNREACH);
1344                 up_rt->rt_refcnt--;
1345         } else
1346                 up_rt = rt0;
1347         if (up_rt->rt_flags & RTF_GATEWAY) {
1348                 if (up_rt->rt_gwroute == NULL) {
1349                         up_rt->rt_gwroute = rtlookup(up_rt->rt_gateway);
1350                         if (up_rt->rt_gwroute == NULL)
1351                                 return (EHOSTUNREACH);
1352                 } else if (!(up_rt->rt_gwroute->rt_flags & RTF_UP)) {
1353                         rtfree(up_rt->rt_gwroute);
1354                         up_rt->rt_gwroute = rtlookup(up_rt->rt_gateway);
1355                         if (up_rt->rt_gwroute == NULL)
1356                                 return (EHOSTUNREACH);
1357                 }
1358                 rt = up_rt->rt_gwroute;
1359         } else
1360                 rt = up_rt;
1361         if (rt->rt_flags & RTF_REJECT &&
1362             (rt->rt_rmx.rmx_expire == 0 ||              /* rt doesn't expire */
1363              time_second < rt->rt_rmx.rmx_expire))      /* rt not expired */
1364                 return (rt->rt_flags & RTF_HOST ?  EHOSTDOWN : EHOSTUNREACH);
1365         *drt = rt;
1366         return 0;
1367 }
1368
1369 static int
1370 rt_setshims(struct rtentry *rt, struct sockaddr **rt_shim){
1371         int i;
1372         
1373         for (i=0; i<3; i++) {
1374                 struct sockaddr *shim = rt_shim[RTAX_MPLS1 + i];
1375                 int shimlen;
1376
1377                 if (shim == NULL)
1378                         break;
1379
1380                 shimlen = ROUNDUP(shim->sa_len);
1381                 R_Malloc(rt->rt_shim[i], struct sockaddr *, shimlen);
1382                 bcopy(shim, rt->rt_shim[i], shimlen);
1383         }
1384
1385         return 0;
1386 }
1387
1388 #ifdef ROUTE_DEBUG
1389
1390 /*
1391  * Print out a route table entry
1392  */
1393 void
1394 rt_print(struct rt_addrinfo *rtinfo, struct rtentry *rn)
1395 {
1396         kprintf("rti %p cpu %d route %p flags %08lx: ", 
1397                 rtinfo, mycpuid, rn, rn->rt_flags);
1398         sockaddr_print(rt_key(rn));
1399         kprintf(" mask ");
1400         sockaddr_print(rt_mask(rn));
1401         kprintf(" gw ");
1402         sockaddr_print(rn->rt_gateway);
1403         kprintf(" ifc \"%s\"", rn->rt_ifp ? rn->rt_ifp->if_dname : "?");
1404         kprintf(" ifa %p\n", rn->rt_ifa);
1405 }
1406
1407 void
1408 rt_addrinfo_print(int cmd, struct rt_addrinfo *rti)
1409 {
1410         int didit = 0;
1411         int i;
1412
1413 #ifdef ROUTE_DEBUG
1414         if (cmd == RTM_DELETE && route_debug > 1)
1415                 print_backtrace();
1416 #endif
1417
1418         switch(cmd) {
1419         case RTM_ADD:
1420                 kprintf("ADD ");
1421                 break;
1422         case RTM_RESOLVE:
1423                 kprintf("RES ");
1424                 break;
1425         case RTM_DELETE:
1426                 kprintf("DEL ");
1427                 break;
1428         default:
1429                 kprintf("C%02d ", cmd);
1430                 break;
1431         }
1432         kprintf("rti %p cpu %d ", rti, mycpuid);
1433         for (i = 0; i < rti->rti_addrs; ++i) {
1434                 if (rti->rti_info[i] == NULL)
1435                         continue;
1436                 if (didit)
1437                         kprintf(" ,");
1438                 switch(i) {
1439                 case RTAX_DST:
1440                         kprintf("(DST ");
1441                         break;
1442                 case RTAX_GATEWAY:
1443                         kprintf("(GWY ");
1444                         break;
1445                 case RTAX_NETMASK:
1446                         kprintf("(MSK ");
1447                         break;
1448                 case RTAX_GENMASK:
1449                         kprintf("(GEN ");
1450                         break;
1451                 case RTAX_IFP:
1452                         kprintf("(IFP ");
1453                         break;
1454                 case RTAX_IFA:
1455                         kprintf("(IFA ");
1456                         break;
1457                 case RTAX_AUTHOR:
1458                         kprintf("(AUT ");
1459                         break;
1460                 case RTAX_BRD:
1461                         kprintf("(BRD ");
1462                         break;
1463                 default:
1464                         kprintf("(?%02d ", i);
1465                         break;
1466                 }
1467                 sockaddr_print(rti->rti_info[i]);
1468                 kprintf(")");
1469                 didit = 1;
1470         }
1471         kprintf("\n");
1472 }
1473
1474 void
1475 sockaddr_print(struct sockaddr *sa)
1476 {
1477         struct sockaddr_in *sa4;
1478         struct sockaddr_in6 *sa6;
1479         int len;
1480         int i;
1481
1482         if (sa == NULL) {
1483                 kprintf("NULL");
1484                 return;
1485         }
1486
1487         len = sa->sa_len - offsetof(struct sockaddr, sa_data[0]);
1488
1489         switch(sa->sa_family) {
1490         case AF_INET:
1491         case AF_INET6:
1492         default:
1493                 switch(sa->sa_family) {
1494                 case AF_INET:
1495                         sa4 = (struct sockaddr_in *)sa;
1496                         kprintf("INET %d %d.%d.%d.%d",
1497                                 ntohs(sa4->sin_port),
1498                                 (ntohl(sa4->sin_addr.s_addr) >> 24) & 255,
1499                                 (ntohl(sa4->sin_addr.s_addr) >> 16) & 255,
1500                                 (ntohl(sa4->sin_addr.s_addr) >> 8) & 255,
1501                                 (ntohl(sa4->sin_addr.s_addr) >> 0) & 255
1502                         );
1503                         break;
1504                 case AF_INET6:
1505                         sa6 = (struct sockaddr_in6 *)sa;
1506                         kprintf("INET6 %d %04x:%04x%04x:%04x:%04x:%04x:%04x:%04x",
1507                                 ntohs(sa6->sin6_port),
1508                                 sa6->sin6_addr.s6_addr16[0],
1509                                 sa6->sin6_addr.s6_addr16[1],
1510                                 sa6->sin6_addr.s6_addr16[2],
1511                                 sa6->sin6_addr.s6_addr16[3],
1512                                 sa6->sin6_addr.s6_addr16[4],
1513                                 sa6->sin6_addr.s6_addr16[5],
1514                                 sa6->sin6_addr.s6_addr16[6],
1515                                 sa6->sin6_addr.s6_addr16[7]
1516                         );
1517                         break;
1518                 default:
1519                         kprintf("AF%d ", sa->sa_family);
1520                         while (len > 0 && sa->sa_data[len-1] == 0)
1521                                 --len;
1522
1523                         for (i = 0; i < len; ++i) {
1524                                 if (i)
1525                                         kprintf(".");
1526                                 kprintf("%d", (unsigned char)sa->sa_data[i]);
1527                         }
1528                         break;
1529                 }
1530         }
1531 }
1532
1533 #endif
1534
1535 /*
1536  * Set up a routing table entry, normally for an interface.
1537  */
1538 int
1539 rtinit(struct ifaddr *ifa, int cmd, int flags)
1540 {
1541         struct sockaddr *dst, *deldst, *netmask;
1542         struct mbuf *m = NULL;
1543         struct radix_node_head *rnh;
1544         struct radix_node *rn;
1545         struct rt_addrinfo rtinfo;
1546         int error;
1547
1548         if (flags & RTF_HOST) {
1549                 dst = ifa->ifa_dstaddr;
1550                 netmask = NULL;
1551         } else {
1552                 dst = ifa->ifa_addr;
1553                 netmask = ifa->ifa_netmask;
1554         }
1555         /*
1556          * If it's a delete, check that if it exists, it's on the correct
1557          * interface or we might scrub a route to another ifa which would
1558          * be confusing at best and possibly worse.
1559          */
1560         if (cmd == RTM_DELETE) {
1561                 /*
1562                  * It's a delete, so it should already exist..
1563                  * If it's a net, mask off the host bits
1564                  * (Assuming we have a mask)
1565                  */
1566                 if (netmask != NULL) {
1567                         m = m_get(MB_DONTWAIT, MT_SONAME);
1568                         if (m == NULL)
1569                                 return (ENOBUFS);
1570                         mbuftrackid(m, 34);
1571                         deldst = mtod(m, struct sockaddr *);
1572                         rt_maskedcopy(dst, deldst, netmask);
1573                         dst = deldst;
1574                 }
1575                 /*
1576                  * Look up an rtentry that is in the routing tree and
1577                  * contains the correct info.
1578                  */
1579                 if ((rnh = rt_tables[mycpuid][dst->sa_family]) == NULL ||
1580                     (rn = rnh->rnh_lookup((char *)dst,
1581                                           (char *)netmask, rnh)) == NULL ||
1582                     ((struct rtentry *)rn)->rt_ifa != ifa ||
1583                     !sa_equal((struct sockaddr *)rn->rn_key, dst)) {
1584                         if (m != NULL)
1585                                 m_free(m);
1586                         return (flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1587                 }
1588                 /* XXX */
1589 #if 0
1590                 else {
1591                         /*
1592                          * One would think that as we are deleting, and we know
1593                          * it doesn't exist, we could just return at this point
1594                          * with an "ELSE" clause, but apparently not..
1595                          */
1596                         return (flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1597                 }
1598 #endif
1599         }
1600         /*
1601          * Do the actual request
1602          */
1603         bzero(&rtinfo, sizeof(struct rt_addrinfo));
1604         rtinfo.rti_info[RTAX_DST] = dst;
1605         rtinfo.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1606         rtinfo.rti_info[RTAX_NETMASK] = netmask;
1607         rtinfo.rti_flags = flags | ifa->ifa_flags;
1608         rtinfo.rti_ifa = ifa;
1609         error = rtrequest1_global(cmd, &rtinfo, rtinit_rtrequest_callback, ifa);
1610         if (m != NULL)
1611                 m_free(m);
1612         return (error);
1613 }
1614
1615 static void
1616 rtinit_rtrequest_callback(int cmd, int error,
1617                           struct rt_addrinfo *rtinfo, struct rtentry *rt,
1618                           void *arg)
1619 {
1620         struct ifaddr *ifa = arg;
1621
1622         if (error == 0 && rt) {
1623                 if (mycpuid == 0) {
1624                         ++rt->rt_refcnt;
1625                         rt_newaddrmsg(cmd, ifa, error, rt);
1626                         --rt->rt_refcnt;
1627                 }
1628                 if (cmd == RTM_DELETE) {
1629                         if (rt->rt_refcnt == 0) {
1630                                 ++rt->rt_refcnt;
1631                                 rtfree(rt);
1632                         }
1633                 }
1634         }
1635 }
1636
1637 struct netmsg_rts {
1638         struct netmsg           netmsg;
1639         int                     req;
1640         struct rt_addrinfo      *rtinfo;
1641         rtsearch_callback_func_t callback;
1642         void                    *arg;
1643         boolean_t               exact_match;
1644         int                     found_cnt;
1645 };
1646
1647 int
1648 rtsearch_global(int req, struct rt_addrinfo *rtinfo,
1649                 rtsearch_callback_func_t callback, void *arg,
1650                 boolean_t exact_match)
1651 {
1652         struct netmsg_rts msg;
1653
1654         netmsg_init(&msg.netmsg, &curthread->td_msgport, 0,
1655                     rtsearch_msghandler);
1656         msg.req = req;
1657         msg.rtinfo = rtinfo;
1658         msg.callback = callback;
1659         msg.arg = arg;
1660         msg.exact_match = exact_match;
1661         msg.found_cnt = 0;
1662         return lwkt_domsg(rtable_portfn(0), &msg.netmsg.nm_lmsg, 0);
1663 }
1664
1665 static void
1666 rtsearch_msghandler(struct netmsg *netmsg)
1667 {
1668         struct netmsg_rts *msg = (void *)netmsg;
1669         struct rt_addrinfo *rtinfo = msg->rtinfo;
1670         struct radix_node_head *rnh;
1671         struct rtentry *rt;
1672         int nextcpu, error;
1673
1674         /*
1675          * Find the correct routing tree to use for this Address Family
1676          */
1677         if ((rnh = rt_tables[mycpuid][rtinfo->rti_dst->sa_family]) == NULL) {
1678                 if (mycpuid != 0)
1679                         panic("partially initialized routing tables\n");
1680                 lwkt_replymsg(&msg->netmsg.nm_lmsg, EAFNOSUPPORT);
1681                 return;
1682         }
1683
1684         /*
1685          * Correct rtinfo for the host route searching.
1686          */
1687         if (rtinfo->rti_flags & RTF_HOST) {
1688                 rtinfo->rti_netmask = NULL;
1689                 rtinfo->rti_flags &= ~(RTF_CLONING | RTF_PRCLONING);
1690         }
1691
1692         rt = (struct rtentry *)
1693              rnh->rnh_lookup((char *)rtinfo->rti_dst,
1694                              (char *)rtinfo->rti_netmask, rnh);
1695
1696         /*
1697          * If we are asked to do the "exact match", we need to make sure
1698          * that host route searching got a host route while a network
1699          * route searching got a network route.
1700          */
1701         if (rt != NULL && msg->exact_match &&
1702             ((rt->rt_flags ^ rtinfo->rti_flags) & RTF_HOST))
1703                 rt = NULL;
1704
1705         if (rt == NULL) {
1706                 /*
1707                  * No matching routes have been found, don't count this
1708                  * as a critical error (here, we set 'error' to 0), just
1709                  * keep moving on, since at least prcloned routes are not
1710                  * duplicated onto each CPU.
1711                  */
1712                 error = 0;
1713         } else {
1714                 msg->found_cnt++;
1715
1716                 rt->rt_refcnt++;
1717                 error = msg->callback(msg->req, msg->rtinfo, rt, msg->arg,
1718                                       msg->found_cnt);
1719                 rt->rt_refcnt--;
1720
1721                 if (error == EJUSTRETURN) {
1722                         lwkt_replymsg(&msg->netmsg.nm_lmsg, 0);
1723                         return;
1724                 }
1725         }
1726
1727         nextcpu = mycpuid + 1;
1728         if (error) {
1729                 KKASSERT(msg->found_cnt > 0);
1730
1731                 /*
1732                  * Under following cases, unrecoverable error has
1733                  * not occured:
1734                  * o  Request is RTM_GET
1735                  * o  The first time that we find the route, but the
1736                  *    modification fails.
1737                  */
1738                 if (msg->req != RTM_GET && msg->found_cnt > 1) {
1739                         panic("rtsearch_msghandler: unrecoverable error "
1740                               "cpu %d, rtinfo %p", mycpuid, msg->rtinfo);
1741                 }
1742                 lwkt_replymsg(&msg->netmsg.nm_lmsg, error);
1743         } else if (nextcpu < ncpus) {
1744                 lwkt_forwardmsg(rtable_portfn(nextcpu), &msg->netmsg.nm_lmsg);
1745         } else {
1746                 if (msg->found_cnt == 0) {
1747                         /* The requested route was never seen ... */
1748                         error = ESRCH;
1749                 }
1750                 lwkt_replymsg(&msg->netmsg.nm_lmsg, error);
1751         }
1752 }
1753
1754 int
1755 rtmask_add_global(struct sockaddr *mask)
1756 {
1757         struct netmsg nmsg;
1758
1759         netmsg_init(&nmsg, &curthread->td_msgport, 0,
1760                     rtmask_add_msghandler);
1761         nmsg.nm_lmsg.u.ms_resultp = mask;
1762
1763         return lwkt_domsg(rtable_portfn(0), &nmsg.nm_lmsg, 0);
1764 }
1765
1766 struct sockaddr *
1767 _rtmask_lookup(struct sockaddr *mask, boolean_t search)
1768 {
1769         struct radix_node *n;
1770
1771 #define clen(s) (*(u_char *)(s))
1772         n = rn_addmask((char *)mask, search, 1);
1773         if (n != NULL &&
1774             mask->sa_len >= clen(n->rn_key) &&
1775             bcmp((char *)mask + 1,
1776                  (char *)n->rn_key + 1, clen(n->rn_key) - 1) == 0) {
1777                 return (struct sockaddr *)n->rn_key;
1778         } else {
1779                 return NULL;
1780         }
1781 #undef clen
1782 }
1783
1784 static void
1785 rtmask_add_msghandler(struct netmsg *nmsg)
1786 {
1787         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
1788         struct sockaddr *mask = lmsg->u.ms_resultp;
1789         int error = 0, nextcpu;
1790
1791         if (rtmask_lookup(mask) == NULL)
1792                 error = ENOBUFS;
1793
1794         nextcpu = mycpuid + 1;
1795         if (!error && nextcpu < ncpus)
1796                 lwkt_forwardmsg(rtable_portfn(nextcpu), lmsg);
1797         else
1798                 lwkt_replymsg(lmsg, error);
1799 }
1800
1801 /* This must be before ip6_init2(), which is now SI_ORDER_MIDDLE */
1802 SYSINIT(route, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);