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