route: Suppress duplicated rtmsgs generated by rtlookup() in rt_setgate()
[dragonfly.git] / sys / net / route.c
1 /*
2  * Copyright (c) 2004, 2005 The DragonFly Project.  All rights reserved.
3  *
4  * This code is derived from software contributed to The DragonFly Project
5  * by Jeffrey M. Hsu.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of The DragonFly Project nor the names of its
16  *    contributors may be used to endorse or promote products derived
17  *    from this software without specific, prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
22  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
23  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
25  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
26  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
27  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
29  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 /*
34  * Copyright (c) 1980, 1986, 1991, 1993
35  *      The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *      This product includes software developed by the University of
48  *      California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *      @(#)route.c     8.3 (Berkeley) 1/9/95
66  * $FreeBSD: src/sys/net/route.c,v 1.59.2.10 2003/01/17 08:04:00 ru Exp $
67  * $DragonFly: src/sys/net/route.c,v 1.41 2008/11/09 10:50:15 sephe Exp $
68  */
69
70 #include "opt_inet.h"
71 #include "opt_mpls.h"
72
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/socket.h>
78 #include <sys/domain.h>
79 #include <sys/kernel.h>
80 #include <sys/sysctl.h>
81 #include <sys/globaldata.h>
82 #include <sys/thread.h>
83
84 #include <net/if.h>
85 #include <net/route.h>
86 #include <net/netisr.h>
87
88 #include <netinet/in.h>
89 #include <net/ip_mroute/ip_mroute.h>
90
91 #include <sys/thread2.h>
92 #include <sys/msgport2.h>
93 #include <net/netmsg2.h>
94
95 #ifdef MPLS
96 #include <netproto/mpls/mpls.h>
97 #endif
98
99 static struct rtstatistics rtstatistics_percpu[MAXCPU];
100 #ifdef SMP
101 #define rtstat  rtstatistics_percpu[mycpuid]
102 #else
103 #define rtstat  rtstatistics_percpu[0]
104 #endif
105
106 struct radix_node_head *rt_tables[MAXCPU][AF_MAX+1];
107 struct lwkt_port *rt_ports[MAXCPU];
108
109 static void     rt_maskedcopy (struct sockaddr *, struct sockaddr *,
110                                struct sockaddr *);
111 static void rtable_init(void);
112 static void rtable_service_loop(void *dummy);
113 static void rtinit_rtrequest_callback(int, int, struct rt_addrinfo *,
114                                       struct rtentry *, void *);
115
116 #ifdef SMP
117 static void rtredirect_msghandler(struct netmsg *netmsg);
118 static void rtrequest1_msghandler(struct netmsg *netmsg);
119 #endif
120 static void rtsearch_msghandler(struct netmsg *netmsg);
121
122 static int rt_setshims(struct rtentry *, struct sockaddr **);
123
124 SYSCTL_NODE(_net, OID_AUTO, route, CTLFLAG_RW, 0, "Routing");
125
126 #ifdef ROUTE_DEBUG
127 static int route_debug = 1;
128 SYSCTL_INT(_net_route, OID_AUTO, route_debug, CTLFLAG_RW,
129            &route_debug, 0, "");
130 #endif
131
132 int route_assert_owner_access = 0;
133 SYSCTL_INT(_net_route, OID_AUTO, assert_owner_access, CTLFLAG_RW,
134            &route_assert_owner_access, 0, "");
135
136 /*
137  * Initialize the route table(s) for protocol domains and
138  * create a helper thread which will be responsible for updating
139  * route table entries on each cpu.
140  */
141 void
142 route_init(void)
143 {
144         int cpu;
145         thread_t rtd;
146
147         for (cpu = 0; cpu < ncpus; ++cpu)
148                 bzero(&rtstatistics_percpu[cpu], sizeof(struct rtstatistics));
149         rn_init();      /* initialize all zeroes, all ones, mask table */
150         rtable_init();  /* call dom_rtattach() on each cpu */
151
152         for (cpu = 0; cpu < ncpus; cpu++) {
153                 lwkt_create(rtable_service_loop, NULL, &rtd, NULL,
154                             0, cpu, "rtable_cpu %d", cpu);
155                 rt_ports[cpu] = &rtd->td_msgport;
156         }
157 }
158
159 static void
160 rtable_init_oncpu(struct netmsg *nmsg)
161 {
162         struct domain *dom;
163         int cpu = mycpuid;
164
165         SLIST_FOREACH(dom, &domains, dom_next) {
166                 if (dom->dom_rtattach) {
167                         dom->dom_rtattach(
168                                 (void **)&rt_tables[cpu][dom->dom_family],
169                                 dom->dom_rtoffset);
170                 }
171         }
172         ifnet_forwardmsg(&nmsg->nm_lmsg, cpu + 1);
173 }
174
175 static void
176 rtable_init(void)
177 {
178         struct netmsg nmsg;
179
180         netmsg_init(&nmsg, &curthread->td_msgport, 0, rtable_init_oncpu);
181         ifnet_domsg(&nmsg.nm_lmsg, 0);
182 }
183
184 /*
185  * Our per-cpu table management protocol thread.  All route table operations
186  * are sequentially chained through all cpus starting at cpu #0 in order to
187  * maintain duplicate route tables on each cpu.  Having a spearate route
188  * table management thread allows the protocol and interrupt threads to
189  * issue route table changes.
190  */
191 static void
192 rtable_service_loop(void *dummy __unused)
193 {
194         struct netmsg *netmsg;
195         thread_t td = curthread;
196
197         while ((netmsg = lwkt_waitport(&td->td_msgport, 0)) != NULL) {
198                 netmsg->nm_dispatch(netmsg);
199         }
200 }
201
202 /*
203  * Routing statistics.
204  */
205 #ifdef SMP
206 static int
207 sysctl_rtstatistics(SYSCTL_HANDLER_ARGS)
208 {
209         int cpu, error = 0;
210
211         for (cpu = 0; cpu < ncpus; ++cpu) {
212                 if ((error = SYSCTL_OUT(req, &rtstatistics_percpu[cpu],
213                                         sizeof(struct rtstatistics))))
214                                 break;
215                 if ((error = SYSCTL_IN(req, &rtstatistics_percpu[cpu],
216                                         sizeof(struct rtstatistics))))
217                                 break;
218         }
219
220         return (error);
221 }
222 SYSCTL_PROC(_net_route, OID_AUTO, stats, (CTLTYPE_OPAQUE|CTLFLAG_RW),
223         0, 0, sysctl_rtstatistics, "S,rtstatistics", "Routing statistics");
224 #else
225 SYSCTL_STRUCT(_net_route, OID_AUTO, stats, CTLFLAG_RW, &rtstat, rtstatistics,
226 "Routing statistics");
227 #endif
228
229 /*
230  * Packet routing routines.
231  */
232
233 /*
234  * Look up and fill in the "ro_rt" rtentry field in a route structure given
235  * an address in the "ro_dst" field.  Always send a report on a miss and
236  * always clone routes.
237  */
238 void
239 rtalloc(struct route *ro)
240 {
241         rtalloc_ign(ro, 0UL);
242 }
243
244 /*
245  * Look up and fill in the "ro_rt" rtentry field in a route structure given
246  * an address in the "ro_dst" field.  Always send a report on a miss and
247  * optionally clone routes when RTF_CLONING or RTF_PRCLONING are not being
248  * ignored.
249  */
250 void
251 rtalloc_ign(struct route *ro, u_long ignoreflags)
252 {
253         if (ro->ro_rt != NULL) {
254                 if (ro->ro_rt->rt_ifp != NULL && ro->ro_rt->rt_flags & RTF_UP)
255                         return;
256                 rtfree(ro->ro_rt);
257                 ro->ro_rt = NULL;
258         }
259         ro->ro_rt = _rtlookup(&ro->ro_dst, RTL_REPORTMSG, ignoreflags);
260 }
261
262 /*
263  * Look up the route that matches the given "dst" address.
264  *
265  * Route lookup can have the side-effect of creating and returning
266  * a cloned route instead when "dst" matches a cloning route and the
267  * RTF_CLONING and RTF_PRCLONING flags are not being ignored.
268  *
269  * Any route returned has its reference count incremented.
270  */
271 struct rtentry *
272 _rtlookup(struct sockaddr *dst, boolean_t generate_report, u_long ignore)
273 {
274         struct radix_node_head *rnh = rt_tables[mycpuid][dst->sa_family];
275         struct rtentry *rt;
276
277         if (rnh == NULL)
278                 goto unreach;
279
280         /*
281          * Look up route in the radix tree.
282          */
283         rt = (struct rtentry *) rnh->rnh_matchaddr((char *)dst, rnh);
284         if (rt == NULL)
285                 goto unreach;
286
287         /*
288          * Handle cloning routes.
289          */
290         if ((rt->rt_flags & ~ignore & (RTF_CLONING | RTF_PRCLONING)) != 0) {
291                 struct rtentry *clonedroute;
292                 int error;
293
294                 clonedroute = rt;       /* copy in/copy out parameter */
295                 error = rtrequest(RTM_RESOLVE, dst, NULL, NULL, 0,
296                                   &clonedroute);        /* clone the route */
297                 if (error != 0) {       /* cloning failed */
298                         if (generate_report)
299                                 rt_dstmsg(RTM_MISS, dst, error);
300                         rt->rt_refcnt++;
301                         return (rt);    /* return the uncloned route */
302                 }
303                 if (generate_report) {
304                         if (clonedroute->rt_flags & RTF_XRESOLVE)
305                                 rt_dstmsg(RTM_RESOLVE, dst, 0);
306                         else
307                                 rt_rtmsg(RTM_ADD, clonedroute,
308                                          clonedroute->rt_ifp, 0);
309                 }
310                 return (clonedroute);   /* return cloned route */
311         }
312
313         /*
314          * Increment the reference count of the matched route and return.
315          */
316         rt->rt_refcnt++;
317         return (rt);
318
319 unreach:
320         rtstat.rts_unreach++;
321         if (generate_report)
322                 rt_dstmsg(RTM_MISS, dst, 0);
323         return (NULL);
324 }
325
326 void
327 rtfree(struct rtentry *rt)
328 {
329         if (rt->rt_cpuid == mycpuid)
330                 rtfree_oncpu(rt);
331         else
332                 rtfree_remote(rt, 1);
333 }
334
335 void
336 rtfree_oncpu(struct rtentry *rt)
337 {
338         KKASSERT(rt->rt_cpuid == mycpuid);
339         KASSERT(rt->rt_refcnt > 0, ("rtfree: rt_refcnt %ld", rt->rt_refcnt));
340
341         --rt->rt_refcnt;
342         if (rt->rt_refcnt == 0) {
343                 struct radix_node_head *rnh =
344                     rt_tables[mycpuid][rt_key(rt)->sa_family];
345
346                 if (rnh->rnh_close)
347                         rnh->rnh_close((struct radix_node *)rt, rnh);
348                 if (!(rt->rt_flags & RTF_UP)) {
349                         /* deallocate route */
350                         if (rt->rt_ifa != NULL)
351                                 IFAFREE(rt->rt_ifa);
352                         if (rt->rt_parent != NULL)
353                                 RTFREE(rt->rt_parent);  /* recursive call! */
354                         Free(rt_key(rt));
355                         Free(rt);
356                 }
357         }
358 }
359
360 static void
361 rtfree_remote_dispatch(struct netmsg *nmsg)
362 {
363         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
364         struct rtentry *rt = lmsg->u.ms_resultp;
365
366         rtfree_oncpu(rt);
367         lwkt_replymsg(lmsg, 0);
368 }
369
370 void
371 rtfree_remote(struct rtentry *rt, int allow_panic)
372 {
373         struct netmsg nmsg;
374         struct lwkt_msg *lmsg;
375
376         KKASSERT(rt->rt_cpuid != mycpuid);
377
378         if (route_assert_owner_access && allow_panic) {
379                 panic("rt remote free rt_cpuid %d, mycpuid %d\n",
380                       rt->rt_cpuid, mycpuid);
381         } else {
382                 kprintf("rt remote free rt_cpuid %d, mycpuid %d\n",
383                         rt->rt_cpuid, mycpuid);
384                 print_backtrace();
385         }
386
387         netmsg_init(&nmsg, &curthread->td_msgport, 0, rtfree_remote_dispatch);
388         lmsg = &nmsg.nm_lmsg;
389         lmsg->u.ms_resultp = rt;
390
391         lwkt_domsg(rtable_portfn(rt->rt_cpuid), lmsg, 0);
392 }
393
394 static int
395 rtredirect_oncpu(struct sockaddr *dst, struct sockaddr *gateway,
396                  struct sockaddr *netmask, int flags, struct sockaddr *src)
397 {
398         struct rtentry *rt = NULL;
399         struct rt_addrinfo rtinfo;
400         struct ifaddr *ifa;
401         u_long *stat = NULL;
402         int error;
403
404         /* verify the gateway is directly reachable */
405         if ((ifa = ifa_ifwithnet(gateway)) == NULL) {
406                 error = ENETUNREACH;
407                 goto out;
408         }
409
410         /*
411          * If the redirect isn't from our current router for this destination,
412          * it's either old or wrong.
413          */
414         if (!(flags & RTF_DONE) &&              /* XXX JH */
415             (rt = rtpurelookup(dst)) != NULL &&
416             (!sa_equal(src, rt->rt_gateway) || rt->rt_ifa != ifa)) {
417                 error = EINVAL;
418                 goto done;
419         }
420
421         /*
422          * If it redirects us to ourselves, we have a routing loop,
423          * perhaps as a result of an interface going down recently.
424          */
425         if (ifa_ifwithaddr(gateway)) {
426                 error = EHOSTUNREACH;
427                 goto done;
428         }
429
430         /*
431          * Create a new entry if the lookup failed or if we got back
432          * a wildcard entry for the default route.  This is necessary
433          * for hosts which use routing redirects generated by smart
434          * gateways to dynamically build the routing tables.
435          */
436         if (rt == NULL)
437                 goto create;
438         if ((rt_mask(rt) != NULL && rt_mask(rt)->sa_len < 2)) {
439                 rtfree(rt);
440                 goto create;
441         }
442
443         /* Ignore redirects for directly connected hosts. */
444         if (!(rt->rt_flags & RTF_GATEWAY)) {
445                 error = EHOSTUNREACH;
446                 goto done;
447         }
448
449         if (!(rt->rt_flags & RTF_HOST) && (flags & RTF_HOST)) {
450                 /*
451                  * Changing from a network route to a host route.
452                  * Create a new host route rather than smashing the
453                  * network route.
454                  */
455 create:
456                 flags |=  RTF_GATEWAY | RTF_DYNAMIC;
457                 bzero(&rtinfo, sizeof(struct rt_addrinfo));
458                 rtinfo.rti_info[RTAX_DST] = dst;
459                 rtinfo.rti_info[RTAX_GATEWAY] = gateway;
460                 rtinfo.rti_info[RTAX_NETMASK] = netmask;
461                 rtinfo.rti_flags = flags;
462                 rtinfo.rti_ifa = ifa;
463                 rt = NULL;      /* copy-in/copy-out parameter */
464                 error = rtrequest1(RTM_ADD, &rtinfo, &rt);
465                 if (rt != NULL)
466                         flags = rt->rt_flags;
467                 stat = &rtstat.rts_dynamic;
468         } else {
469                 /*
470                  * Smash the current notion of the gateway to this destination.
471                  * Should check about netmask!!!
472                  */
473                 rt->rt_flags |= RTF_MODIFIED;
474                 flags |= RTF_MODIFIED;
475
476                 /* We only need to report rtmsg on CPU0 */
477                 rt_setgate(rt, rt_key(rt), gateway,
478                            mycpuid == 0 ? RTL_REPORTMSG : RTL_DONTREPORT);
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         boolean_t reportmsg;
822         int error = 0;
823
824 #define gotoerr(x) { error = x ; goto bad; }
825
826 #ifdef ROUTE_DEBUG
827         if (route_debug)
828                 rt_addrinfo_print(req, rtinfo);
829 #endif
830
831         crit_enter();
832         /*
833          * Find the correct routing tree to use for this Address Family
834          */
835         if ((rnh = rt_tables[mycpuid][dst->sa_family]) == NULL)
836                 gotoerr(EAFNOSUPPORT);
837
838         /*
839          * If we are adding a host route then we don't want to put
840          * a netmask in the tree, nor do we want to clone it.
841          */
842         if (rtinfo->rti_flags & RTF_HOST) {
843                 rtinfo->rti_info[RTAX_NETMASK] = NULL;
844                 rtinfo->rti_flags &= ~(RTF_CLONING | RTF_PRCLONING);
845         }
846
847         switch (req) {
848         case RTM_DELETE:
849                 /* Remove the item from the tree. */
850                 rn = rnh->rnh_deladdr((char *)rtinfo->rti_info[RTAX_DST],
851                                       (char *)rtinfo->rti_info[RTAX_NETMASK],
852                                       rnh);
853                 if (rn == NULL)
854                         gotoerr(ESRCH);
855                 KASSERT(!(rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)),
856                         ("rnh_deladdr returned flags 0x%x", rn->rn_flags));
857                 rt = (struct rtentry *)rn;
858
859                 /* ref to prevent a deletion race */
860                 ++rt->rt_refcnt;
861
862                 /* Free any routes cloned from this one. */
863                 if ((rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) &&
864                     rt_mask(rt) != NULL) {
865                         rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
866                                                (char *)rt_mask(rt),
867                                                rt_fixdelete, rt);
868                 }
869
870                 if (rt->rt_gwroute != NULL) {
871                         RTFREE(rt->rt_gwroute);
872                         rt->rt_gwroute = NULL;
873                 }
874
875                 /*
876                  * NB: RTF_UP must be set during the search above,
877                  * because we might delete the last ref, causing
878                  * rt to get freed prematurely.
879                  */
880                 rt->rt_flags &= ~RTF_UP;
881
882 #ifdef ROUTE_DEBUG
883                 if (route_debug)
884                         rt_print(rtinfo, rt);
885 #endif
886
887                 /* Give the protocol a chance to keep things in sync. */
888                 if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
889                         ifa->ifa_rtrequest(RTM_DELETE, rt, rtinfo);
890
891                 /*
892                  * If the caller wants it, then it can have it,
893                  * but it's up to it to free the rtentry as we won't be
894                  * doing it.
895                  */
896                 KASSERT(rt->rt_refcnt >= 0,
897                         ("rtrequest1(DELETE): refcnt %ld", rt->rt_refcnt));
898                 if (ret_nrt != NULL) {
899                         /* leave ref intact for return */
900                         *ret_nrt = rt;
901                 } else {
902                         /* deref / attempt to destroy */
903                         rtfree(rt);
904                 }
905                 break;
906
907         case RTM_RESOLVE:
908                 if (ret_nrt == NULL || (rt = *ret_nrt) == NULL)
909                         gotoerr(EINVAL);
910                 ifa = rt->rt_ifa;
911                 rtinfo->rti_flags =
912                     rt->rt_flags & ~(RTF_CLONING | RTF_PRCLONING | RTF_STATIC);
913                 rtinfo->rti_flags |= RTF_WASCLONED;
914                 rtinfo->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
915                 if ((rtinfo->rti_info[RTAX_NETMASK] = rt->rt_genmask) == NULL)
916                         rtinfo->rti_flags |= RTF_HOST;
917                 rtinfo->rti_info[RTAX_MPLS1] = rt->rt_shim[0];
918                 rtinfo->rti_info[RTAX_MPLS2] = rt->rt_shim[1];
919                 rtinfo->rti_info[RTAX_MPLS3] = rt->rt_shim[2];
920                 goto makeroute;
921
922         case RTM_ADD:
923                 KASSERT(!(rtinfo->rti_flags & RTF_GATEWAY) ||
924                         rtinfo->rti_info[RTAX_GATEWAY] != NULL,
925                     ("rtrequest: GATEWAY but no gateway"));
926
927                 if (rtinfo->rti_ifa == NULL && (error = rt_getifa(rtinfo)))
928                         gotoerr(error);
929                 ifa = rtinfo->rti_ifa;
930 makeroute:
931                 R_Malloc(rt, struct rtentry *, sizeof(struct rtentry));
932                 if (rt == NULL)
933                         gotoerr(ENOBUFS);
934                 bzero(rt, sizeof(struct rtentry));
935                 rt->rt_flags = RTF_UP | rtinfo->rti_flags;
936                 rt->rt_cpuid = mycpuid;
937
938                 if (mycpuid != 0 && req == RTM_ADD) {
939                         /* For RTM_ADD, we have already sent rtmsg on CPU0. */
940                         reportmsg = RTL_DONTREPORT;
941                 } else {
942                         /*
943                          * For RTM_ADD, we only send rtmsg on CPU0.
944                          * For RTM_RESOLVE, we always send rtmsg. XXX
945                          */
946                         reportmsg = RTL_REPORTMSG;
947                 }
948                 error = rt_setgate(rt, dst, rtinfo->rti_info[RTAX_GATEWAY],
949                                    reportmsg);
950                 if (error != 0) {
951                         Free(rt);
952                         gotoerr(error);
953                 }
954
955                 ndst = rt_key(rt);
956                 if (rtinfo->rti_info[RTAX_NETMASK] != NULL)
957                         rt_maskedcopy(dst, ndst,
958                                       rtinfo->rti_info[RTAX_NETMASK]);
959                 else
960                         bcopy(dst, ndst, dst->sa_len);
961
962                 if (rtinfo->rti_info[RTAX_MPLS1] != NULL)
963                         rt_setshims(rt, rtinfo->rti_info);
964
965                 /*
966                  * Note that we now have a reference to the ifa.
967                  * This moved from below so that rnh->rnh_addaddr() can
968                  * examine the ifa and  ifa->ifa_ifp if it so desires.
969                  */
970                 IFAREF(ifa);
971                 rt->rt_ifa = ifa;
972                 rt->rt_ifp = ifa->ifa_ifp;
973                 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
974
975                 rn = rnh->rnh_addaddr((char *)ndst,
976                                       (char *)rtinfo->rti_info[RTAX_NETMASK],
977                                       rnh, rt->rt_nodes);
978                 if (rn == NULL) {
979                         struct rtentry *oldrt;
980
981                         /*
982                          * We already have one of these in the tree.
983                          * We do a special hack: if the old route was
984                          * cloned, then we blow it away and try
985                          * re-inserting the new one.
986                          */
987                         oldrt = rtpurelookup(ndst);
988                         if (oldrt != NULL) {
989                                 --oldrt->rt_refcnt;
990                                 if (oldrt->rt_flags & RTF_WASCLONED) {
991                                         rtrequest(RTM_DELETE, rt_key(oldrt),
992                                                   oldrt->rt_gateway,
993                                                   rt_mask(oldrt),
994                                                   oldrt->rt_flags, NULL);
995                                         rn = rnh->rnh_addaddr((char *)ndst,
996                                             (char *)
997                                                 rtinfo->rti_info[RTAX_NETMASK],
998                                             rnh, rt->rt_nodes);
999                                 }
1000                         }
1001                 }
1002
1003                 /*
1004                  * If it still failed to go into the tree,
1005                  * then un-make it (this should be a function).
1006                  */
1007                 if (rn == NULL) {
1008                         if (rt->rt_gwroute != NULL)
1009                                 rtfree(rt->rt_gwroute);
1010                         IFAFREE(ifa);
1011                         Free(rt_key(rt));
1012                         Free(rt);
1013                         gotoerr(EEXIST);
1014                 }
1015
1016                 /*
1017                  * If we got here from RESOLVE, then we are cloning
1018                  * so clone the rest, and note that we
1019                  * are a clone (and increment the parent's references)
1020                  */
1021                 if (req == RTM_RESOLVE) {
1022                         rt->rt_rmx = (*ret_nrt)->rt_rmx;    /* copy metrics */
1023                         rt->rt_rmx.rmx_pksent = 0;  /* reset packet counter */
1024                         if ((*ret_nrt)->rt_flags &
1025                                        (RTF_CLONING | RTF_PRCLONING)) {
1026                                 rt->rt_parent = *ret_nrt;
1027                                 (*ret_nrt)->rt_refcnt++;
1028                         }
1029                 }
1030
1031                 /*
1032                  * if this protocol has something to add to this then
1033                  * allow it to do that as well.
1034                  */
1035                 if (ifa->ifa_rtrequest != NULL)
1036                         ifa->ifa_rtrequest(req, rt, rtinfo);
1037
1038                 /*
1039                  * We repeat the same procedure from rt_setgate() here because
1040                  * it doesn't fire when we call it there because the node
1041                  * hasn't been added to the tree yet.
1042                  */
1043                 if (req == RTM_ADD && !(rt->rt_flags & RTF_HOST) &&
1044                     rt_mask(rt) != NULL) {
1045                         struct rtfc_arg arg = { rt, rnh };
1046
1047                         rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
1048                                                (char *)rt_mask(rt),
1049                                                rt_fixchange, &arg);
1050                 }
1051
1052 #ifdef ROUTE_DEBUG
1053                 if (route_debug)
1054                         rt_print(rtinfo, rt);
1055 #endif
1056                 /*
1057                  * Return the resulting rtentry,
1058                  * increasing the number of references by one.
1059                  */
1060                 if (ret_nrt != NULL) {
1061                         rt->rt_refcnt++;
1062                         *ret_nrt = rt;
1063                 }
1064                 break;
1065         default:
1066                 error = EOPNOTSUPP;
1067         }
1068 bad:
1069 #ifdef ROUTE_DEBUG
1070         if (route_debug) {
1071                 if (error)
1072                         kprintf("rti %p failed error %d\n", rtinfo, error);
1073                 else
1074                         kprintf("rti %p succeeded\n", rtinfo);
1075         }
1076 #endif
1077         crit_exit();
1078         return (error);
1079 }
1080
1081 /*
1082  * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
1083  * (i.e., the routes related to it by the operation of cloning).  This
1084  * routine is iterated over all potential former-child-routes by way of
1085  * rnh->rnh_walktree_from() above, and those that actually are children of
1086  * the late parent (passed in as VP here) are themselves deleted.
1087  */
1088 static int
1089 rt_fixdelete(struct radix_node *rn, void *vp)
1090 {
1091         struct rtentry *rt = (struct rtentry *)rn;
1092         struct rtentry *rt0 = vp;
1093
1094         if (rt->rt_parent == rt0 &&
1095             !(rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1096                 return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1097                                  rt->rt_flags, NULL);
1098         }
1099         return 0;
1100 }
1101
1102 /*
1103  * This routine is called from rt_setgate() to do the analogous thing for
1104  * adds and changes.  There is the added complication in this case of a
1105  * middle insert; i.e., insertion of a new network route between an older
1106  * network route and (cloned) host routes.  For this reason, a simple check
1107  * of rt->rt_parent is insufficient; each candidate route must be tested
1108  * against the (mask, value) of the new route (passed as before in vp)
1109  * to see if the new route matches it.
1110  *
1111  * XXX - it may be possible to do fixdelete() for changes and reserve this
1112  * routine just for adds.  I'm not sure why I thought it was necessary to do
1113  * changes this way.
1114  */
1115 #ifdef DEBUG
1116 static int rtfcdebug = 0;
1117 #endif
1118
1119 static int
1120 rt_fixchange(struct radix_node *rn, void *vp)
1121 {
1122         struct rtentry *rt = (struct rtentry *)rn;
1123         struct rtfc_arg *ap = vp;
1124         struct rtentry *rt0 = ap->rt0;
1125         struct radix_node_head *rnh = ap->rnh;
1126         u_char *xk1, *xm1, *xk2, *xmp;
1127         int i, len, mlen;
1128
1129 #ifdef DEBUG
1130         if (rtfcdebug)
1131                 kprintf("rt_fixchange: rt %p, rt0 %p\n", rt, rt0);
1132 #endif
1133
1134         if (rt->rt_parent == NULL ||
1135             (rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
1136 #ifdef DEBUG
1137                 if (rtfcdebug) kprintf("no parent, pinned or cloning\n");
1138 #endif
1139                 return 0;
1140         }
1141
1142         if (rt->rt_parent == rt0) {
1143 #ifdef DEBUG
1144                 if (rtfcdebug) kprintf("parent match\n");
1145 #endif
1146                 return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1147                                  rt->rt_flags, NULL);
1148         }
1149
1150         /*
1151          * There probably is a function somewhere which does this...
1152          * if not, there should be.
1153          */
1154         len = imin(rt_key(rt0)->sa_len, rt_key(rt)->sa_len);
1155
1156         xk1 = (u_char *)rt_key(rt0);
1157         xm1 = (u_char *)rt_mask(rt0);
1158         xk2 = (u_char *)rt_key(rt);
1159
1160         /* avoid applying a less specific route */
1161         xmp = (u_char *)rt_mask(rt->rt_parent);
1162         mlen = rt_key(rt->rt_parent)->sa_len;
1163         if (mlen > rt_key(rt0)->sa_len) {
1164 #ifdef DEBUG
1165                 if (rtfcdebug)
1166                         kprintf("rt_fixchange: inserting a less "
1167                                "specific route\n");
1168 #endif
1169                 return 0;
1170         }
1171         for (i = rnh->rnh_treetop->rn_offset; i < mlen; i++) {
1172                 if ((xmp[i] & ~(xmp[i] ^ xm1[i])) != xmp[i]) {
1173 #ifdef DEBUG
1174                         if (rtfcdebug)
1175                                 kprintf("rt_fixchange: inserting a less "
1176                                        "specific route\n");
1177 #endif
1178                         return 0;
1179                 }
1180         }
1181
1182         for (i = rnh->rnh_treetop->rn_offset; i < len; i++) {
1183                 if ((xk2[i] & xm1[i]) != xk1[i]) {
1184 #ifdef DEBUG
1185                         if (rtfcdebug) kprintf("no match\n");
1186 #endif
1187                         return 0;
1188                 }
1189         }
1190
1191         /*
1192          * OK, this node is a clone, and matches the node currently being
1193          * changed/added under the node's mask.  So, get rid of it.
1194          */
1195 #ifdef DEBUG
1196         if (rtfcdebug) kprintf("deleting\n");
1197 #endif
1198         return rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt),
1199                          rt->rt_flags, NULL);
1200 }
1201
1202 #define ROUNDUP(a) (a>0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
1203
1204 int
1205 rt_setgate(struct rtentry *rt0, struct sockaddr *dst, struct sockaddr *gate,
1206            boolean_t generate_report)
1207 {
1208         char *space, *oldspace;
1209         int dlen = ROUNDUP(dst->sa_len), glen = ROUNDUP(gate->sa_len);
1210         struct rtentry *rt = rt0;
1211         struct radix_node_head *rnh = rt_tables[mycpuid][dst->sa_family];
1212
1213         /*
1214          * A host route with the destination equal to the gateway
1215          * will interfere with keeping LLINFO in the routing
1216          * table, so disallow it.
1217          */
1218         if (((rt0->rt_flags & (RTF_HOST | RTF_GATEWAY | RTF_LLINFO)) ==
1219                               (RTF_HOST | RTF_GATEWAY)) &&
1220             dst->sa_len == gate->sa_len &&
1221             sa_equal(dst, gate)) {
1222                 /*
1223                  * The route might already exist if this is an RTM_CHANGE
1224                  * or a routing redirect, so try to delete it.
1225                  */
1226                 if (rt_key(rt0) != NULL)
1227                         rtrequest(RTM_DELETE, rt_key(rt0), rt0->rt_gateway,
1228                                   rt_mask(rt0), rt0->rt_flags, NULL);
1229                 return EADDRNOTAVAIL;
1230         }
1231
1232         /*
1233          * Both dst and gateway are stored in the same malloc'ed chunk
1234          * (If I ever get my hands on....)
1235          * if we need to malloc a new chunk, then keep the old one around
1236          * till we don't need it any more.
1237          */
1238         if (rt->rt_gateway == NULL || glen > ROUNDUP(rt->rt_gateway->sa_len)) {
1239                 oldspace = (char *)rt_key(rt);
1240                 R_Malloc(space, char *, dlen + glen);
1241                 if (space == NULL)
1242                         return ENOBUFS;
1243                 rt->rt_nodes->rn_key = space;
1244         } else {
1245                 space = (char *)rt_key(rt);     /* Just use the old space. */
1246                 oldspace = NULL;
1247         }
1248
1249         /* Set the gateway value. */
1250         rt->rt_gateway = (struct sockaddr *)(space + dlen);
1251         bcopy(gate, rt->rt_gateway, glen);
1252
1253         if (oldspace != NULL) {
1254                 /*
1255                  * If we allocated a new chunk, preserve the original dst.
1256                  * This way, rt_setgate() really just sets the gate
1257                  * and leaves the dst field alone.
1258                  */
1259                 bcopy(dst, space, dlen);
1260                 Free(oldspace);
1261         }
1262
1263         /*
1264          * If there is already a gwroute, it's now almost definitely wrong
1265          * so drop it.
1266          */
1267         if (rt->rt_gwroute != NULL) {
1268                 RTFREE(rt->rt_gwroute);
1269                 rt->rt_gwroute = NULL;
1270         }
1271         if (rt->rt_flags & RTF_GATEWAY) {
1272                 /*
1273                  * Cloning loop avoidance: In the presence of
1274                  * protocol-cloning and bad configuration, it is
1275                  * possible to get stuck in bottomless mutual recursion
1276                  * (rtrequest rt_setgate rtlookup).  We avoid this
1277                  * by not allowing protocol-cloning to operate for
1278                  * gateways (which is probably the correct choice
1279                  * anyway), and avoid the resulting reference loops
1280                  * by disallowing any route to run through itself as
1281                  * a gateway.  This is obviously mandatory when we
1282                  * get rt->rt_output().
1283                  *
1284                  * This breaks TTCP for hosts outside the gateway!  XXX JH
1285                  */
1286                 rt->rt_gwroute = _rtlookup(gate, generate_report,
1287                                            RTF_PRCLONING);
1288                 if (rt->rt_gwroute == rt) {
1289                         rt->rt_gwroute = NULL;
1290                         --rt->rt_refcnt;
1291                         return EDQUOT; /* failure */
1292                 }
1293         }
1294
1295         /*
1296          * This isn't going to do anything useful for host routes, so
1297          * don't bother.  Also make sure we have a reasonable mask
1298          * (we don't yet have one during adds).
1299          */
1300         if (!(rt->rt_flags & RTF_HOST) && rt_mask(rt) != NULL) {
1301                 struct rtfc_arg arg = { rt, rnh };
1302
1303                 rnh->rnh_walktree_from(rnh, (char *)rt_key(rt),
1304                                        (char *)rt_mask(rt),
1305                                        rt_fixchange, &arg);
1306         }
1307
1308         return 0;
1309 }
1310
1311 static void
1312 rt_maskedcopy(
1313         struct sockaddr *src,
1314         struct sockaddr *dst,
1315         struct sockaddr *netmask)
1316 {
1317         u_char *cp1 = (u_char *)src;
1318         u_char *cp2 = (u_char *)dst;
1319         u_char *cp3 = (u_char *)netmask;
1320         u_char *cplim = cp2 + *cp3;
1321         u_char *cplim2 = cp2 + *cp1;
1322
1323         *cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1324         cp3 += 2;
1325         if (cplim > cplim2)
1326                 cplim = cplim2;
1327         while (cp2 < cplim)
1328                 *cp2++ = *cp1++ & *cp3++;
1329         if (cp2 < cplim2)
1330                 bzero(cp2, cplim2 - cp2);
1331 }
1332
1333 int
1334 rt_llroute(struct sockaddr *dst, struct rtentry *rt0, struct rtentry **drt)
1335 {
1336         struct rtentry *up_rt, *rt;
1337
1338         if (!(rt0->rt_flags & RTF_UP)) {
1339                 up_rt = rtlookup(dst);
1340                 if (up_rt == NULL)
1341                         return (EHOSTUNREACH);
1342                 up_rt->rt_refcnt--;
1343         } else
1344                 up_rt = rt0;
1345         if (up_rt->rt_flags & RTF_GATEWAY) {
1346                 if (up_rt->rt_gwroute == NULL) {
1347                         up_rt->rt_gwroute = rtlookup(up_rt->rt_gateway);
1348                         if (up_rt->rt_gwroute == NULL)
1349                                 return (EHOSTUNREACH);
1350                 } else if (!(up_rt->rt_gwroute->rt_flags & RTF_UP)) {
1351                         rtfree(up_rt->rt_gwroute);
1352                         up_rt->rt_gwroute = rtlookup(up_rt->rt_gateway);
1353                         if (up_rt->rt_gwroute == NULL)
1354                                 return (EHOSTUNREACH);
1355                 }
1356                 rt = up_rt->rt_gwroute;
1357         } else
1358                 rt = up_rt;
1359         if (rt->rt_flags & RTF_REJECT &&
1360             (rt->rt_rmx.rmx_expire == 0 ||              /* rt doesn't expire */
1361              time_second < rt->rt_rmx.rmx_expire))      /* rt not expired */
1362                 return (rt->rt_flags & RTF_HOST ?  EHOSTDOWN : EHOSTUNREACH);
1363         *drt = rt;
1364         return 0;
1365 }
1366
1367 static int
1368 rt_setshims(struct rtentry *rt, struct sockaddr **rt_shim){
1369         int i;
1370         
1371         for (i=0; i<3; i++) {
1372                 struct sockaddr *shim = rt_shim[RTAX_MPLS1 + i];
1373                 int shimlen;
1374
1375                 if (shim == NULL)
1376                         break;
1377
1378                 shimlen = ROUNDUP(shim->sa_len);
1379                 R_Malloc(rt->rt_shim[i], struct sockaddr *, shimlen);
1380                 bcopy(shim, rt->rt_shim[i], shimlen);
1381         }
1382
1383         return 0;
1384 }
1385
1386 #ifdef ROUTE_DEBUG
1387
1388 /*
1389  * Print out a route table entry
1390  */
1391 void
1392 rt_print(struct rt_addrinfo *rtinfo, struct rtentry *rn)
1393 {
1394         kprintf("rti %p cpu %d route %p flags %08lx: ", 
1395                 rtinfo, mycpuid, rn, rn->rt_flags);
1396         sockaddr_print(rt_key(rn));
1397         kprintf(" mask ");
1398         sockaddr_print(rt_mask(rn));
1399         kprintf(" gw ");
1400         sockaddr_print(rn->rt_gateway);
1401         kprintf(" ifc \"%s\"", rn->rt_ifp ? rn->rt_ifp->if_dname : "?");
1402         kprintf(" ifa %p\n", rn->rt_ifa);
1403 }
1404
1405 void
1406 rt_addrinfo_print(int cmd, struct rt_addrinfo *rti)
1407 {
1408         int didit = 0;
1409         int i;
1410
1411 #ifdef ROUTE_DEBUG
1412         if (cmd == RTM_DELETE && route_debug > 1)
1413                 print_backtrace();
1414 #endif
1415
1416         switch(cmd) {
1417         case RTM_ADD:
1418                 kprintf("ADD ");
1419                 break;
1420         case RTM_RESOLVE:
1421                 kprintf("RES ");
1422                 break;
1423         case RTM_DELETE:
1424                 kprintf("DEL ");
1425                 break;
1426         default:
1427                 kprintf("C%02d ", cmd);
1428                 break;
1429         }
1430         kprintf("rti %p cpu %d ", rti, mycpuid);
1431         for (i = 0; i < rti->rti_addrs; ++i) {
1432                 if (rti->rti_info[i] == NULL)
1433                         continue;
1434                 if (didit)
1435                         kprintf(" ,");
1436                 switch(i) {
1437                 case RTAX_DST:
1438                         kprintf("(DST ");
1439                         break;
1440                 case RTAX_GATEWAY:
1441                         kprintf("(GWY ");
1442                         break;
1443                 case RTAX_NETMASK:
1444                         kprintf("(MSK ");
1445                         break;
1446                 case RTAX_GENMASK:
1447                         kprintf("(GEN ");
1448                         break;
1449                 case RTAX_IFP:
1450                         kprintf("(IFP ");
1451                         break;
1452                 case RTAX_IFA:
1453                         kprintf("(IFA ");
1454                         break;
1455                 case RTAX_AUTHOR:
1456                         kprintf("(AUT ");
1457                         break;
1458                 case RTAX_BRD:
1459                         kprintf("(BRD ");
1460                         break;
1461                 default:
1462                         kprintf("(?%02d ", i);
1463                         break;
1464                 }
1465                 sockaddr_print(rti->rti_info[i]);
1466                 kprintf(")");
1467                 didit = 1;
1468         }
1469         kprintf("\n");
1470 }
1471
1472 void
1473 sockaddr_print(struct sockaddr *sa)
1474 {
1475         struct sockaddr_in *sa4;
1476         struct sockaddr_in6 *sa6;
1477         int len;
1478         int i;
1479
1480         if (sa == NULL) {
1481                 kprintf("NULL");
1482                 return;
1483         }
1484
1485         len = sa->sa_len - offsetof(struct sockaddr, sa_data[0]);
1486
1487         switch(sa->sa_family) {
1488         case AF_INET:
1489         case AF_INET6:
1490         default:
1491                 switch(sa->sa_family) {
1492                 case AF_INET:
1493                         sa4 = (struct sockaddr_in *)sa;
1494                         kprintf("INET %d %d.%d.%d.%d",
1495                                 ntohs(sa4->sin_port),
1496                                 (ntohl(sa4->sin_addr.s_addr) >> 24) & 255,
1497                                 (ntohl(sa4->sin_addr.s_addr) >> 16) & 255,
1498                                 (ntohl(sa4->sin_addr.s_addr) >> 8) & 255,
1499                                 (ntohl(sa4->sin_addr.s_addr) >> 0) & 255
1500                         );
1501                         break;
1502                 case AF_INET6:
1503                         sa6 = (struct sockaddr_in6 *)sa;
1504                         kprintf("INET6 %d %04x:%04x%04x:%04x:%04x:%04x:%04x:%04x",
1505                                 ntohs(sa6->sin6_port),
1506                                 sa6->sin6_addr.s6_addr16[0],
1507                                 sa6->sin6_addr.s6_addr16[1],
1508                                 sa6->sin6_addr.s6_addr16[2],
1509                                 sa6->sin6_addr.s6_addr16[3],
1510                                 sa6->sin6_addr.s6_addr16[4],
1511                                 sa6->sin6_addr.s6_addr16[5],
1512                                 sa6->sin6_addr.s6_addr16[6],
1513                                 sa6->sin6_addr.s6_addr16[7]
1514                         );
1515                         break;
1516                 default:
1517                         kprintf("AF%d ", sa->sa_family);
1518                         while (len > 0 && sa->sa_data[len-1] == 0)
1519                                 --len;
1520
1521                         for (i = 0; i < len; ++i) {
1522                                 if (i)
1523                                         kprintf(".");
1524                                 kprintf("%d", (unsigned char)sa->sa_data[i]);
1525                         }
1526                         break;
1527                 }
1528         }
1529 }
1530
1531 #endif
1532
1533 /*
1534  * Set up a routing table entry, normally for an interface.
1535  */
1536 int
1537 rtinit(struct ifaddr *ifa, int cmd, int flags)
1538 {
1539         struct sockaddr *dst, *deldst, *netmask;
1540         struct mbuf *m = NULL;
1541         struct radix_node_head *rnh;
1542         struct radix_node *rn;
1543         struct rt_addrinfo rtinfo;
1544         int error;
1545
1546         if (flags & RTF_HOST) {
1547                 dst = ifa->ifa_dstaddr;
1548                 netmask = NULL;
1549         } else {
1550                 dst = ifa->ifa_addr;
1551                 netmask = ifa->ifa_netmask;
1552         }
1553         /*
1554          * If it's a delete, check that if it exists, it's on the correct
1555          * interface or we might scrub a route to another ifa which would
1556          * be confusing at best and possibly worse.
1557          */
1558         if (cmd == RTM_DELETE) {
1559                 /*
1560                  * It's a delete, so it should already exist..
1561                  * If it's a net, mask off the host bits
1562                  * (Assuming we have a mask)
1563                  */
1564                 if (netmask != NULL) {
1565                         m = m_get(MB_DONTWAIT, MT_SONAME);
1566                         if (m == NULL)
1567                                 return (ENOBUFS);
1568                         mbuftrackid(m, 34);
1569                         deldst = mtod(m, struct sockaddr *);
1570                         rt_maskedcopy(dst, deldst, netmask);
1571                         dst = deldst;
1572                 }
1573                 /*
1574                  * Look up an rtentry that is in the routing tree and
1575                  * contains the correct info.
1576                  */
1577                 if ((rnh = rt_tables[mycpuid][dst->sa_family]) == NULL ||
1578                     (rn = rnh->rnh_lookup((char *)dst,
1579                                           (char *)netmask, rnh)) == NULL ||
1580                     ((struct rtentry *)rn)->rt_ifa != ifa ||
1581                     !sa_equal((struct sockaddr *)rn->rn_key, dst)) {
1582                         if (m != NULL)
1583                                 m_free(m);
1584                         return (flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1585                 }
1586                 /* XXX */
1587 #if 0
1588                 else {
1589                         /*
1590                          * One would think that as we are deleting, and we know
1591                          * it doesn't exist, we could just return at this point
1592                          * with an "ELSE" clause, but apparently not..
1593                          */
1594                         return (flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1595                 }
1596 #endif
1597         }
1598         /*
1599          * Do the actual request
1600          */
1601         bzero(&rtinfo, sizeof(struct rt_addrinfo));
1602         rtinfo.rti_info[RTAX_DST] = dst;
1603         rtinfo.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1604         rtinfo.rti_info[RTAX_NETMASK] = netmask;
1605         rtinfo.rti_flags = flags | ifa->ifa_flags;
1606         rtinfo.rti_ifa = ifa;
1607         error = rtrequest1_global(cmd, &rtinfo, rtinit_rtrequest_callback, ifa);
1608         if (m != NULL)
1609                 m_free(m);
1610         return (error);
1611 }
1612
1613 static void
1614 rtinit_rtrequest_callback(int cmd, int error,
1615                           struct rt_addrinfo *rtinfo, struct rtentry *rt,
1616                           void *arg)
1617 {
1618         struct ifaddr *ifa = arg;
1619
1620         if (error == 0 && rt) {
1621                 if (mycpuid == 0) {
1622                         ++rt->rt_refcnt;
1623                         rt_newaddrmsg(cmd, ifa, error, rt);
1624                         --rt->rt_refcnt;
1625                 }
1626                 if (cmd == RTM_DELETE) {
1627                         if (rt->rt_refcnt == 0) {
1628                                 ++rt->rt_refcnt;
1629                                 rtfree(rt);
1630                         }
1631                 }
1632         }
1633 }
1634
1635 struct netmsg_rts {
1636         struct netmsg           netmsg;
1637         int                     req;
1638         struct rt_addrinfo      *rtinfo;
1639         rtsearch_callback_func_t callback;
1640         void                    *arg;
1641         boolean_t               exact_match;
1642         int                     found_cnt;
1643 };
1644
1645 int
1646 rtsearch_global(int req, struct rt_addrinfo *rtinfo,
1647                 rtsearch_callback_func_t callback, void *arg,
1648                 boolean_t exact_match)
1649 {
1650         struct netmsg_rts msg;
1651
1652         netmsg_init(&msg.netmsg, &curthread->td_msgport, 0,
1653                     rtsearch_msghandler);
1654         msg.req = req;
1655         msg.rtinfo = rtinfo;
1656         msg.callback = callback;
1657         msg.arg = arg;
1658         msg.exact_match = exact_match;
1659         msg.found_cnt = 0;
1660         return lwkt_domsg(rtable_portfn(0), &msg.netmsg.nm_lmsg, 0);
1661 }
1662
1663 static void
1664 rtsearch_msghandler(struct netmsg *netmsg)
1665 {
1666         struct netmsg_rts *msg = (void *)netmsg;
1667         struct rt_addrinfo *rtinfo = msg->rtinfo;
1668         struct radix_node_head *rnh;
1669         struct rtentry *rt;
1670         int nextcpu, error;
1671
1672         /*
1673          * Find the correct routing tree to use for this Address Family
1674          */
1675         if ((rnh = rt_tables[mycpuid][rtinfo->rti_dst->sa_family]) == NULL) {
1676                 if (mycpuid != 0)
1677                         panic("partially initialized routing tables\n");
1678                 lwkt_replymsg(&msg->netmsg.nm_lmsg, EAFNOSUPPORT);
1679                 return;
1680         }
1681
1682         /*
1683          * Correct rtinfo for the host route searching.
1684          */
1685         if (rtinfo->rti_flags & RTF_HOST) {
1686                 rtinfo->rti_netmask = NULL;
1687                 rtinfo->rti_flags &= ~(RTF_CLONING | RTF_PRCLONING);
1688         }
1689
1690         rt = (struct rtentry *)
1691              rnh->rnh_lookup((char *)rtinfo->rti_dst,
1692                              (char *)rtinfo->rti_netmask, rnh);
1693
1694         /*
1695          * If we are asked to do the "exact match", we need to make sure
1696          * that host route searching got a host route while a network
1697          * route searching got a network route.
1698          */
1699         if (rt != NULL && msg->exact_match &&
1700             ((rt->rt_flags ^ rtinfo->rti_flags) & RTF_HOST))
1701                 rt = NULL;
1702
1703         if (rt == NULL) {
1704                 /*
1705                  * No matching routes have been found, don't count this
1706                  * as a critical error (here, we set 'error' to 0), just
1707                  * keep moving on, since at least prcloned routes are not
1708                  * duplicated onto each CPU.
1709                  */
1710                 error = 0;
1711         } else {
1712                 msg->found_cnt++;
1713
1714                 rt->rt_refcnt++;
1715                 error = msg->callback(msg->req, msg->rtinfo, rt, msg->arg);
1716                 rt->rt_refcnt--;
1717
1718                 if (error == EJUSTRETURN) {
1719                         lwkt_replymsg(&msg->netmsg.nm_lmsg, 0);
1720                         return;
1721                 }
1722         }
1723
1724         nextcpu = mycpuid + 1;
1725         if (error) {
1726                 KKASSERT(msg->found_cnt > 0);
1727
1728                 /*
1729                  * Under following cases, unrecoverable error has
1730                  * not occured:
1731                  * o  Request is RTM_GET
1732                  * o  The first time that we find the route, but the
1733                  *    modification fails.
1734                  */
1735                 if (msg->req != RTM_GET && msg->found_cnt > 1) {
1736                         panic("rtsearch_msghandler: unrecoverable error "
1737                               "cpu %d, rtinfo %p", mycpuid, msg->rtinfo);
1738                 }
1739                 lwkt_replymsg(&msg->netmsg.nm_lmsg, error);
1740         } else if (nextcpu < ncpus) {
1741                 lwkt_forwardmsg(rtable_portfn(nextcpu), &msg->netmsg.nm_lmsg);
1742         } else {
1743                 if (msg->found_cnt == 0) {
1744                         /* The requested route was never seen ... */
1745                         error = ESRCH;
1746                 }
1747                 lwkt_replymsg(&msg->netmsg.nm_lmsg, error);
1748         }
1749 }
1750
1751 /* This must be before ip6_init2(), which is now SI_ORDER_MIDDLE */
1752 SYSINIT(route, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);