]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/net/route.c
Merge r259528, r259528, r260295.
[FreeBSD/stable/10.git] / sys / net / route.c
1 /*-
2  * Copyright (c) 1980, 1986, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      @(#)route.c     8.3.1.1 (Berkeley) 2/23/95
30  * $FreeBSD$
31  */
32 /************************************************************************
33  * Note: In this file a 'fib' is a "forwarding information base"        *
34  * Which is the new name for an in kernel routing (next hop) table.     *
35  ***********************************************************************/
36
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_route.h"
40 #include "opt_mrouting.h"
41 #include "opt_mpath.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/syslog.h>
46 #include <sys/malloc.h>
47 #include <sys/mbuf.h>
48 #include <sys/socket.h>
49 #include <sys/sysctl.h>
50 #include <sys/syslog.h>
51 #include <sys/sysproto.h>
52 #include <sys/proc.h>
53 #include <sys/domain.h>
54 #include <sys/kernel.h>
55
56 #include <net/if.h>
57 #include <net/if_dl.h>
58 #include <net/route.h>
59 #include <net/vnet.h>
60 #include <net/flowtable.h>
61
62 #ifdef RADIX_MPATH
63 #include <net/radix_mpath.h>
64 #endif
65
66 #include <netinet/in.h>
67 #include <netinet/ip_mroute.h>
68
69 #include <vm/uma.h>
70
71 #define RT_MAXFIBS      UINT16_MAX
72
73 /* Kernel config default option. */
74 #ifdef ROUTETABLES
75 #if ROUTETABLES <= 0
76 #error "ROUTETABLES defined too low"
77 #endif
78 #if ROUTETABLES > RT_MAXFIBS
79 #error "ROUTETABLES defined too big"
80 #endif
81 #define RT_NUMFIBS      ROUTETABLES
82 #endif /* ROUTETABLES */
83 /* Initialize to default if not otherwise set. */
84 #ifndef RT_NUMFIBS
85 #define RT_NUMFIBS      1
86 #endif
87
88 /* This is read-only.. */
89 u_int rt_numfibs = RT_NUMFIBS;
90 SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RD, &rt_numfibs, 0, "");
91 /* and this can be set too big but will be fixed before it is used */
92 TUNABLE_INT("net.fibs", &rt_numfibs);
93
94 /*
95  * By default add routes to all fibs for new interfaces.
96  * Once this is set to 0 then only allocate routes on interface
97  * changes for the FIB of the caller when adding a new set of addresses
98  * to an interface.  XXX this is a shotgun aproach to a problem that needs
99  * a more fine grained solution.. that will come.
100  * XXX also has the problems getting the FIB from curthread which will not
101  * always work given the fib can be overridden and prefixes can be added
102  * from the network stack context.
103  */
104 u_int rt_add_addr_allfibs = 1;
105 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RW,
106     &rt_add_addr_allfibs, 0, "");
107 TUNABLE_INT("net.add_addr_allfibs", &rt_add_addr_allfibs);
108
109 VNET_DEFINE(struct rtstat, rtstat);
110 #define V_rtstat        VNET(rtstat)
111
112 VNET_DEFINE(struct radix_node_head *, rt_tables);
113 #define V_rt_tables     VNET(rt_tables)
114
115 VNET_DEFINE(int, rttrash);              /* routes not in table but not freed */
116 #define V_rttrash       VNET(rttrash)
117
118
119 /* compare two sockaddr structures */
120 #define sa_equal(a1, a2) (bcmp((a1), (a2), (a1)->sa_len) == 0)
121
122 /*
123  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
124  * The operation can be done safely (in this code) because a
125  * 'struct rtentry' starts with two 'struct radix_node''s, the first
126  * one representing leaf nodes in the routing tree, which is
127  * what the code in radix.c passes us as a 'struct radix_node'.
128  *
129  * But because there are a lot of assumptions in this conversion,
130  * do not cast explicitly, but always use the macro below.
131  */
132 #define RNTORT(p)       ((struct rtentry *)(p))
133
134 static VNET_DEFINE(uma_zone_t, rtzone);         /* Routing table UMA zone. */
135 #define V_rtzone        VNET(rtzone)
136
137 /*
138  * handler for net.my_fibnum
139  */
140 static int
141 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
142 {
143         int fibnum;
144         int error;
145  
146         fibnum = curthread->td_proc->p_fibnum;
147         error = sysctl_handle_int(oidp, &fibnum, 0, req);
148         return (error);
149 }
150
151 SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
152             NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
153
154 static __inline struct radix_node_head **
155 rt_tables_get_rnh_ptr(int table, int fam)
156 {
157         struct radix_node_head **rnh;
158
159         KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
160             __func__));
161         KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
162             __func__));
163
164         /* rnh is [fib=0][af=0]. */
165         rnh = (struct radix_node_head **)V_rt_tables;
166         /* Get the offset to the requested table and fam. */
167         rnh += table * (AF_MAX+1) + fam;
168
169         return (rnh);
170 }
171
172 struct radix_node_head *
173 rt_tables_get_rnh(int table, int fam)
174 {
175
176         return (*rt_tables_get_rnh_ptr(table, fam));
177 }
178
179 /*
180  * route initialization must occur before ip6_init2(), which happenas at
181  * SI_ORDER_MIDDLE.
182  */
183 static void
184 route_init(void)
185 {
186         struct domain *dom;
187         int max_keylen = 0;
188
189         /* whack the tunable ints into  line. */
190         if (rt_numfibs > RT_MAXFIBS)
191                 rt_numfibs = RT_MAXFIBS;
192         if (rt_numfibs == 0)
193                 rt_numfibs = 1;
194
195         for (dom = domains; dom; dom = dom->dom_next)
196                 if (dom->dom_maxrtkey > max_keylen)
197                         max_keylen = dom->dom_maxrtkey;
198
199         rn_init(max_keylen);    /* init all zeroes, all ones, mask table */
200 }
201 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
202
203 static int
204 rtentry_zinit(void *mem, int size, int how)
205 {
206         struct rtentry *rt = mem;
207
208         rt->rt_pksent = counter_u64_alloc(how);
209         if (rt->rt_pksent == NULL)
210                 return (ENOMEM);
211
212         RT_LOCK_INIT(rt);
213
214         return (0);
215 }
216
217 static void
218 rtentry_zfini(void *mem, int size)
219 {
220         struct rtentry *rt = mem;
221
222         RT_LOCK_DESTROY(rt);
223         counter_u64_free(rt->rt_pksent);
224 }
225
226 static int
227 rtentry_ctor(void *mem, int size, void *arg, int how)
228 {
229         struct rtentry *rt = mem;
230
231         bzero(rt, offsetof(struct rtentry, rt_endzero));
232         counter_u64_zero(rt->rt_pksent);
233
234         return (0);
235 }
236
237 static void
238 rtentry_dtor(void *mem, int size, void *arg)
239 {
240         struct rtentry *rt = mem;
241
242         RT_UNLOCK_COND(rt);
243 }
244
245 static void
246 vnet_route_init(const void *unused __unused)
247 {
248         struct domain *dom;
249         struct radix_node_head **rnh;
250         int table;
251         int fam;
252
253         V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
254             sizeof(struct radix_node_head *), M_RTABLE, M_WAITOK|M_ZERO);
255
256         V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
257             rtentry_ctor, rtentry_dtor,
258             rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
259         for (dom = domains; dom; dom = dom->dom_next) {
260                 if (dom->dom_rtattach == NULL)
261                         continue;
262
263                 for  (table = 0; table < rt_numfibs; table++) {
264                         fam = dom->dom_family;
265                         if (table != 0 && fam != AF_INET6 && fam != AF_INET)
266                                 break;
267
268                         /*
269                          * XXX MRT rtattach will be also called from
270                          * vfs_export.c but the offset will be 0 (only for
271                          * AF_INET and AF_INET6 which don't need it anyhow).
272                          */
273                         rnh = rt_tables_get_rnh_ptr(table, fam);
274                         if (rnh == NULL)
275                                 panic("%s: rnh NULL", __func__);
276                         dom->dom_rtattach((void **)rnh, dom->dom_rtoffset);
277                 }
278         }
279 }
280 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
281     vnet_route_init, 0);
282
283 #ifdef VIMAGE
284 static void
285 vnet_route_uninit(const void *unused __unused)
286 {
287         int table;
288         int fam;
289         struct domain *dom;
290         struct radix_node_head **rnh;
291
292         for (dom = domains; dom; dom = dom->dom_next) {
293                 if (dom->dom_rtdetach == NULL)
294                         continue;
295
296                 for (table = 0; table < rt_numfibs; table++) {
297                         fam = dom->dom_family;
298
299                         if (table != 0 && fam != AF_INET6 && fam != AF_INET)
300                                 break;
301
302                         rnh = rt_tables_get_rnh_ptr(table, fam);
303                         if (rnh == NULL)
304                                 panic("%s: rnh NULL", __func__);
305                         dom->dom_rtdetach((void **)rnh, dom->dom_rtoffset);
306                 }
307         }
308
309         free(V_rt_tables, M_RTABLE);
310         uma_zdestroy(V_rtzone);
311 }
312 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
313     vnet_route_uninit, 0);
314 #endif
315
316 #ifndef _SYS_SYSPROTO_H_
317 struct setfib_args {
318         int     fibnum;
319 };
320 #endif
321 int
322 sys_setfib(struct thread *td, struct setfib_args *uap)
323 {
324         if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
325                 return EINVAL;
326         td->td_proc->p_fibnum = uap->fibnum;
327         return (0);
328 }
329
330 /*
331  * Packet routing routines.
332  */
333 void
334 rtalloc(struct route *ro)
335 {
336
337         rtalloc_ign_fib(ro, 0UL, RT_DEFAULT_FIB);
338 }
339
340 void
341 rtalloc_fib(struct route *ro, u_int fibnum)
342 {
343         rtalloc_ign_fib(ro, 0UL, fibnum);
344 }
345
346 void
347 rtalloc_ign(struct route *ro, u_long ignore)
348 {
349         struct rtentry *rt;
350
351         if ((rt = ro->ro_rt) != NULL) {
352                 if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
353                         return;
354                 RTFREE(rt);
355                 ro->ro_rt = NULL;
356         }
357         ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, RT_DEFAULT_FIB);
358         if (ro->ro_rt)
359                 RT_UNLOCK(ro->ro_rt);
360 }
361
362 void
363 rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
364 {
365         struct rtentry *rt;
366
367         if ((rt = ro->ro_rt) != NULL) {
368                 if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
369                         return;
370                 RTFREE(rt);
371                 ro->ro_rt = NULL;
372         }
373         ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
374         if (ro->ro_rt)
375                 RT_UNLOCK(ro->ro_rt);
376 }
377
378 /*
379  * Look up the route that matches the address given
380  * Or, at least try.. Create a cloned route if needed.
381  *
382  * The returned route, if any, is locked.
383  */
384 struct rtentry *
385 rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
386 {
387
388         return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
389 }
390
391 struct rtentry *
392 rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
393                     u_int fibnum)
394 {
395         struct radix_node_head *rnh;
396         struct radix_node *rn;
397         struct rtentry *newrt;
398         struct rt_addrinfo info;
399         int err = 0, msgtype = RTM_MISS;
400         int needlock;
401
402         KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
403         switch (dst->sa_family) {
404         case AF_INET6:
405         case AF_INET:
406                 /* We support multiple FIBs. */
407                 break;
408         default:
409                 fibnum = RT_DEFAULT_FIB;
410                 break;
411         }
412         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
413         newrt = NULL;
414         if (rnh == NULL)
415                 goto miss;
416
417         /*
418          * Look up the address in the table for that Address Family
419          */
420         needlock = !(ignflags & RTF_RNH_LOCKED);
421         if (needlock)
422                 RADIX_NODE_HEAD_RLOCK(rnh);
423 #ifdef INVARIANTS       
424         else
425                 RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
426 #endif
427         rn = rnh->rnh_matchaddr(dst, rnh);
428         if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
429                 newrt = RNTORT(rn);
430                 RT_LOCK(newrt);
431                 RT_ADDREF(newrt);
432                 if (needlock)
433                         RADIX_NODE_HEAD_RUNLOCK(rnh);
434                 goto done;
435
436         } else if (needlock)
437                 RADIX_NODE_HEAD_RUNLOCK(rnh);
438         
439         /*
440          * Either we hit the root or couldn't find any match,
441          * Which basically means
442          * "caint get there frm here"
443          */
444 miss:
445         V_rtstat.rts_unreach++;
446
447         if (report) {
448                 /*
449                  * If required, report the failure to the supervising
450                  * Authorities.
451                  * For a delete, this is not an error. (report == 0)
452                  */
453                 bzero(&info, sizeof(info));
454                 info.rti_info[RTAX_DST] = dst;
455                 rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
456         }       
457 done:
458         if (newrt)
459                 RT_LOCK_ASSERT(newrt);
460         return (newrt);
461 }
462
463 /*
464  * Remove a reference count from an rtentry.
465  * If the count gets low enough, take it out of the routing table
466  */
467 void
468 rtfree(struct rtentry *rt)
469 {
470         struct radix_node_head *rnh;
471
472         KASSERT(rt != NULL,("%s: NULL rt", __func__));
473         rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
474         KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
475
476         RT_LOCK_ASSERT(rt);
477
478         /*
479          * The callers should use RTFREE_LOCKED() or RTFREE(), so
480          * we should come here exactly with the last reference.
481          */
482         RT_REMREF(rt);
483         if (rt->rt_refcnt > 0) {
484                 log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
485                 goto done;
486         }
487
488         /*
489          * On last reference give the "close method" a chance
490          * to cleanup private state.  This also permits (for
491          * IPv4 and IPv6) a chance to decide if the routing table
492          * entry should be purged immediately or at a later time.
493          * When an immediate purge is to happen the close routine
494          * typically calls rtexpunge which clears the RTF_UP flag
495          * on the entry so that the code below reclaims the storage.
496          */
497         if (rt->rt_refcnt == 0 && rnh->rnh_close)
498                 rnh->rnh_close((struct radix_node *)rt, rnh);
499
500         /*
501          * If we are no longer "up" (and ref == 0)
502          * then we can free the resources associated
503          * with the route.
504          */
505         if ((rt->rt_flags & RTF_UP) == 0) {
506                 if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
507                         panic("rtfree 2");
508                 /*
509                  * the rtentry must have been removed from the routing table
510                  * so it is represented in rttrash.. remove that now.
511                  */
512                 V_rttrash--;
513 #ifdef  DIAGNOSTIC
514                 if (rt->rt_refcnt < 0) {
515                         printf("rtfree: %p not freed (neg refs)\n", rt);
516                         goto done;
517                 }
518 #endif
519                 /*
520                  * release references on items we hold them on..
521                  * e.g other routes and ifaddrs.
522                  */
523                 if (rt->rt_ifa)
524                         ifa_free(rt->rt_ifa);
525                 /*
526                  * The key is separatly alloc'd so free it (see rt_setgate()).
527                  * This also frees the gateway, as they are always malloc'd
528                  * together.
529                  */
530                 Free(rt_key(rt));
531
532                 /*
533                  * and the rtentry itself of course
534                  */
535                 uma_zfree(V_rtzone, rt);
536                 return;
537         }
538 done:
539         RT_UNLOCK(rt);
540 }
541
542
543 /*
544  * Force a routing table entry to the specified
545  * destination to go through the given gateway.
546  * Normally called as a result of a routing redirect
547  * message from the network layer.
548  */
549 void
550 rtredirect(struct sockaddr *dst,
551         struct sockaddr *gateway,
552         struct sockaddr *netmask,
553         int flags,
554         struct sockaddr *src)
555 {
556
557         rtredirect_fib(dst, gateway, netmask, flags, src, RT_DEFAULT_FIB);
558 }
559
560 void
561 rtredirect_fib(struct sockaddr *dst,
562         struct sockaddr *gateway,
563         struct sockaddr *netmask,
564         int flags,
565         struct sockaddr *src,
566         u_int fibnum)
567 {
568         struct rtentry *rt, *rt0 = NULL;
569         int error = 0;
570         short *stat = NULL;
571         struct rt_addrinfo info;
572         struct ifaddr *ifa;
573         struct radix_node_head *rnh;
574
575         ifa = NULL;
576         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
577         if (rnh == NULL) {
578                 error = EAFNOSUPPORT;
579                 goto out;
580         }
581
582         /* verify the gateway is directly reachable */
583         if ((ifa = ifa_ifwithnet(gateway, 0)) == NULL) {
584                 error = ENETUNREACH;
585                 goto out;
586         }
587         rt = rtalloc1_fib(dst, 0, 0UL, fibnum); /* NB: rt is locked */
588         /*
589          * If the redirect isn't from our current router for this dst,
590          * it's either old or wrong.  If it redirects us to ourselves,
591          * we have a routing loop, perhaps as a result of an interface
592          * going down recently.
593          */
594         if (!(flags & RTF_DONE) && rt &&
595              (!sa_equal(src, rt->rt_gateway) || rt->rt_ifa != ifa))
596                 error = EINVAL;
597         else if (ifa_ifwithaddr_check(gateway))
598                 error = EHOSTUNREACH;
599         if (error)
600                 goto done;
601         /*
602          * Create a new entry if we just got back a wildcard entry
603          * or the lookup failed.  This is necessary for hosts
604          * which use routing redirects generated by smart gateways
605          * to dynamically build the routing tables.
606          */
607         if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
608                 goto create;
609         /*
610          * Don't listen to the redirect if it's
611          * for a route to an interface.
612          */
613         if (rt->rt_flags & RTF_GATEWAY) {
614                 if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
615                         /*
616                          * Changing from route to net => route to host.
617                          * Create new route, rather than smashing route to net.
618                          */
619                 create:
620                         rt0 = rt;
621                         rt = NULL;
622                 
623                         flags |=  RTF_GATEWAY | RTF_DYNAMIC;
624                         bzero((caddr_t)&info, sizeof(info));
625                         info.rti_info[RTAX_DST] = dst;
626                         info.rti_info[RTAX_GATEWAY] = gateway;
627                         info.rti_info[RTAX_NETMASK] = netmask;
628                         info.rti_ifa = ifa;
629                         info.rti_flags = flags;
630                         if (rt0 != NULL)
631                                 RT_UNLOCK(rt0); /* drop lock to avoid LOR with RNH */
632                         error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
633                         if (rt != NULL) {
634                                 RT_LOCK(rt);
635                                 if (rt0 != NULL)
636                                         EVENTHANDLER_INVOKE(route_redirect_event, rt0, rt, dst);
637                                 flags = rt->rt_flags;
638                         }
639                         if (rt0 != NULL)
640                                 RTFREE(rt0);
641                         
642                         stat = &V_rtstat.rts_dynamic;
643                 } else {
644                         struct rtentry *gwrt;
645
646                         /*
647                          * Smash the current notion of the gateway to
648                          * this destination.  Should check about netmask!!!
649                          */
650                         rt->rt_flags |= RTF_MODIFIED;
651                         flags |= RTF_MODIFIED;
652                         stat = &V_rtstat.rts_newgateway;
653                         /*
654                          * add the key and gateway (in one malloc'd chunk).
655                          */
656                         RT_UNLOCK(rt);
657                         RADIX_NODE_HEAD_LOCK(rnh);
658                         RT_LOCK(rt);
659                         rt_setgate(rt, rt_key(rt), gateway);
660                         gwrt = rtalloc1(gateway, 1, RTF_RNH_LOCKED);
661                         RADIX_NODE_HEAD_UNLOCK(rnh);
662                         EVENTHANDLER_INVOKE(route_redirect_event, rt, gwrt, dst);
663                         RTFREE_LOCKED(gwrt);
664                 }
665         } else
666                 error = EHOSTUNREACH;
667 done:
668         if (rt)
669                 RTFREE_LOCKED(rt);
670 out:
671         if (error)
672                 V_rtstat.rts_badredirect++;
673         else if (stat != NULL)
674                 (*stat)++;
675         bzero((caddr_t)&info, sizeof(info));
676         info.rti_info[RTAX_DST] = dst;
677         info.rti_info[RTAX_GATEWAY] = gateway;
678         info.rti_info[RTAX_NETMASK] = netmask;
679         info.rti_info[RTAX_AUTHOR] = src;
680         rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
681         if (ifa != NULL)
682                 ifa_free(ifa);
683 }
684
685 int
686 rtioctl(u_long req, caddr_t data)
687 {
688
689         return (rtioctl_fib(req, data, RT_DEFAULT_FIB));
690 }
691
692 /*
693  * Routing table ioctl interface.
694  */
695 int
696 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
697 {
698
699         /*
700          * If more ioctl commands are added here, make sure the proper
701          * super-user checks are being performed because it is possible for
702          * prison-root to make it this far if raw sockets have been enabled
703          * in jails.
704          */
705 #ifdef INET
706         /* Multicast goop, grrr... */
707         return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
708 #else /* INET */
709         return ENXIO;
710 #endif /* INET */
711 }
712
713 /*
714  * For both ifa_ifwithroute() routines, 'ifa' is returned referenced.
715  */
716 struct ifaddr *
717 ifa_ifwithroute(int flags, struct sockaddr *dst, struct sockaddr *gateway)
718 {
719
720         return (ifa_ifwithroute_fib(flags, dst, gateway, RT_DEFAULT_FIB));
721 }
722
723 struct ifaddr *
724 ifa_ifwithroute_fib(int flags, struct sockaddr *dst, struct sockaddr *gateway,
725                                 u_int fibnum)
726 {
727         register struct ifaddr *ifa;
728         int not_found = 0;
729
730         if ((flags & RTF_GATEWAY) == 0) {
731                 /*
732                  * If we are adding a route to an interface,
733                  * and the interface is a pt to pt link
734                  * we should search for the destination
735                  * as our clue to the interface.  Otherwise
736                  * we can use the local address.
737                  */
738                 ifa = NULL;
739                 if (flags & RTF_HOST)
740                         ifa = ifa_ifwithdstaddr(dst);
741                 if (ifa == NULL)
742                         ifa = ifa_ifwithaddr(gateway);
743         } else {
744                 /*
745                  * If we are adding a route to a remote net
746                  * or host, the gateway may still be on the
747                  * other end of a pt to pt link.
748                  */
749                 ifa = ifa_ifwithdstaddr(gateway);
750         }
751         if (ifa == NULL)
752                 ifa = ifa_ifwithnet(gateway, 0);
753         if (ifa == NULL) {
754                 struct rtentry *rt = rtalloc1_fib(gateway, 0, RTF_RNH_LOCKED, fibnum);
755                 if (rt == NULL)
756                         return (NULL);
757                 /*
758                  * dismiss a gateway that is reachable only
759                  * through the default router
760                  */
761                 switch (gateway->sa_family) {
762                 case AF_INET:
763                         if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
764                                 not_found = 1;
765                         break;
766                 case AF_INET6:
767                         if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
768                                 not_found = 1;
769                         break;
770                 default:
771                         break;
772                 }
773                 if (!not_found && rt->rt_ifa != NULL) {
774                         ifa = rt->rt_ifa;
775                         ifa_ref(ifa);
776                 }
777                 RT_REMREF(rt);
778                 RT_UNLOCK(rt);
779                 if (not_found || ifa == NULL)
780                         return (NULL);
781         }
782         if (ifa->ifa_addr->sa_family != dst->sa_family) {
783                 struct ifaddr *oifa = ifa;
784                 ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
785                 if (ifa == NULL)
786                         ifa = oifa;
787                 else
788                         ifa_free(oifa);
789         }
790         return (ifa);
791 }
792
793 /*
794  * Do appropriate manipulations of a routing tree given
795  * all the bits of info needed
796  */
797 int
798 rtrequest(int req,
799         struct sockaddr *dst,
800         struct sockaddr *gateway,
801         struct sockaddr *netmask,
802         int flags,
803         struct rtentry **ret_nrt)
804 {
805
806         return (rtrequest_fib(req, dst, gateway, netmask, flags, ret_nrt,
807             RT_DEFAULT_FIB));
808 }
809
810 int
811 rtrequest_fib(int req,
812         struct sockaddr *dst,
813         struct sockaddr *gateway,
814         struct sockaddr *netmask,
815         int flags,
816         struct rtentry **ret_nrt,
817         u_int fibnum)
818 {
819         struct rt_addrinfo info;
820
821         if (dst->sa_len == 0)
822                 return(EINVAL);
823
824         bzero((caddr_t)&info, sizeof(info));
825         info.rti_flags = flags;
826         info.rti_info[RTAX_DST] = dst;
827         info.rti_info[RTAX_GATEWAY] = gateway;
828         info.rti_info[RTAX_NETMASK] = netmask;
829         return rtrequest1_fib(req, &info, ret_nrt, fibnum);
830 }
831
832 /*
833  * These (questionable) definitions of apparent local variables apply
834  * to the next two functions.  XXXXXX!!!
835  */
836 #define dst     info->rti_info[RTAX_DST]
837 #define gateway info->rti_info[RTAX_GATEWAY]
838 #define netmask info->rti_info[RTAX_NETMASK]
839 #define ifaaddr info->rti_info[RTAX_IFA]
840 #define ifpaddr info->rti_info[RTAX_IFP]
841 #define flags   info->rti_flags
842
843 int
844 rt_getifa(struct rt_addrinfo *info)
845 {
846
847         return (rt_getifa_fib(info, RT_DEFAULT_FIB));
848 }
849
850 /*
851  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
852  * it will be referenced so the caller must free it.
853  */
854 int
855 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
856 {
857         struct ifaddr *ifa;
858         int error = 0;
859
860         /*
861          * ifp may be specified by sockaddr_dl
862          * when protocol address is ambiguous.
863          */
864         if (info->rti_ifp == NULL && ifpaddr != NULL &&
865             ifpaddr->sa_family == AF_LINK &&
866             (ifa = ifa_ifwithnet(ifpaddr, 0)) != NULL) {
867                 info->rti_ifp = ifa->ifa_ifp;
868                 ifa_free(ifa);
869         }
870         if (info->rti_ifa == NULL && ifaaddr != NULL)
871                 info->rti_ifa = ifa_ifwithaddr(ifaaddr);
872         if (info->rti_ifa == NULL) {
873                 struct sockaddr *sa;
874
875                 sa = ifaaddr != NULL ? ifaaddr :
876                     (gateway != NULL ? gateway : dst);
877                 if (sa != NULL && info->rti_ifp != NULL)
878                         info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
879                 else if (dst != NULL && gateway != NULL)
880                         info->rti_ifa = ifa_ifwithroute_fib(flags, dst, gateway,
881                                                         fibnum);
882                 else if (sa != NULL)
883                         info->rti_ifa = ifa_ifwithroute_fib(flags, sa, sa,
884                                                         fibnum);
885         }
886         if ((ifa = info->rti_ifa) != NULL) {
887                 if (info->rti_ifp == NULL)
888                         info->rti_ifp = ifa->ifa_ifp;
889         } else
890                 error = ENETUNREACH;
891         return (error);
892 }
893
894 /*
895  * Expunges references to a route that's about to be reclaimed.
896  * The route must be locked.
897  */
898 int
899 rtexpunge(struct rtentry *rt)
900 {
901 #if !defined(RADIX_MPATH)
902         struct radix_node *rn;
903 #else
904         struct rt_addrinfo info;
905         int fib;
906         struct rtentry *rt0;
907 #endif
908         struct radix_node_head *rnh;
909         struct ifaddr *ifa;
910         int error = 0;
911
912         /*
913          * Find the correct routing tree to use for this Address Family
914          */
915         rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
916         RT_LOCK_ASSERT(rt);
917         if (rnh == NULL)
918                 return (EAFNOSUPPORT);
919         RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
920
921 #ifdef RADIX_MPATH
922         fib = rt->rt_fibnum;
923         bzero(&info, sizeof(info));
924         info.rti_ifp = rt->rt_ifp;
925         info.rti_flags = RTF_RNH_LOCKED;
926         info.rti_info[RTAX_DST] = rt_key(rt);
927         info.rti_info[RTAX_GATEWAY] = rt->rt_ifa->ifa_addr;
928
929         RT_UNLOCK(rt);
930         error = rtrequest1_fib(RTM_DELETE, &info, &rt0, fib);
931
932         if (error == 0 && rt0 != NULL) {
933                 rt = rt0;
934                 RT_LOCK(rt);
935         } else if (error != 0) {
936                 RT_LOCK(rt);
937                 return (error);
938         }
939 #else
940         /*
941          * Remove the item from the tree; it should be there,
942          * but when callers invoke us blindly it may not (sigh).
943          */
944         rn = rnh->rnh_deladdr(rt_key(rt), rt_mask(rt), rnh);
945         if (rn == NULL) {
946                 error = ESRCH;
947                 goto bad;
948         }
949         KASSERT((rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)) == 0,
950                 ("unexpected flags 0x%x", rn->rn_flags));
951         KASSERT(rt == RNTORT(rn),
952                 ("lookup mismatch, rt %p rn %p", rt, rn));
953 #endif /* RADIX_MPATH */
954
955         rt->rt_flags &= ~RTF_UP;
956
957         /*
958          * Give the protocol a chance to keep things in sync.
959          */
960         if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest) {
961                 struct rt_addrinfo info;
962
963                 bzero((caddr_t)&info, sizeof(info));
964                 info.rti_flags = rt->rt_flags;
965                 info.rti_info[RTAX_DST] = rt_key(rt);
966                 info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
967                 info.rti_info[RTAX_NETMASK] = rt_mask(rt);
968                 ifa->ifa_rtrequest(RTM_DELETE, rt, &info);
969         }
970
971         /*
972          * one more rtentry floating around that is not
973          * linked to the routing table.
974          */
975         V_rttrash++;
976 #if !defined(RADIX_MPATH)
977 bad:
978 #endif
979         return (error);
980 }
981
982 #if 0
983 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
984 int rt_print(char *buf, int buflen, struct rtentry *rt);
985
986 int
987 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
988 {
989         void *paddr = NULL;
990
991         switch (s->sa_family) {
992         case AF_INET:
993                 paddr = &((struct sockaddr_in *)s)->sin_addr;
994                 break;
995         case AF_INET6:
996                 paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
997                 break;
998         }
999
1000         if (paddr == NULL)
1001                 return (0);
1002
1003         if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
1004                 return (0);
1005         
1006         return (strlen(buf));
1007 }
1008
1009 int
1010 rt_print(char *buf, int buflen, struct rtentry *rt)
1011 {
1012         struct sockaddr *addr, *mask;
1013         int i = 0;
1014
1015         addr = rt_key(rt);
1016         mask = rt_mask(rt);
1017
1018         i = p_sockaddr(buf, buflen, addr);
1019         if (!(rt->rt_flags & RTF_HOST)) {
1020                 buf[i++] = '/';
1021                 i += p_sockaddr(buf + i, buflen - i, mask);
1022         }
1023
1024         if (rt->rt_flags & RTF_GATEWAY) {
1025                 buf[i++] = '>';
1026                 i += p_sockaddr(buf + i, buflen - i, rt->rt_gateway);
1027         }
1028
1029         return (i);
1030 }
1031 #endif
1032
1033 #ifdef RADIX_MPATH
1034 static int
1035 rn_mpath_update(int req, struct rt_addrinfo *info,
1036     struct radix_node_head *rnh, struct rtentry **ret_nrt)
1037 {
1038         /*
1039          * if we got multipath routes, we require users to specify
1040          * a matching RTAX_GATEWAY.
1041          */
1042         struct rtentry *rt, *rto = NULL;
1043         register struct radix_node *rn;
1044         int error = 0;
1045
1046         rn = rnh->rnh_lookup(dst, netmask, rnh);
1047         if (rn == NULL)
1048                 return (ESRCH);
1049         rto = rt = RNTORT(rn);
1050
1051         rt = rt_mpath_matchgate(rt, gateway);
1052         if (rt == NULL)
1053                 return (ESRCH);
1054         /*
1055          * this is the first entry in the chain
1056          */
1057         if (rto == rt) {
1058                 rn = rn_mpath_next((struct radix_node *)rt);
1059                 /*
1060                  * there is another entry, now it's active
1061                  */
1062                 if (rn) {
1063                         rto = RNTORT(rn);
1064                         RT_LOCK(rto);
1065                         rto->rt_flags |= RTF_UP;
1066                         RT_UNLOCK(rto);
1067                 } else if (rt->rt_flags & RTF_GATEWAY) {
1068                         /*
1069                          * For gateway routes, we need to 
1070                          * make sure that we we are deleting
1071                          * the correct gateway. 
1072                          * rt_mpath_matchgate() does not 
1073                          * check the case when there is only
1074                          * one route in the chain.  
1075                          */
1076                         if (gateway &&
1077                             (rt->rt_gateway->sa_len != gateway->sa_len ||
1078                                 memcmp(rt->rt_gateway, gateway, gateway->sa_len)))
1079                                 error = ESRCH;
1080                         else {
1081                                 /*
1082                                  * remove from tree before returning it
1083                                  * to the caller
1084                                  */
1085                                 rn = rnh->rnh_deladdr(dst, netmask, rnh);
1086                                 KASSERT(rt == RNTORT(rn), ("radix node disappeared"));
1087                                 goto gwdelete;
1088                         }
1089                         
1090                 }
1091                 /*
1092                  * use the normal delete code to remove
1093                  * the first entry
1094                  */
1095                 if (req != RTM_DELETE) 
1096                         goto nondelete;
1097
1098                 error = ENOENT;
1099                 goto done;
1100         }
1101                 
1102         /*
1103          * if the entry is 2nd and on up
1104          */
1105         if ((req == RTM_DELETE) && !rt_mpath_deldup(rto, rt))
1106                 panic ("rtrequest1: rt_mpath_deldup");
1107 gwdelete:
1108         RT_LOCK(rt);
1109         RT_ADDREF(rt);
1110         if (req == RTM_DELETE) {
1111                 rt->rt_flags &= ~RTF_UP;
1112                 /*
1113                  * One more rtentry floating around that is not
1114                  * linked to the routing table. rttrash will be decremented
1115                  * when RTFREE(rt) is eventually called.
1116                  */
1117                 V_rttrash++;
1118         }
1119         
1120 nondelete:
1121         if (req != RTM_DELETE)
1122                 panic("unrecognized request %d", req);
1123         
1124
1125         /*
1126          * If the caller wants it, then it can have it,
1127          * but it's up to it to free the rtentry as we won't be
1128          * doing it.
1129          */
1130         if (ret_nrt) {
1131                 *ret_nrt = rt;
1132                 RT_UNLOCK(rt);
1133         } else
1134                 RTFREE_LOCKED(rt);
1135 done:
1136         return (error);
1137 }
1138 #endif
1139
1140 int
1141 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1142                                 u_int fibnum)
1143 {
1144         int error = 0, needlock = 0;
1145         register struct rtentry *rt;
1146 #ifdef FLOWTABLE
1147         register struct rtentry *rt0;
1148 #endif
1149         register struct radix_node *rn;
1150         register struct radix_node_head *rnh;
1151         struct ifaddr *ifa;
1152         struct sockaddr *ndst;
1153         struct sockaddr_storage mdst;
1154 #define senderr(x) { error = x ; goto bad; }
1155
1156         KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1157         switch (dst->sa_family) {
1158         case AF_INET6:
1159         case AF_INET:
1160                 /* We support multiple FIBs. */
1161                 break;
1162         default:
1163                 fibnum = RT_DEFAULT_FIB;
1164                 break;
1165         }
1166
1167         /*
1168          * Find the correct routing tree to use for this Address Family
1169          */
1170         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1171         if (rnh == NULL)
1172                 return (EAFNOSUPPORT);
1173         needlock = ((flags & RTF_RNH_LOCKED) == 0);
1174         flags &= ~RTF_RNH_LOCKED;
1175         if (needlock)
1176                 RADIX_NODE_HEAD_LOCK(rnh);
1177         else
1178                 RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1179         /*
1180          * If we are adding a host route then we don't want to put
1181          * a netmask in the tree, nor do we want to clone it.
1182          */
1183         if (flags & RTF_HOST)
1184                 netmask = NULL;
1185
1186         switch (req) {
1187         case RTM_DELETE:
1188                 if (netmask) {
1189                         rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1190                         dst = (struct sockaddr *)&mdst;
1191                 }
1192 #ifdef RADIX_MPATH
1193                 if (rn_mpath_capable(rnh)) {
1194                         error = rn_mpath_update(req, info, rnh, ret_nrt);
1195                         /*
1196                          * "bad" holds true for the success case
1197                          * as well
1198                          */
1199                         if (error != ENOENT)
1200                                 goto bad;
1201                         error = 0;
1202                 }
1203 #endif
1204                 if ((flags & RTF_PINNED) == 0) {
1205                         /* Check if target route can be deleted */
1206                         rt = (struct rtentry *)rnh->rnh_lookup(dst,
1207                             netmask, rnh);
1208                         if ((rt != NULL) && (rt->rt_flags & RTF_PINNED))
1209                                 senderr(EADDRINUSE);
1210                 }
1211
1212                 /*
1213                  * Remove the item from the tree and return it.
1214                  * Complain if it is not there and do no more processing.
1215                  */
1216                 rn = rnh->rnh_deladdr(dst, netmask, rnh);
1217                 if (rn == NULL)
1218                         senderr(ESRCH);
1219                 if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1220                         panic ("rtrequest delete");
1221                 rt = RNTORT(rn);
1222                 RT_LOCK(rt);
1223                 RT_ADDREF(rt);
1224                 rt->rt_flags &= ~RTF_UP;
1225
1226                 /*
1227                  * give the protocol a chance to keep things in sync.
1228                  */
1229                 if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
1230                         ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1231
1232                 /*
1233                  * One more rtentry floating around that is not
1234                  * linked to the routing table. rttrash will be decremented
1235                  * when RTFREE(rt) is eventually called.
1236                  */
1237                 V_rttrash++;
1238
1239                 /*
1240                  * If the caller wants it, then it can have it,
1241                  * but it's up to it to free the rtentry as we won't be
1242                  * doing it.
1243                  */
1244                 if (ret_nrt) {
1245                         *ret_nrt = rt;
1246                         RT_UNLOCK(rt);
1247                 } else
1248                         RTFREE_LOCKED(rt);
1249                 break;
1250         case RTM_RESOLVE:
1251                 /*
1252                  * resolve was only used for route cloning
1253                  * here for compat
1254                  */
1255                 break;
1256         case RTM_ADD:
1257                 if ((flags & RTF_GATEWAY) && !gateway)
1258                         senderr(EINVAL);
1259                 if (dst && gateway && (dst->sa_family != gateway->sa_family) && 
1260                     (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1261                         senderr(EINVAL);
1262
1263                 if (info->rti_ifa == NULL) {
1264                         error = rt_getifa_fib(info, fibnum);
1265                         if (error)
1266                                 senderr(error);
1267                 } else
1268                         ifa_ref(info->rti_ifa);
1269                 ifa = info->rti_ifa;
1270                 rt = uma_zalloc(V_rtzone, M_NOWAIT);
1271                 if (rt == NULL) {
1272                         ifa_free(ifa);
1273                         senderr(ENOBUFS);
1274                 }
1275                 rt->rt_flags = RTF_UP | flags;
1276                 rt->rt_fibnum = fibnum;
1277                 /*
1278                  * Add the gateway. Possibly re-malloc-ing the storage for it.
1279                  */
1280                 RT_LOCK(rt);
1281                 if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1282                         ifa_free(ifa);
1283                         uma_zfree(V_rtzone, rt);
1284                         senderr(error);
1285                 }
1286
1287                 /*
1288                  * point to the (possibly newly malloc'd) dest address.
1289                  */
1290                 ndst = (struct sockaddr *)rt_key(rt);
1291
1292                 /*
1293                  * make sure it contains the value we want (masked if needed).
1294                  */
1295                 if (netmask) {
1296                         rt_maskedcopy(dst, ndst, netmask);
1297                 } else
1298                         bcopy(dst, ndst, dst->sa_len);
1299
1300                 /*
1301                  * We use the ifa reference returned by rt_getifa_fib().
1302                  * This moved from below so that rnh->rnh_addaddr() can
1303                  * examine the ifa and  ifa->ifa_ifp if it so desires.
1304                  */
1305                 rt->rt_ifa = ifa;
1306                 rt->rt_ifp = ifa->ifa_ifp;
1307                 rt->rt_weight = 1;
1308
1309 #ifdef RADIX_MPATH
1310                 /* do not permit exactly the same dst/mask/gw pair */
1311                 if (rn_mpath_capable(rnh) &&
1312                         rt_mpath_conflict(rnh, rt, netmask)) {
1313                         ifa_free(rt->rt_ifa);
1314                         Free(rt_key(rt));
1315                         uma_zfree(V_rtzone, rt);
1316                         senderr(EEXIST);
1317                 }
1318 #endif
1319
1320 #ifdef FLOWTABLE
1321                 rt0 = NULL;
1322                 /* "flow-table" only supports IPv6 and IPv4 at the moment. */
1323                 switch (dst->sa_family) {
1324 #ifdef INET6
1325                 case AF_INET6:
1326 #endif
1327 #ifdef INET
1328                 case AF_INET:
1329 #endif
1330 #if defined(INET6) || defined(INET)
1331                         rn = rnh->rnh_matchaddr(dst, rnh);
1332                         if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
1333                                 struct sockaddr *mask;
1334                                 u_char *m, *n;
1335                                 int len;
1336                                 
1337                                 /*
1338                                  * compare mask to see if the new route is
1339                                  * more specific than the existing one
1340                                  */
1341                                 rt0 = RNTORT(rn);
1342                                 RT_LOCK(rt0);
1343                                 RT_ADDREF(rt0);
1344                                 RT_UNLOCK(rt0);
1345                                 /*
1346                                  * A host route is already present, so 
1347                                  * leave the flow-table entries as is.
1348                                  */
1349                                 if (rt0->rt_flags & RTF_HOST) {
1350                                         RTFREE(rt0);
1351                                         rt0 = NULL;
1352                                 } else if (!(flags & RTF_HOST) && netmask) {
1353                                         mask = rt_mask(rt0);
1354                                         len = mask->sa_len;
1355                                         m = (u_char *)mask;
1356                                         n = (u_char *)netmask;
1357                                         while (len-- > 0) {
1358                                                 if (*n != *m)
1359                                                         break;
1360                                                 n++;
1361                                                 m++;
1362                                         }
1363                                         if (len == 0 || (*n < *m)) {
1364                                                 RTFREE(rt0);
1365                                                 rt0 = NULL;
1366                                         }
1367                                 }
1368                         }
1369 #endif/* INET6 || INET */
1370                 }
1371 #endif /* FLOWTABLE */
1372
1373                 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1374                 rn = rnh->rnh_addaddr(ndst, netmask, rnh, rt->rt_nodes);
1375                 /*
1376                  * If it still failed to go into the tree,
1377                  * then un-make it (this should be a function)
1378                  */
1379                 if (rn == NULL) {
1380                         ifa_free(rt->rt_ifa);
1381                         Free(rt_key(rt));
1382                         uma_zfree(V_rtzone, rt);
1383 #ifdef FLOWTABLE
1384                         if (rt0 != NULL)
1385                                 RTFREE(rt0);
1386 #endif
1387                         senderr(EEXIST);
1388                 } 
1389 #ifdef FLOWTABLE
1390                 else if (rt0 != NULL) {
1391                         flowtable_route_flush(dst->sa_family, rt0);
1392                         RTFREE(rt0);
1393                 }
1394 #endif
1395
1396                 /*
1397                  * If this protocol has something to add to this then
1398                  * allow it to do that as well.
1399                  */
1400                 if (ifa->ifa_rtrequest)
1401                         ifa->ifa_rtrequest(req, rt, info);
1402
1403                 /*
1404                  * actually return a resultant rtentry and
1405                  * give the caller a single reference.
1406                  */
1407                 if (ret_nrt) {
1408                         *ret_nrt = rt;
1409                         RT_ADDREF(rt);
1410                 }
1411                 RT_UNLOCK(rt);
1412                 break;
1413         default:
1414                 error = EOPNOTSUPP;
1415         }
1416 bad:
1417         if (needlock)
1418                 RADIX_NODE_HEAD_UNLOCK(rnh);
1419         return (error);
1420 #undef senderr
1421 }
1422
1423 #undef dst
1424 #undef gateway
1425 #undef netmask
1426 #undef ifaaddr
1427 #undef ifpaddr
1428 #undef flags
1429
1430 int
1431 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1432 {
1433         /* XXX dst may be overwritten, can we move this to below */
1434         int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1435 #ifdef INVARIANTS
1436         struct radix_node_head *rnh;
1437
1438         rnh = rt_tables_get_rnh(rt->rt_fibnum, dst->sa_family);
1439 #endif
1440
1441         RT_LOCK_ASSERT(rt);
1442         RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1443         
1444         /*
1445          * Prepare to store the gateway in rt->rt_gateway.
1446          * Both dst and gateway are stored one after the other in the same
1447          * malloc'd chunk. If we have room, we can reuse the old buffer,
1448          * rt_gateway already points to the right place.
1449          * Otherwise, malloc a new block and update the 'dst' address.
1450          */
1451         if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1452                 caddr_t new;
1453
1454                 R_Malloc(new, caddr_t, dlen + glen);
1455                 if (new == NULL)
1456                         return ENOBUFS;
1457                 /*
1458                  * XXX note, we copy from *dst and not *rt_key(rt) because
1459                  * rt_setgate() can be called to initialize a newly
1460                  * allocated route entry, in which case rt_key(rt) == NULL
1461                  * (and also rt->rt_gateway == NULL).
1462                  * Free()/free() handle a NULL argument just fine.
1463                  */
1464                 bcopy(dst, new, dlen);
1465                 Free(rt_key(rt));       /* free old block, if any */
1466                 rt_key(rt) = (struct sockaddr *)new;
1467                 rt->rt_gateway = (struct sockaddr *)(new + dlen);
1468         }
1469
1470         /*
1471          * Copy the new gateway value into the memory chunk.
1472          */
1473         bcopy(gate, rt->rt_gateway, glen);
1474
1475         return (0);
1476 }
1477
1478 void
1479 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1480 {
1481         register u_char *cp1 = (u_char *)src;
1482         register u_char *cp2 = (u_char *)dst;
1483         register u_char *cp3 = (u_char *)netmask;
1484         u_char *cplim = cp2 + *cp3;
1485         u_char *cplim2 = cp2 + *cp1;
1486
1487         *cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1488         cp3 += 2;
1489         if (cplim > cplim2)
1490                 cplim = cplim2;
1491         while (cp2 < cplim)
1492                 *cp2++ = *cp1++ & *cp3++;
1493         if (cp2 < cplim2)
1494                 bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1495 }
1496
1497 /*
1498  * Set up a routing table entry, normally
1499  * for an interface.
1500  */
1501 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1502 static inline  int
1503 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1504 {
1505         struct sockaddr *dst;
1506         struct sockaddr *netmask;
1507         struct rtentry *rt = NULL;
1508         struct rt_addrinfo info;
1509         int error = 0;
1510         int startfib, endfib;
1511         char tempbuf[_SOCKADDR_TMPSIZE];
1512         int didwork = 0;
1513         int a_failure = 0;
1514         static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1515         struct radix_node_head *rnh;
1516
1517         if (flags & RTF_HOST) {
1518                 dst = ifa->ifa_dstaddr;
1519                 netmask = NULL;
1520         } else {
1521                 dst = ifa->ifa_addr;
1522                 netmask = ifa->ifa_netmask;
1523         }
1524         if (dst->sa_len == 0)
1525                 return(EINVAL);
1526         switch (dst->sa_family) {
1527         case AF_INET6:
1528         case AF_INET:
1529                 /* We support multiple FIBs. */
1530                 break;
1531         default:
1532                 fibnum = RT_DEFAULT_FIB;
1533                 break;
1534         }
1535         if (fibnum == -1) {
1536                 if (rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD) {
1537                         startfib = endfib = curthread->td_proc->p_fibnum;
1538                 } else {
1539                         startfib = 0;
1540                         endfib = rt_numfibs - 1;
1541                 }
1542         } else {
1543                 KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1544                 startfib = fibnum;
1545                 endfib = fibnum;
1546         }
1547
1548         /*
1549          * If it's a delete, check that if it exists,
1550          * it's on the correct interface or we might scrub
1551          * a route to another ifa which would
1552          * be confusing at best and possibly worse.
1553          */
1554         if (cmd == RTM_DELETE) {
1555                 /*
1556                  * It's a delete, so it should already exist..
1557                  * If it's a net, mask off the host bits
1558                  * (Assuming we have a mask)
1559                  * XXX this is kinda inet specific..
1560                  */
1561                 if (netmask != NULL) {
1562                         rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
1563                         dst = (struct sockaddr *)tempbuf;
1564                 }
1565         }
1566         /*
1567          * Now go through all the requested tables (fibs) and do the
1568          * requested action. Realistically, this will either be fib 0
1569          * for protocols that don't do multiple tables or all the
1570          * tables for those that do.
1571          */
1572         for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
1573                 if (cmd == RTM_DELETE) {
1574                         struct radix_node *rn;
1575                         /*
1576                          * Look up an rtentry that is in the routing tree and
1577                          * contains the correct info.
1578                          */
1579                         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1580                         if (rnh == NULL)
1581                                 /* this table doesn't exist but others might */
1582                                 continue;
1583                         RADIX_NODE_HEAD_RLOCK(rnh);
1584 #ifdef RADIX_MPATH
1585                         if (rn_mpath_capable(rnh)) {
1586
1587                                 rn = rnh->rnh_matchaddr(dst, rnh);
1588                                 if (rn == NULL) 
1589                                         error = ESRCH;
1590                                 else {
1591                                         rt = RNTORT(rn);
1592                                         /*
1593                                          * for interface route the
1594                                          * rt->rt_gateway is sockaddr_intf
1595                                          * for cloning ARP entries, so
1596                                          * rt_mpath_matchgate must use the
1597                                          * interface address
1598                                          */
1599                                         rt = rt_mpath_matchgate(rt,
1600                                             ifa->ifa_addr);
1601                                         if (!rt) 
1602                                                 error = ESRCH;
1603                                 }
1604                         }
1605                         else
1606 #endif
1607                         rn = rnh->rnh_lookup(dst, netmask, rnh);
1608                         error = (rn == NULL ||
1609                             (rn->rn_flags & RNF_ROOT) ||
1610                             RNTORT(rn)->rt_ifa != ifa);
1611                         RADIX_NODE_HEAD_RUNLOCK(rnh);
1612                         if (error) {
1613                                 /* this is only an error if bad on ALL tables */
1614                                 continue;
1615                         }
1616                 }
1617                 /*
1618                  * Do the actual request
1619                  */
1620                 bzero((caddr_t)&info, sizeof(info));
1621                 info.rti_ifa = ifa;
1622                 info.rti_flags = flags |
1623                     (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1624                 info.rti_info[RTAX_DST] = dst;
1625                 /* 
1626                  * doing this for compatibility reasons
1627                  */
1628                 if (cmd == RTM_ADD)
1629                         info.rti_info[RTAX_GATEWAY] =
1630                             (struct sockaddr *)&null_sdl;
1631                 else
1632                         info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1633                 info.rti_info[RTAX_NETMASK] = netmask;
1634                 error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1635
1636                 if ((error == EEXIST) && (cmd == RTM_ADD)) {
1637                         /*
1638                          * Interface route addition failed.
1639                          * Atomically delete current prefix generating
1640                          * RTM_DELETE message, and retry adding
1641                          * interface prefix.
1642                          */
1643                         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1644                         RADIX_NODE_HEAD_LOCK(rnh);
1645
1646                         /* Delete old prefix */
1647                         info.rti_ifa = NULL;
1648                         info.rti_flags = RTF_RNH_LOCKED;
1649
1650                         error = rtrequest1_fib(RTM_DELETE, &info, NULL, fibnum);
1651                         if (error == 0) {
1652                                 info.rti_ifa = ifa;
1653                                 info.rti_flags = flags | RTF_RNH_LOCKED |
1654                                     (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1655                                 error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1656                         }
1657
1658                         RADIX_NODE_HEAD_UNLOCK(rnh);
1659                 }
1660
1661
1662                 if (error == 0 && rt != NULL) {
1663                         /*
1664                          * notify any listening routing agents of the change
1665                          */
1666                         RT_LOCK(rt);
1667 #ifdef RADIX_MPATH
1668                         /*
1669                          * in case address alias finds the first address
1670                          * e.g. ifconfig bge0 192.0.2.246/24
1671                          * e.g. ifconfig bge0 192.0.2.247/24
1672                          * the address set in the route is 192.0.2.246
1673                          * so we need to replace it with 192.0.2.247
1674                          */
1675                         if (memcmp(rt->rt_ifa->ifa_addr,
1676                             ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
1677                                 ifa_free(rt->rt_ifa);
1678                                 ifa_ref(ifa);
1679                                 rt->rt_ifp = ifa->ifa_ifp;
1680                                 rt->rt_ifa = ifa;
1681                         }
1682 #endif
1683                         /* 
1684                          * doing this for compatibility reasons
1685                          */
1686                         if (cmd == RTM_ADD) {
1687                             ((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
1688                                 rt->rt_ifp->if_type;
1689                             ((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1690                                 rt->rt_ifp->if_index;
1691                         }
1692                         RT_ADDREF(rt);
1693                         RT_UNLOCK(rt);
1694                         rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
1695                         RT_LOCK(rt);
1696                         RT_REMREF(rt);
1697                         if (cmd == RTM_DELETE) {
1698                                 /*
1699                                  * If we are deleting, and we found an entry,
1700                                  * then it's been removed from the tree..
1701                                  * now throw it away.
1702                                  */
1703                                 RTFREE_LOCKED(rt);
1704                         } else {
1705                                 if (cmd == RTM_ADD) {
1706                                         /*
1707                                          * We just wanted to add it..
1708                                          * we don't actually need a reference.
1709                                          */
1710                                         RT_REMREF(rt);
1711                                 }
1712                                 RT_UNLOCK(rt);
1713                         }
1714                         didwork = 1;
1715                 }
1716                 if (error)
1717                         a_failure = error;
1718         }
1719         if (cmd == RTM_DELETE) {
1720                 if (didwork) {
1721                         error = 0;
1722                 } else {
1723                         /* we only give an error if it wasn't in any table */
1724                         error = ((flags & RTF_HOST) ?
1725                             EHOSTUNREACH : ENETUNREACH);
1726                 }
1727         } else {
1728                 if (a_failure) {
1729                         /* return an error if any of them failed */
1730                         error = a_failure;
1731                 }
1732         }
1733         return (error);
1734 }
1735
1736 /*
1737  * Set up a routing table entry, normally
1738  * for an interface.
1739  */
1740 int
1741 rtinit(struct ifaddr *ifa, int cmd, int flags)
1742 {
1743         struct sockaddr *dst;
1744         int fib = RT_DEFAULT_FIB;
1745
1746         if (flags & RTF_HOST) {
1747                 dst = ifa->ifa_dstaddr;
1748         } else {
1749                 dst = ifa->ifa_addr;
1750         }
1751
1752         switch (dst->sa_family) {
1753         case AF_INET6:
1754         case AF_INET:
1755                 /* We do support multiple FIBs. */
1756                 fib = -1;
1757                 break;
1758         }
1759         return (rtinit1(ifa, cmd, flags, fib));
1760 }