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