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