]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/route.c
Import libxo-0.7.2; add xo_options.7.
[FreeBSD/FreeBSD.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  * 3. 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/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_var.h>
58 #include <net/if_dl.h>
59 #include <net/route.h>
60 #include <net/route_var.h>
61 #include <net/vnet.h>
62 #include <net/flowtable.h>
63
64 #ifdef RADIX_MPATH
65 #include <net/radix_mpath.h>
66 #endif
67
68 #include <netinet/in.h>
69 #include <netinet/ip_mroute.h>
70
71 #include <vm/uma.h>
72
73 #define RT_MAXFIBS      UINT16_MAX
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_RDTUN, &rt_numfibs, 0, "");
100
101 /*
102  * By default add routes to all fibs for new interfaces.
103  * Once this is set to 0 then only allocate routes on interface
104  * changes for the FIB of the caller when adding a new set of addresses
105  * to an interface.  XXX this is a shotgun aproach to a problem that needs
106  * a more fine grained solution.. that will come.
107  * XXX also has the problems getting the FIB from curthread which will not
108  * always work given the fib can be overridden and prefixes can be added
109  * from the network stack context.
110  */
111 VNET_DEFINE(u_int, rt_add_addr_allfibs) = 1;
112 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RWTUN | CTLFLAG_VNET,
113     &VNET_NAME(rt_add_addr_allfibs), 0, "");
114
115 VNET_DEFINE(struct rtstat, rtstat);
116 #define V_rtstat        VNET(rtstat)
117
118 VNET_DEFINE(struct rib_head *, rt_tables);
119 #define V_rt_tables     VNET(rt_tables)
120
121 VNET_DEFINE(int, rttrash);              /* routes not in table but not freed */
122 #define V_rttrash       VNET(rttrash)
123
124
125 /*
126  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
127  * The operation can be done safely (in this code) because a
128  * 'struct rtentry' starts with two 'struct radix_node''s, the first
129  * one representing leaf nodes in the routing tree, which is
130  * what the code in radix.c passes us as a 'struct radix_node'.
131  *
132  * But because there are a lot of assumptions in this conversion,
133  * do not cast explicitly, but always use the macro below.
134  */
135 #define RNTORT(p)       ((struct rtentry *)(p))
136
137 static VNET_DEFINE(uma_zone_t, rtzone);         /* Routing table UMA zone. */
138 #define V_rtzone        VNET(rtzone)
139
140 static int rtrequest1_fib_change(struct rib_head *, struct rt_addrinfo *,
141     struct rtentry **, u_int);
142 static void rt_setmetrics(const struct rt_addrinfo *, struct rtentry *);
143 static int rt_ifdelroute(const struct rtentry *rt, void *arg);
144 static struct rtentry *rt_unlinkrte(struct rib_head *rnh,
145     struct rt_addrinfo *info, int *perror);
146 static void rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info);
147 #ifdef RADIX_MPATH
148 static struct radix_node *rt_mpath_unlink(struct rib_head *rnh,
149     struct rt_addrinfo *info, struct rtentry *rto, int *perror);
150 #endif
151 static int rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info,
152     int flags);
153
154 struct if_mtuinfo
155 {
156         struct ifnet    *ifp;
157         int             mtu;
158 };
159
160 static int      if_updatemtu_cb(struct radix_node *, void *);
161
162 /*
163  * handler for net.my_fibnum
164  */
165 static int
166 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
167 {
168         int fibnum;
169         int error;
170  
171         fibnum = curthread->td_proc->p_fibnum;
172         error = sysctl_handle_int(oidp, &fibnum, 0, req);
173         return (error);
174 }
175
176 SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
177             NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
178
179 static __inline struct rib_head **
180 rt_tables_get_rnh_ptr(int table, int fam)
181 {
182         struct rib_head **rnh;
183
184         KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
185             __func__));
186         KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
187             __func__));
188
189         /* rnh is [fib=0][af=0]. */
190         rnh = (struct rib_head **)V_rt_tables;
191         /* Get the offset to the requested table and fam. */
192         rnh += table * (AF_MAX+1) + fam;
193
194         return (rnh);
195 }
196
197 struct rib_head *
198 rt_tables_get_rnh(int table, int fam)
199 {
200
201         return (*rt_tables_get_rnh_ptr(table, fam));
202 }
203
204 u_int
205 rt_tables_get_gen(int table, int fam)
206 {
207         struct rib_head *rnh;
208
209         rnh = *rt_tables_get_rnh_ptr(table, fam);
210         KASSERT(rnh != NULL, ("%s: NULL rib_head pointer table %d fam %d",
211             __func__, table, fam));
212         return (rnh->rnh_gen);
213 }
214
215
216 /*
217  * route initialization must occur before ip6_init2(), which happenas at
218  * SI_ORDER_MIDDLE.
219  */
220 static void
221 route_init(void)
222 {
223
224         /* whack the tunable ints into  line. */
225         if (rt_numfibs > RT_MAXFIBS)
226                 rt_numfibs = RT_MAXFIBS;
227         if (rt_numfibs == 0)
228                 rt_numfibs = 1;
229 }
230 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
231
232 static int
233 rtentry_zinit(void *mem, int size, int how)
234 {
235         struct rtentry *rt = mem;
236
237         rt->rt_pksent = counter_u64_alloc(how);
238         if (rt->rt_pksent == NULL)
239                 return (ENOMEM);
240
241         RT_LOCK_INIT(rt);
242
243         return (0);
244 }
245
246 static void
247 rtentry_zfini(void *mem, int size)
248 {
249         struct rtentry *rt = mem;
250
251         RT_LOCK_DESTROY(rt);
252         counter_u64_free(rt->rt_pksent);
253 }
254
255 static int
256 rtentry_ctor(void *mem, int size, void *arg, int how)
257 {
258         struct rtentry *rt = mem;
259
260         bzero(rt, offsetof(struct rtentry, rt_endzero));
261         counter_u64_zero(rt->rt_pksent);
262         rt->rt_chain = NULL;
263
264         return (0);
265 }
266
267 static void
268 rtentry_dtor(void *mem, int size, void *arg)
269 {
270         struct rtentry *rt = mem;
271
272         RT_UNLOCK_COND(rt);
273 }
274
275 static void
276 vnet_route_init(const void *unused __unused)
277 {
278         struct domain *dom;
279         struct rib_head **rnh;
280         int table;
281         int fam;
282
283         V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
284             sizeof(struct rib_head *), M_RTABLE, M_WAITOK|M_ZERO);
285
286         V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
287             rtentry_ctor, rtentry_dtor,
288             rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
289         for (dom = domains; dom; dom = dom->dom_next) {
290                 if (dom->dom_rtattach == NULL)
291                         continue;
292
293                 for  (table = 0; table < rt_numfibs; table++) {
294                         fam = dom->dom_family;
295                         if (table != 0 && fam != AF_INET6 && fam != AF_INET)
296                                 break;
297
298                         rnh = rt_tables_get_rnh_ptr(table, fam);
299                         if (rnh == NULL)
300                                 panic("%s: rnh NULL", __func__);
301                         dom->dom_rtattach((void **)rnh, 0);
302                 }
303         }
304 }
305 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
306     vnet_route_init, 0);
307
308 #ifdef VIMAGE
309 static void
310 vnet_route_uninit(const void *unused __unused)
311 {
312         int table;
313         int fam;
314         struct domain *dom;
315         struct rib_head **rnh;
316
317         for (dom = domains; dom; dom = dom->dom_next) {
318                 if (dom->dom_rtdetach == NULL)
319                         continue;
320
321                 for (table = 0; table < rt_numfibs; table++) {
322                         fam = dom->dom_family;
323
324                         if (table != 0 && fam != AF_INET6 && fam != AF_INET)
325                                 break;
326
327                         rnh = rt_tables_get_rnh_ptr(table, fam);
328                         if (rnh == NULL)
329                                 panic("%s: rnh NULL", __func__);
330                         dom->dom_rtdetach((void **)rnh, 0);
331                 }
332         }
333
334         free(V_rt_tables, M_RTABLE);
335         uma_zdestroy(V_rtzone);
336 }
337 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
338     vnet_route_uninit, 0);
339 #endif
340
341 struct rib_head *
342 rt_table_init(int offset)
343 {
344         struct rib_head *rh;
345
346         rh = malloc(sizeof(struct rib_head), M_RTABLE, M_WAITOK | M_ZERO);
347
348         /* TODO: These details should be hidded inside radix.c */
349         /* Init masks tree */
350         rn_inithead_internal(&rh->head, rh->rnh_nodes, offset);
351         rn_inithead_internal(&rh->rmhead.head, rh->rmhead.mask_nodes, 0);
352         rh->head.rnh_masks = &rh->rmhead;
353
354         /* Init locks */
355         RIB_LOCK_INIT(rh);
356
357         /* Finally, set base callbacks */
358         rh->rnh_addaddr = rn_addroute;
359         rh->rnh_deladdr = rn_delete;
360         rh->rnh_matchaddr = rn_match;
361         rh->rnh_lookup = rn_lookup;
362         rh->rnh_walktree = rn_walktree;
363         rh->rnh_walktree_from = rn_walktree_from;
364
365         return (rh);
366 }
367
368 static int
369 rt_freeentry(struct radix_node *rn, void *arg)
370 {
371         struct radix_head * const rnh = arg;
372         struct radix_node *x;
373
374         x = (struct radix_node *)rn_delete(rn + 2, NULL, rnh);
375         if (x != NULL)
376                 R_Free(x);
377         return (0);
378 }
379
380 void
381 rt_table_destroy(struct rib_head *rh)
382 {
383
384         rn_walktree(&rh->rmhead.head, rt_freeentry, &rh->rmhead.head);
385
386         /* Assume table is already empty */
387         RIB_LOCK_DESTROY(rh);
388         free(rh, M_RTABLE);
389 }
390
391
392 #ifndef _SYS_SYSPROTO_H_
393 struct setfib_args {
394         int     fibnum;
395 };
396 #endif
397 int
398 sys_setfib(struct thread *td, struct setfib_args *uap)
399 {
400         if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
401                 return EINVAL;
402         td->td_proc->p_fibnum = uap->fibnum;
403         return (0);
404 }
405
406 /*
407  * Packet routing routines.
408  */
409 void
410 rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
411 {
412         struct rtentry *rt;
413
414         if ((rt = ro->ro_rt) != NULL) {
415                 if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
416                         return;
417                 RTFREE(rt);
418                 ro->ro_rt = NULL;
419         }
420         ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
421         if (ro->ro_rt)
422                 RT_UNLOCK(ro->ro_rt);
423 }
424
425 /*
426  * Look up the route that matches the address given
427  * Or, at least try.. Create a cloned route if needed.
428  *
429  * The returned route, if any, is locked.
430  */
431 struct rtentry *
432 rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
433 {
434
435         return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
436 }
437
438 struct rtentry *
439 rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
440                     u_int fibnum)
441 {
442         struct rib_head *rh;
443         struct radix_node *rn;
444         struct rtentry *newrt;
445         struct rt_addrinfo info;
446         int err = 0, msgtype = RTM_MISS;
447
448         KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
449         rh = rt_tables_get_rnh(fibnum, dst->sa_family);
450         newrt = NULL;
451         if (rh == NULL)
452                 goto miss;
453
454         /*
455          * Look up the address in the table for that Address Family
456          */
457         RIB_RLOCK(rh);
458         rn = rh->rnh_matchaddr(dst, &rh->head);
459         if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
460                 newrt = RNTORT(rn);
461                 RT_LOCK(newrt);
462                 RT_ADDREF(newrt);
463                 RIB_RUNLOCK(rh);
464                 return (newrt);
465
466         } else
467                 RIB_RUNLOCK(rh);
468         
469         /*
470          * Either we hit the root or could not find any match,
471          * which basically means: "cannot get there from here".
472          */
473 miss:
474         V_rtstat.rts_unreach++;
475
476         if (report) {
477                 /*
478                  * If required, report the failure to the supervising
479                  * Authorities.
480                  * For a delete, this is not an error. (report == 0)
481                  */
482                 bzero(&info, sizeof(info));
483                 info.rti_info[RTAX_DST] = dst;
484                 rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
485         }
486         return (newrt);
487 }
488
489 /*
490  * Remove a reference count from an rtentry.
491  * If the count gets low enough, take it out of the routing table
492  */
493 void
494 rtfree(struct rtentry *rt)
495 {
496         struct rib_head *rnh;
497
498         KASSERT(rt != NULL,("%s: NULL rt", __func__));
499         rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
500         KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
501
502         RT_LOCK_ASSERT(rt);
503
504         /*
505          * The callers should use RTFREE_LOCKED() or RTFREE(), so
506          * we should come here exactly with the last reference.
507          */
508         RT_REMREF(rt);
509         if (rt->rt_refcnt > 0) {
510                 log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
511                 goto done;
512         }
513
514         /*
515          * On last reference give the "close method" a chance
516          * to cleanup private state.  This also permits (for
517          * IPv4 and IPv6) a chance to decide if the routing table
518          * entry should be purged immediately or at a later time.
519          * When an immediate purge is to happen the close routine
520          * typically calls rtexpunge which clears the RTF_UP flag
521          * on the entry so that the code below reclaims the storage.
522          */
523         if (rt->rt_refcnt == 0 && rnh->rnh_close)
524                 rnh->rnh_close((struct radix_node *)rt, &rnh->head);
525
526         /*
527          * If we are no longer "up" (and ref == 0)
528          * then we can free the resources associated
529          * with the route.
530          */
531         if ((rt->rt_flags & RTF_UP) == 0) {
532                 if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
533                         panic("rtfree 2");
534                 /*
535                  * the rtentry must have been removed from the routing table
536                  * so it is represented in rttrash.. remove that now.
537                  */
538                 V_rttrash--;
539 #ifdef  DIAGNOSTIC
540                 if (rt->rt_refcnt < 0) {
541                         printf("rtfree: %p not freed (neg refs)\n", rt);
542                         goto done;
543                 }
544 #endif
545                 /*
546                  * release references on items we hold them on..
547                  * e.g other routes and ifaddrs.
548                  */
549                 if (rt->rt_ifa)
550                         ifa_free(rt->rt_ifa);
551                 /*
552                  * The key is separatly alloc'd so free it (see rt_setgate()).
553                  * This also frees the gateway, as they are always malloc'd
554                  * together.
555                  */
556                 R_Free(rt_key(rt));
557
558                 /*
559                  * and the rtentry itself of course
560                  */
561                 uma_zfree(V_rtzone, rt);
562                 return;
563         }
564 done:
565         RT_UNLOCK(rt);
566 }
567
568
569 /*
570  * Force a routing table entry to the specified
571  * destination to go through the given gateway.
572  * Normally called as a result of a routing redirect
573  * message from the network layer.
574  */
575 void
576 rtredirect_fib(struct sockaddr *dst,
577         struct sockaddr *gateway,
578         struct sockaddr *netmask,
579         int flags,
580         struct sockaddr *src,
581         u_int fibnum)
582 {
583         struct rtentry *rt;
584         int error = 0;
585         short *stat = NULL;
586         struct rt_addrinfo info;
587         struct ifaddr *ifa;
588         struct rib_head *rnh;
589
590         ifa = NULL;
591         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
592         if (rnh == NULL) {
593                 error = EAFNOSUPPORT;
594                 goto out;
595         }
596
597         /* verify the gateway is directly reachable */
598         if ((ifa = ifa_ifwithnet(gateway, 0, fibnum)) == NULL) {
599                 error = ENETUNREACH;
600                 goto out;
601         }
602         rt = rtalloc1_fib(dst, 0, 0UL, fibnum); /* NB: rt is locked */
603         /*
604          * If the redirect isn't from our current router for this dst,
605          * it's either old or wrong.  If it redirects us to ourselves,
606          * we have a routing loop, perhaps as a result of an interface
607          * going down recently.
608          */
609         if (!(flags & RTF_DONE) && rt) {
610                 if (!sa_equal(src, rt->rt_gateway)) {
611                         error = EINVAL;
612                         goto done;
613                 }
614                 if (rt->rt_ifa != ifa && ifa->ifa_addr->sa_family != AF_LINK) {
615                         error = EINVAL;
616                         goto done;
617                 }
618         }
619         if ((flags & RTF_GATEWAY) && ifa_ifwithaddr_check(gateway)) {
620                 error = EHOSTUNREACH;
621                 goto done;
622         }
623         /*
624          * Create a new entry if we just got back a wildcard entry
625          * or the lookup failed.  This is necessary for hosts
626          * which use routing redirects generated by smart gateways
627          * to dynamically build the routing tables.
628          */
629         if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
630                 goto create;
631         /*
632          * Don't listen to the redirect if it's
633          * for a route to an interface.
634          */
635         if (rt->rt_flags & RTF_GATEWAY) {
636                 if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
637                         /*
638                          * Changing from route to net => route to host.
639                          * Create new route, rather than smashing route to net.
640                          */
641                 create:
642                         if (rt != NULL)
643                                 RTFREE_LOCKED(rt);
644                 
645                         flags |= RTF_DYNAMIC;
646                         bzero((caddr_t)&info, sizeof(info));
647                         info.rti_info[RTAX_DST] = dst;
648                         info.rti_info[RTAX_GATEWAY] = gateway;
649                         info.rti_info[RTAX_NETMASK] = netmask;
650                         info.rti_ifa = ifa;
651                         info.rti_flags = flags;
652                         error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
653                         if (rt != NULL) {
654                                 RT_LOCK(rt);
655                                 flags = rt->rt_flags;
656                         }
657                         
658                         stat = &V_rtstat.rts_dynamic;
659                 } else {
660
661                         /*
662                          * Smash the current notion of the gateway to
663                          * this destination.  Should check about netmask!!!
664                          */
665                         if ((flags & RTF_GATEWAY) == 0)
666                                 rt->rt_flags &= ~RTF_GATEWAY;
667                         rt->rt_flags |= RTF_MODIFIED;
668                         flags |= RTF_MODIFIED;
669                         stat = &V_rtstat.rts_newgateway;
670                         /*
671                          * add the key and gateway (in one malloc'd chunk).
672                          */
673                         RT_UNLOCK(rt);
674                         RIB_WLOCK(rnh);
675                         RT_LOCK(rt);
676                         rt_setgate(rt, rt_key(rt), gateway);
677                         RIB_WUNLOCK(rnh);
678                 }
679         } else
680                 error = EHOSTUNREACH;
681 done:
682         if (rt)
683                 RTFREE_LOCKED(rt);
684 out:
685         if (error)
686                 V_rtstat.rts_badredirect++;
687         else if (stat != NULL)
688                 (*stat)++;
689         bzero((caddr_t)&info, sizeof(info));
690         info.rti_info[RTAX_DST] = dst;
691         info.rti_info[RTAX_GATEWAY] = gateway;
692         info.rti_info[RTAX_NETMASK] = netmask;
693         info.rti_info[RTAX_AUTHOR] = src;
694         rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
695         if (ifa != NULL)
696                 ifa_free(ifa);
697 }
698
699 /*
700  * Routing table ioctl interface.
701  */
702 int
703 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
704 {
705
706         /*
707          * If more ioctl commands are added here, make sure the proper
708          * super-user checks are being performed because it is possible for
709          * prison-root to make it this far if raw sockets have been enabled
710          * in jails.
711          */
712 #ifdef INET
713         /* Multicast goop, grrr... */
714         return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
715 #else /* INET */
716         return ENXIO;
717 #endif /* INET */
718 }
719
720 struct ifaddr *
721 ifa_ifwithroute(int flags, const struct sockaddr *dst, struct sockaddr *gateway,
722                                 u_int fibnum)
723 {
724         struct ifaddr *ifa;
725         int not_found = 0;
726
727         if ((flags & RTF_GATEWAY) == 0) {
728                 /*
729                  * If we are adding a route to an interface,
730                  * and the interface is a pt to pt link
731                  * we should search for the destination
732                  * as our clue to the interface.  Otherwise
733                  * we can use the local address.
734                  */
735                 ifa = NULL;
736                 if (flags & RTF_HOST)
737                         ifa = ifa_ifwithdstaddr(dst, fibnum);
738                 if (ifa == NULL)
739                         ifa = ifa_ifwithaddr(gateway);
740         } else {
741                 /*
742                  * If we are adding a route to a remote net
743                  * or host, the gateway may still be on the
744                  * other end of a pt to pt link.
745                  */
746                 ifa = ifa_ifwithdstaddr(gateway, fibnum);
747         }
748         if (ifa == NULL)
749                 ifa = ifa_ifwithnet(gateway, 0, fibnum);
750         if (ifa == NULL) {
751                 struct rtentry *rt = rtalloc1_fib(gateway, 0, 0, fibnum);
752                 if (rt == NULL)
753                         return (NULL);
754                 /*
755                  * dismiss a gateway that is reachable only
756                  * through the default router
757                  */
758                 switch (gateway->sa_family) {
759                 case AF_INET:
760                         if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
761                                 not_found = 1;
762                         break;
763                 case AF_INET6:
764                         if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
765                                 not_found = 1;
766                         break;
767                 default:
768                         break;
769                 }
770                 if (!not_found && rt->rt_ifa != NULL) {
771                         ifa = rt->rt_ifa;
772                         ifa_ref(ifa);
773                 }
774                 RT_REMREF(rt);
775                 RT_UNLOCK(rt);
776                 if (not_found || ifa == NULL)
777                         return (NULL);
778         }
779         if (ifa->ifa_addr->sa_family != dst->sa_family) {
780                 struct ifaddr *oifa = ifa;
781                 ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
782                 if (ifa == NULL)
783                         ifa = oifa;
784                 else
785                         ifa_free(oifa);
786         }
787         return (ifa);
788 }
789
790 /*
791  * Do appropriate manipulations of a routing tree given
792  * all the bits of info needed
793  */
794 int
795 rtrequest_fib(int req,
796         struct sockaddr *dst,
797         struct sockaddr *gateway,
798         struct sockaddr *netmask,
799         int flags,
800         struct rtentry **ret_nrt,
801         u_int fibnum)
802 {
803         struct rt_addrinfo info;
804
805         if (dst->sa_len == 0)
806                 return(EINVAL);
807
808         bzero((caddr_t)&info, sizeof(info));
809         info.rti_flags = flags;
810         info.rti_info[RTAX_DST] = dst;
811         info.rti_info[RTAX_GATEWAY] = gateway;
812         info.rti_info[RTAX_NETMASK] = netmask;
813         return rtrequest1_fib(req, &info, ret_nrt, fibnum);
814 }
815
816
817 /*
818  * Copy most of @rt data into @info.
819  *
820  * If @flags contains NHR_COPY, copies dst,netmask and gw to the
821  * pointers specified by @info structure. Assume such pointers
822  * are zeroed sockaddr-like structures with sa_len field initialized
823  * to reflect size of the provided buffer. if no NHR_COPY is specified,
824  * point dst,netmask and gw @info fields to appropriate @rt values.
825  *
826  * if @flags contains NHR_REF, do refcouting on rt_ifp.
827  *
828  * Returns 0 on success.
829  */
830 int
831 rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info, int flags)
832 {
833         struct rt_metrics *rmx;
834         struct sockaddr *src, *dst;
835         int sa_len;
836
837         if (flags & NHR_COPY) {
838                 /* Copy destination if dst is non-zero */
839                 src = rt_key(rt);
840                 dst = info->rti_info[RTAX_DST];
841                 sa_len = src->sa_len;
842                 if (dst != NULL) {
843                         if (src->sa_len > dst->sa_len)
844                                 return (ENOMEM);
845                         memcpy(dst, src, src->sa_len);
846                         info->rti_addrs |= RTA_DST;
847                 }
848
849                 /* Copy mask if set && dst is non-zero */
850                 src = rt_mask(rt);
851                 dst = info->rti_info[RTAX_NETMASK];
852                 if (src != NULL && dst != NULL) {
853
854                         /*
855                          * Radix stores different value in sa_len,
856                          * assume rt_mask() to have the same length
857                          * as rt_key()
858                          */
859                         if (sa_len > dst->sa_len)
860                                 return (ENOMEM);
861                         memcpy(dst, src, src->sa_len);
862                         info->rti_addrs |= RTA_NETMASK;
863                 }
864
865                 /* Copy gateway is set && dst is non-zero */
866                 src = rt->rt_gateway;
867                 dst = info->rti_info[RTAX_GATEWAY];
868                 if ((rt->rt_flags & RTF_GATEWAY) && src != NULL && dst != NULL){
869                         if (src->sa_len > dst->sa_len)
870                                 return (ENOMEM);
871                         memcpy(dst, src, src->sa_len);
872                         info->rti_addrs |= RTA_GATEWAY;
873                 }
874         } else {
875                 info->rti_info[RTAX_DST] = rt_key(rt);
876                 info->rti_addrs |= RTA_DST;
877                 if (rt_mask(rt) != NULL) {
878                         info->rti_info[RTAX_NETMASK] = rt_mask(rt);
879                         info->rti_addrs |= RTA_NETMASK;
880                 }
881                 if (rt->rt_flags & RTF_GATEWAY) {
882                         info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
883                         info->rti_addrs |= RTA_GATEWAY;
884                 }
885         }
886
887         rmx = info->rti_rmx;
888         if (rmx != NULL) {
889                 info->rti_mflags |= RTV_MTU;
890                 rmx->rmx_mtu = rt->rt_mtu;
891         }
892
893         info->rti_flags = rt->rt_flags;
894         info->rti_ifp = rt->rt_ifp;
895         info->rti_ifa = rt->rt_ifa;
896
897         if (flags & NHR_REF) {
898                 /* Do 'traditional' refcouting */
899                 if_ref(info->rti_ifp);
900         }
901
902         return (0);
903 }
904
905 /*
906  * Lookups up route entry for @dst in RIB database for fib @fibnum.
907  * Exports entry data to @info using rt_exportinfo().
908  *
909  * if @flags contains NHR_REF, refcouting is performed on rt_ifp.
910  *   All references can be released later by calling rib_free_info()
911  *
912  * Returns 0 on success.
913  * Returns ENOENT for lookup failure, ENOMEM for export failure.
914  */
915 int
916 rib_lookup_info(uint32_t fibnum, const struct sockaddr *dst, uint32_t flags,
917     uint32_t flowid, struct rt_addrinfo *info)
918 {
919         struct rib_head *rh;
920         struct radix_node *rn;
921         struct rtentry *rt;
922         int error;
923
924         KASSERT((fibnum < rt_numfibs), ("rib_lookup_rte: bad fibnum"));
925         rh = rt_tables_get_rnh(fibnum, dst->sa_family);
926         if (rh == NULL)
927                 return (ENOENT);
928
929         RIB_RLOCK(rh);
930         rn = rh->rnh_matchaddr(__DECONST(void *, dst), &rh->head);
931         if (rn != NULL && ((rn->rn_flags & RNF_ROOT) == 0)) {
932                 rt = RNTORT(rn);
933                 /* Ensure route & ifp is UP */
934                 if (RT_LINK_IS_UP(rt->rt_ifp)) {
935                         flags = (flags & NHR_REF) | NHR_COPY;
936                         error = rt_exportinfo(rt, info, flags);
937                         RIB_RUNLOCK(rh);
938
939                         return (error);
940                 }
941         }
942         RIB_RUNLOCK(rh);
943
944         return (ENOENT);
945 }
946
947 /*
948  * Releases all references acquired by rib_lookup_info() when
949  * called with NHR_REF flags.
950  */
951 void
952 rib_free_info(struct rt_addrinfo *info)
953 {
954
955         if_rele(info->rti_ifp);
956 }
957
958 /*
959  * Iterates over all existing fibs in system calling
960  *  @setwa_f function prior to traversing each fib.
961  *  Calls @wa_f function for each element in current fib.
962  * If af is not AF_UNSPEC, iterates over fibs in particular
963  * address family.
964  */
965 void
966 rt_foreach_fib_walk(int af, rt_setwarg_t *setwa_f, rt_walktree_f_t *wa_f,
967     void *arg)
968 {
969         struct rib_head *rnh;
970         uint32_t fibnum;
971         int i;
972
973         for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
974                 /* Do we want some specific family? */
975                 if (af != AF_UNSPEC) {
976                         rnh = rt_tables_get_rnh(fibnum, af);
977                         if (rnh == NULL)
978                                 continue;
979                         if (setwa_f != NULL)
980                                 setwa_f(rnh, fibnum, af, arg);
981
982                         RIB_WLOCK(rnh);
983                         rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
984                         RIB_WUNLOCK(rnh);
985                         continue;
986                 }
987
988                 for (i = 1; i <= AF_MAX; i++) {
989                         rnh = rt_tables_get_rnh(fibnum, i);
990                         if (rnh == NULL)
991                                 continue;
992                         if (setwa_f != NULL)
993                                 setwa_f(rnh, fibnum, i, arg);
994
995                         RIB_WLOCK(rnh);
996                         rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
997                         RIB_WUNLOCK(rnh);
998                 }
999         }
1000 }
1001
1002 struct rt_delinfo
1003 {
1004         struct rt_addrinfo info;
1005         struct rib_head *rnh;
1006         struct rtentry *head;
1007 };
1008
1009 /*
1010  * Conditionally unlinks @rn from radix tree based
1011  * on info data passed in @arg.
1012  */
1013 static int
1014 rt_checkdelroute(struct radix_node *rn, void *arg)
1015 {
1016         struct rt_delinfo *di;
1017         struct rt_addrinfo *info;
1018         struct rtentry *rt;
1019         int error;
1020
1021         di = (struct rt_delinfo *)arg;
1022         rt = (struct rtentry *)rn;
1023         info = &di->info;
1024         error = 0;
1025
1026         info->rti_info[RTAX_DST] = rt_key(rt);
1027         info->rti_info[RTAX_NETMASK] = rt_mask(rt);
1028         info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1029
1030         rt = rt_unlinkrte(di->rnh, info, &error);
1031         if (rt == NULL) {
1032                 /* Either not allowed or not matched. Skip entry */
1033                 return (0);
1034         }
1035
1036         /* Entry was unlinked. Add to the list and return */
1037         rt->rt_chain = di->head;
1038         di->head = rt;
1039
1040         return (0);
1041 }
1042
1043 /*
1044  * Iterates over all existing fibs in system.
1045  * Deletes each element for which @filter_f function returned
1046  * non-zero value.
1047  * If @af is not AF_UNSPEC, iterates over fibs in particular
1048  * address family.
1049  */
1050 void
1051 rt_foreach_fib_walk_del(int af, rt_filter_f_t *filter_f, void *arg)
1052 {
1053         struct rib_head *rnh;
1054         struct rt_delinfo di;
1055         struct rtentry *rt;
1056         uint32_t fibnum;
1057         int i, start, end;
1058
1059         bzero(&di, sizeof(di));
1060         di.info.rti_filter = filter_f;
1061         di.info.rti_filterdata = arg;
1062
1063         for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
1064                 /* Do we want some specific family? */
1065                 if (af != AF_UNSPEC) {
1066                         start = af;
1067                         end = af;
1068                 } else {
1069                         start = 1;
1070                         end = AF_MAX;
1071                 }
1072
1073                 for (i = start; i <= end; i++) {
1074                         rnh = rt_tables_get_rnh(fibnum, i);
1075                         if (rnh == NULL)
1076                                 continue;
1077                         di.rnh = rnh;
1078
1079                         RIB_WLOCK(rnh);
1080                         rnh->rnh_walktree(&rnh->head, rt_checkdelroute, &di);
1081                         RIB_WUNLOCK(rnh);
1082
1083                         if (di.head == NULL)
1084                                 continue;
1085
1086                         /* We might have something to reclaim */
1087                         while (di.head != NULL) {
1088                                 rt = di.head;
1089                                 di.head = rt->rt_chain;
1090                                 rt->rt_chain = NULL;
1091
1092                                 /* TODO std rt -> rt_addrinfo export */
1093                                 di.info.rti_info[RTAX_DST] = rt_key(rt);
1094                                 di.info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1095
1096                                 rt_notifydelete(rt, &di.info);
1097                                 RTFREE_LOCKED(rt);
1098                         }
1099
1100                 }
1101         }
1102 }
1103
1104 /*
1105  * Delete Routes for a Network Interface
1106  *
1107  * Called for each routing entry via the rnh->rnh_walktree() call above
1108  * to delete all route entries referencing a detaching network interface.
1109  *
1110  * Arguments:
1111  *      rt      pointer to rtentry
1112  *      arg     argument passed to rnh->rnh_walktree() - detaching interface
1113  *
1114  * Returns:
1115  *      0       successful
1116  *      errno   failed - reason indicated
1117  */
1118 static int
1119 rt_ifdelroute(const struct rtentry *rt, void *arg)
1120 {
1121         struct ifnet    *ifp = arg;
1122
1123         if (rt->rt_ifp != ifp)
1124                 return (0);
1125
1126         /*
1127          * Protect (sorta) against walktree recursion problems
1128          * with cloned routes
1129          */
1130         if ((rt->rt_flags & RTF_UP) == 0)
1131                 return (0);
1132
1133         return (1);
1134 }
1135
1136 /*
1137  * Delete all remaining routes using this interface
1138  * Unfortuneatly the only way to do this is to slog through
1139  * the entire routing table looking for routes which point
1140  * to this interface...oh well...
1141  */
1142 void
1143 rt_flushifroutes_af(struct ifnet *ifp, int af)
1144 {
1145         KASSERT((af >= 1 && af <= AF_MAX), ("%s: af %d not >= 1 and <= %d",
1146             __func__, af, AF_MAX));
1147
1148         rt_foreach_fib_walk_del(af, rt_ifdelroute, ifp);
1149 }
1150
1151 void
1152 rt_flushifroutes(struct ifnet *ifp)
1153 {
1154
1155         rt_foreach_fib_walk_del(AF_UNSPEC, rt_ifdelroute, ifp);
1156 }
1157
1158 /*
1159  * Conditionally unlinks rtentry matching data inside @info from @rnh.
1160  * Returns unlinked, locked and referenced @rtentry on success,
1161  * Returns NULL and sets @perror to:
1162  * ESRCH - if prefix was not found,
1163  * EADDRINUSE - if trying to delete PINNED route without appropriate flag.
1164  * ENOENT - if supplied filter function returned 0 (not matched).
1165  */
1166 static struct rtentry *
1167 rt_unlinkrte(struct rib_head *rnh, struct rt_addrinfo *info, int *perror)
1168 {
1169         struct sockaddr *dst, *netmask;
1170         struct rtentry *rt;
1171         struct radix_node *rn;
1172
1173         dst = info->rti_info[RTAX_DST];
1174         netmask = info->rti_info[RTAX_NETMASK];
1175
1176         rt = (struct rtentry *)rnh->rnh_lookup(dst, netmask, &rnh->head);
1177         if (rt == NULL) {
1178                 *perror = ESRCH;
1179                 return (NULL);
1180         }
1181
1182         if ((info->rti_flags & RTF_PINNED) == 0) {
1183                 /* Check if target route can be deleted */
1184                 if (rt->rt_flags & RTF_PINNED) {
1185                         *perror = EADDRINUSE;
1186                         return (NULL);
1187                 }
1188         }
1189
1190         if (info->rti_filter != NULL) {
1191                 if (info->rti_filter(rt, info->rti_filterdata) == 0) {
1192                         /* Not matched */
1193                         *perror = ENOENT;
1194                         return (NULL);
1195                 }
1196
1197                 /*
1198                  * Filter function requested rte deletion.
1199                  * Ease the caller work by filling in remaining info
1200                  * from that particular entry.
1201                  */
1202                 info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1203         }
1204
1205         /*
1206          * Remove the item from the tree and return it.
1207          * Complain if it is not there and do no more processing.
1208          */
1209         *perror = ESRCH;
1210 #ifdef RADIX_MPATH
1211         if (rt_mpath_capable(rnh))
1212                 rn = rt_mpath_unlink(rnh, info, rt, perror);
1213         else
1214 #endif
1215         rn = rnh->rnh_deladdr(dst, netmask, &rnh->head);
1216         if (rn == NULL)
1217                 return (NULL);
1218
1219         if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1220                 panic ("rtrequest delete");
1221
1222         rt = RNTORT(rn);
1223         RT_LOCK(rt);
1224         RT_ADDREF(rt);
1225         rt->rt_flags &= ~RTF_UP;
1226
1227         *perror = 0;
1228
1229         return (rt);
1230 }
1231
1232 static void
1233 rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info)
1234 {
1235         struct ifaddr *ifa;
1236
1237         /*
1238          * give the protocol a chance to keep things in sync.
1239          */
1240         ifa = rt->rt_ifa;
1241         if (ifa != NULL && ifa->ifa_rtrequest != NULL)
1242                 ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1243
1244         /*
1245          * One more rtentry floating around that is not
1246          * linked to the routing table. rttrash will be decremented
1247          * when RTFREE(rt) is eventually called.
1248          */
1249         V_rttrash++;
1250 }
1251
1252
1253 /*
1254  * These (questionable) definitions of apparent local variables apply
1255  * to the next two functions.  XXXXXX!!!
1256  */
1257 #define dst     info->rti_info[RTAX_DST]
1258 #define gateway info->rti_info[RTAX_GATEWAY]
1259 #define netmask info->rti_info[RTAX_NETMASK]
1260 #define ifaaddr info->rti_info[RTAX_IFA]
1261 #define ifpaddr info->rti_info[RTAX_IFP]
1262 #define flags   info->rti_flags
1263
1264 /*
1265  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
1266  * it will be referenced so the caller must free it.
1267  */
1268 int
1269 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
1270 {
1271         struct ifaddr *ifa;
1272         int error = 0;
1273
1274         /*
1275          * ifp may be specified by sockaddr_dl
1276          * when protocol address is ambiguous.
1277          */
1278         if (info->rti_ifp == NULL && ifpaddr != NULL &&
1279             ifpaddr->sa_family == AF_LINK &&
1280             (ifa = ifa_ifwithnet(ifpaddr, 0, fibnum)) != NULL) {
1281                 info->rti_ifp = ifa->ifa_ifp;
1282                 ifa_free(ifa);
1283         }
1284         if (info->rti_ifa == NULL && ifaaddr != NULL)
1285                 info->rti_ifa = ifa_ifwithaddr(ifaaddr);
1286         if (info->rti_ifa == NULL) {
1287                 struct sockaddr *sa;
1288
1289                 sa = ifaaddr != NULL ? ifaaddr :
1290                     (gateway != NULL ? gateway : dst);
1291                 if (sa != NULL && info->rti_ifp != NULL)
1292                         info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
1293                 else if (dst != NULL && gateway != NULL)
1294                         info->rti_ifa = ifa_ifwithroute(flags, dst, gateway,
1295                                                         fibnum);
1296                 else if (sa != NULL)
1297                         info->rti_ifa = ifa_ifwithroute(flags, sa, sa,
1298                                                         fibnum);
1299         }
1300         if ((ifa = info->rti_ifa) != NULL) {
1301                 if (info->rti_ifp == NULL)
1302                         info->rti_ifp = ifa->ifa_ifp;
1303         } else
1304                 error = ENETUNREACH;
1305         return (error);
1306 }
1307
1308 static int
1309 if_updatemtu_cb(struct radix_node *rn, void *arg)
1310 {
1311         struct rtentry *rt;
1312         struct if_mtuinfo *ifmtu;
1313
1314         rt = (struct rtentry *)rn;
1315         ifmtu = (struct if_mtuinfo *)arg;
1316
1317         if (rt->rt_ifp != ifmtu->ifp)
1318                 return (0);
1319
1320         if (rt->rt_mtu >= ifmtu->mtu) {
1321                 /* We have to decrease mtu regardless of flags */
1322                 rt->rt_mtu = ifmtu->mtu;
1323                 return (0);
1324         }
1325
1326         /*
1327          * New MTU is bigger. Check if are allowed to alter it
1328          */
1329         if ((rt->rt_flags & (RTF_FIXEDMTU | RTF_GATEWAY | RTF_HOST)) != 0) {
1330
1331                 /*
1332                  * Skip routes with user-supplied MTU and
1333                  * non-interface routes
1334                  */
1335                 return (0);
1336         }
1337
1338         /* We are safe to update route MTU */
1339         rt->rt_mtu = ifmtu->mtu;
1340
1341         return (0);
1342 }
1343
1344 void
1345 rt_updatemtu(struct ifnet *ifp)
1346 {
1347         struct if_mtuinfo ifmtu;
1348         struct rib_head *rnh;
1349         int i, j;
1350
1351         ifmtu.ifp = ifp;
1352
1353         /*
1354          * Try to update rt_mtu for all routes using this interface
1355          * Unfortunately the only way to do this is to traverse all
1356          * routing tables in all fibs/domains.
1357          */
1358         for (i = 1; i <= AF_MAX; i++) {
1359                 ifmtu.mtu = if_getmtu_family(ifp, i);
1360                 for (j = 0; j < rt_numfibs; j++) {
1361                         rnh = rt_tables_get_rnh(j, i);
1362                         if (rnh == NULL)
1363                                 continue;
1364                         RIB_WLOCK(rnh);
1365                         rnh->rnh_walktree(&rnh->head, if_updatemtu_cb, &ifmtu);
1366                         RIB_WUNLOCK(rnh);
1367                 }
1368         }
1369 }
1370
1371
1372 #if 0
1373 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
1374 int rt_print(char *buf, int buflen, struct rtentry *rt);
1375
1376 int
1377 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
1378 {
1379         void *paddr = NULL;
1380
1381         switch (s->sa_family) {
1382         case AF_INET:
1383                 paddr = &((struct sockaddr_in *)s)->sin_addr;
1384                 break;
1385         case AF_INET6:
1386                 paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
1387                 break;
1388         }
1389
1390         if (paddr == NULL)
1391                 return (0);
1392
1393         if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
1394                 return (0);
1395         
1396         return (strlen(buf));
1397 }
1398
1399 int
1400 rt_print(char *buf, int buflen, struct rtentry *rt)
1401 {
1402         struct sockaddr *addr, *mask;
1403         int i = 0;
1404
1405         addr = rt_key(rt);
1406         mask = rt_mask(rt);
1407
1408         i = p_sockaddr(buf, buflen, addr);
1409         if (!(rt->rt_flags & RTF_HOST)) {
1410                 buf[i++] = '/';
1411                 i += p_sockaddr(buf + i, buflen - i, mask);
1412         }
1413
1414         if (rt->rt_flags & RTF_GATEWAY) {
1415                 buf[i++] = '>';
1416                 i += p_sockaddr(buf + i, buflen - i, rt->rt_gateway);
1417         }
1418
1419         return (i);
1420 }
1421 #endif
1422
1423 #ifdef RADIX_MPATH
1424 /*
1425  * Deletes key for single-path routes, unlinks rtentry with
1426  * gateway specified in @info from multi-path routes.
1427  *
1428  * Returnes unlinked entry. In case of failure, returns NULL
1429  * and sets @perror to ESRCH.
1430  */
1431 static struct radix_node *
1432 rt_mpath_unlink(struct rib_head *rnh, struct rt_addrinfo *info,
1433     struct rtentry *rto, int *perror)
1434 {
1435         /*
1436          * if we got multipath routes, we require users to specify
1437          * a matching RTAX_GATEWAY.
1438          */
1439         struct rtentry *rt; // *rto = NULL;
1440         struct radix_node *rn;
1441         struct sockaddr *gw;
1442
1443         gw = info->rti_info[RTAX_GATEWAY];
1444         rt = rt_mpath_matchgate(rto, gw);
1445         if (rt == NULL) {
1446                 *perror = ESRCH;
1447                 return (NULL);
1448         }
1449
1450         /*
1451          * this is the first entry in the chain
1452          */
1453         if (rto == rt) {
1454                 rn = rn_mpath_next((struct radix_node *)rt);
1455                 /*
1456                  * there is another entry, now it's active
1457                  */
1458                 if (rn) {
1459                         rto = RNTORT(rn);
1460                         RT_LOCK(rto);
1461                         rto->rt_flags |= RTF_UP;
1462                         RT_UNLOCK(rto);
1463                 } else if (rt->rt_flags & RTF_GATEWAY) {
1464                         /*
1465                          * For gateway routes, we need to 
1466                          * make sure that we we are deleting
1467                          * the correct gateway. 
1468                          * rt_mpath_matchgate() does not 
1469                          * check the case when there is only
1470                          * one route in the chain.  
1471                          */
1472                         if (gw &&
1473                             (rt->rt_gateway->sa_len != gw->sa_len ||
1474                                 memcmp(rt->rt_gateway, gw, gw->sa_len))) {
1475                                 *perror = ESRCH;
1476                                 return (NULL);
1477                         }
1478                 }
1479
1480                 /*
1481                  * use the normal delete code to remove
1482                  * the first entry
1483                  */
1484                 rn = rnh->rnh_deladdr(dst, netmask, &rnh->head);
1485                 *perror = 0;
1486                 return (rn);
1487         }
1488                 
1489         /*
1490          * if the entry is 2nd and on up
1491          */
1492         if (rt_mpath_deldup(rto, rt) == 0)
1493                 panic ("rtrequest1: rt_mpath_deldup");
1494         *perror = 0;
1495         rn = (struct radix_node *)rt;
1496         return (rn);
1497 }
1498 #endif
1499
1500 #ifdef FLOWTABLE
1501 static struct rtentry *
1502 rt_flowtable_check_route(struct rib_head *rnh, struct rt_addrinfo *info)
1503 {
1504 #if defined(INET6) || defined(INET)
1505         struct radix_node *rn;
1506 #endif
1507         struct rtentry *rt0;
1508
1509         rt0 = NULL;
1510         /* "flow-table" only supports IPv6 and IPv4 at the moment. */
1511         switch (dst->sa_family) {
1512 #ifdef INET6
1513         case AF_INET6:
1514 #endif
1515 #ifdef INET
1516         case AF_INET:
1517 #endif
1518 #if defined(INET6) || defined(INET)
1519                 rn = rnh->rnh_matchaddr(dst, &rnh->head);
1520                 if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
1521                         struct sockaddr *mask;
1522                         u_char *m, *n;
1523                         int len;
1524
1525                         /*
1526                          * compare mask to see if the new route is
1527                          * more specific than the existing one
1528                          */
1529                         rt0 = RNTORT(rn);
1530                         RT_LOCK(rt0);
1531                         RT_ADDREF(rt0);
1532                         RT_UNLOCK(rt0);
1533                         /*
1534                          * A host route is already present, so
1535                          * leave the flow-table entries as is.
1536                          */
1537                         if (rt0->rt_flags & RTF_HOST) {
1538                                 RTFREE(rt0);
1539                                 rt0 = NULL;
1540                         } else if (!(flags & RTF_HOST) && netmask) {
1541                                 mask = rt_mask(rt0);
1542                                 len = mask->sa_len;
1543                                 m = (u_char *)mask;
1544                                 n = (u_char *)netmask;
1545                                 while (len-- > 0) {
1546                                         if (*n != *m)
1547                                                 break;
1548                                         n++;
1549                                         m++;
1550                                 }
1551                                 if (len == 0 || (*n < *m)) {
1552                                         RTFREE(rt0);
1553                                         rt0 = NULL;
1554                                 }
1555                         }
1556                 }
1557 #endif/* INET6 || INET */
1558         }
1559
1560         return (rt0);
1561 }
1562 #endif
1563
1564 int
1565 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1566                                 u_int fibnum)
1567 {
1568         int error = 0;
1569         struct rtentry *rt, *rt_old;
1570 #ifdef FLOWTABLE
1571         struct rtentry *rt0;
1572 #endif
1573         struct radix_node *rn;
1574         struct rib_head *rnh;
1575         struct ifaddr *ifa;
1576         struct sockaddr *ndst;
1577         struct sockaddr_storage mdst;
1578
1579         KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1580         KASSERT((flags & RTF_RNH_LOCKED) == 0, ("rtrequest1_fib: locked"));
1581         switch (dst->sa_family) {
1582         case AF_INET6:
1583         case AF_INET:
1584                 /* We support multiple FIBs. */
1585                 break;
1586         default:
1587                 fibnum = RT_DEFAULT_FIB;
1588                 break;
1589         }
1590
1591         /*
1592          * Find the correct routing tree to use for this Address Family
1593          */
1594         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1595         if (rnh == NULL)
1596                 return (EAFNOSUPPORT);
1597
1598         /*
1599          * If we are adding a host route then we don't want to put
1600          * a netmask in the tree, nor do we want to clone it.
1601          */
1602         if (flags & RTF_HOST)
1603                 netmask = NULL;
1604
1605         switch (req) {
1606         case RTM_DELETE:
1607                 if (netmask) {
1608                         rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1609                         dst = (struct sockaddr *)&mdst;
1610                 }
1611
1612                 RIB_WLOCK(rnh);
1613                 rt = rt_unlinkrte(rnh, info, &error);
1614                 RIB_WUNLOCK(rnh);
1615                 if (error != 0)
1616                         return (error);
1617
1618                 rt_notifydelete(rt, info);
1619
1620                 /*
1621                  * If the caller wants it, then it can have it,
1622                  * but it's up to it to free the rtentry as we won't be
1623                  * doing it.
1624                  */
1625                 if (ret_nrt) {
1626                         *ret_nrt = rt;
1627                         RT_UNLOCK(rt);
1628                 } else
1629                         RTFREE_LOCKED(rt);
1630                 break;
1631         case RTM_RESOLVE:
1632                 /*
1633                  * resolve was only used for route cloning
1634                  * here for compat
1635                  */
1636                 break;
1637         case RTM_ADD:
1638                 if ((flags & RTF_GATEWAY) && !gateway)
1639                         return (EINVAL);
1640                 if (dst && gateway && (dst->sa_family != gateway->sa_family) && 
1641                     (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1642                         return (EINVAL);
1643
1644                 if (info->rti_ifa == NULL) {
1645                         error = rt_getifa_fib(info, fibnum);
1646                         if (error)
1647                                 return (error);
1648                 } else
1649                         ifa_ref(info->rti_ifa);
1650                 ifa = info->rti_ifa;
1651                 rt = uma_zalloc(V_rtzone, M_NOWAIT);
1652                 if (rt == NULL) {
1653                         ifa_free(ifa);
1654                         return (ENOBUFS);
1655                 }
1656                 rt->rt_flags = RTF_UP | flags;
1657                 rt->rt_fibnum = fibnum;
1658                 /*
1659                  * Add the gateway. Possibly re-malloc-ing the storage for it.
1660                  */
1661                 if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1662                         ifa_free(ifa);
1663                         uma_zfree(V_rtzone, rt);
1664                         return (error);
1665                 }
1666
1667                 /*
1668                  * point to the (possibly newly malloc'd) dest address.
1669                  */
1670                 ndst = (struct sockaddr *)rt_key(rt);
1671
1672                 /*
1673                  * make sure it contains the value we want (masked if needed).
1674                  */
1675                 if (netmask) {
1676                         rt_maskedcopy(dst, ndst, netmask);
1677                 } else
1678                         bcopy(dst, ndst, dst->sa_len);
1679
1680                 /*
1681                  * We use the ifa reference returned by rt_getifa_fib().
1682                  * This moved from below so that rnh->rnh_addaddr() can
1683                  * examine the ifa and  ifa->ifa_ifp if it so desires.
1684                  */
1685                 rt->rt_ifa = ifa;
1686                 rt->rt_ifp = ifa->ifa_ifp;
1687                 rt->rt_weight = 1;
1688
1689                 rt_setmetrics(info, rt);
1690
1691                 RIB_WLOCK(rnh);
1692                 RT_LOCK(rt);
1693 #ifdef RADIX_MPATH
1694                 /* do not permit exactly the same dst/mask/gw pair */
1695                 if (rt_mpath_capable(rnh) &&
1696                         rt_mpath_conflict(rnh, rt, netmask)) {
1697                         RIB_WUNLOCK(rnh);
1698
1699                         ifa_free(rt->rt_ifa);
1700                         R_Free(rt_key(rt));
1701                         uma_zfree(V_rtzone, rt);
1702                         return (EEXIST);
1703                 }
1704 #endif
1705
1706 #ifdef FLOWTABLE
1707                 rt0 = rt_flowtable_check_route(rnh, info);
1708 #endif /* FLOWTABLE */
1709
1710                 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1711                 rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head, rt->rt_nodes);
1712
1713                 rt_old = NULL;
1714                 if (rn == NULL && (info->rti_flags & RTF_PINNED) != 0) {
1715
1716                         /*
1717                          * Force removal and re-try addition
1718                          * TODO: better multipath&pinned support
1719                          */
1720                         struct sockaddr *info_dst = info->rti_info[RTAX_DST];
1721                         info->rti_info[RTAX_DST] = ndst;
1722                         /* Do not delete existing PINNED(interface) routes */
1723                         info->rti_flags &= ~RTF_PINNED;
1724                         rt_old = rt_unlinkrte(rnh, info, &error);
1725                         info->rti_flags |= RTF_PINNED;
1726                         info->rti_info[RTAX_DST] = info_dst;
1727                         if (rt_old != NULL)
1728                                 rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head,
1729                                     rt->rt_nodes);
1730                 }
1731                 RIB_WUNLOCK(rnh);
1732
1733                 if (rt_old != NULL)
1734                         RT_UNLOCK(rt_old);
1735
1736                 /*
1737                  * If it still failed to go into the tree,
1738                  * then un-make it (this should be a function)
1739                  */
1740                 if (rn == NULL) {
1741                         ifa_free(rt->rt_ifa);
1742                         R_Free(rt_key(rt));
1743                         uma_zfree(V_rtzone, rt);
1744 #ifdef FLOWTABLE
1745                         if (rt0 != NULL)
1746                                 RTFREE(rt0);
1747 #endif
1748                         return (EEXIST);
1749                 } 
1750 #ifdef FLOWTABLE
1751                 else if (rt0 != NULL) {
1752                         flowtable_route_flush(dst->sa_family, rt0);
1753                         RTFREE(rt0);
1754                 }
1755 #endif
1756
1757                 if (rt_old != NULL) {
1758                         rt_notifydelete(rt_old, info);
1759                         RTFREE(rt_old);
1760                 }
1761
1762                 /*
1763                  * If this protocol has something to add to this then
1764                  * allow it to do that as well.
1765                  */
1766                 if (ifa->ifa_rtrequest)
1767                         ifa->ifa_rtrequest(req, rt, info);
1768
1769                 /*
1770                  * actually return a resultant rtentry and
1771                  * give the caller a single reference.
1772                  */
1773                 if (ret_nrt) {
1774                         *ret_nrt = rt;
1775                         RT_ADDREF(rt);
1776                 }
1777                 rnh->rnh_gen++;         /* Routing table updated */
1778                 RT_UNLOCK(rt);
1779                 break;
1780         case RTM_CHANGE:
1781                 RIB_WLOCK(rnh);
1782                 error = rtrequest1_fib_change(rnh, info, ret_nrt, fibnum);
1783                 RIB_WUNLOCK(rnh);
1784                 break;
1785         default:
1786                 error = EOPNOTSUPP;
1787         }
1788
1789         return (error);
1790 }
1791
1792 #undef dst
1793 #undef gateway
1794 #undef netmask
1795 #undef ifaaddr
1796 #undef ifpaddr
1797 #undef flags
1798
1799 static int
1800 rtrequest1_fib_change(struct rib_head *rnh, struct rt_addrinfo *info,
1801     struct rtentry **ret_nrt, u_int fibnum)
1802 {
1803         struct rtentry *rt = NULL;
1804         int error = 0;
1805         int free_ifa = 0;
1806         int family, mtu;
1807         struct if_mtuinfo ifmtu;
1808
1809         rt = (struct rtentry *)rnh->rnh_lookup(info->rti_info[RTAX_DST],
1810             info->rti_info[RTAX_NETMASK], &rnh->head);
1811
1812         if (rt == NULL)
1813                 return (ESRCH);
1814
1815 #ifdef RADIX_MPATH
1816         /*
1817          * If we got multipath routes,
1818          * we require users to specify a matching RTAX_GATEWAY.
1819          */
1820         if (rt_mpath_capable(rnh)) {
1821                 rt = rt_mpath_matchgate(rt, info->rti_info[RTAX_GATEWAY]);
1822                 if (rt == NULL)
1823                         return (ESRCH);
1824         }
1825 #endif
1826
1827         RT_LOCK(rt);
1828
1829         rt_setmetrics(info, rt);
1830
1831         /*
1832          * New gateway could require new ifaddr, ifp;
1833          * flags may also be different; ifp may be specified
1834          * by ll sockaddr when protocol address is ambiguous
1835          */
1836         if (((rt->rt_flags & RTF_GATEWAY) &&
1837             info->rti_info[RTAX_GATEWAY] != NULL) ||
1838             info->rti_info[RTAX_IFP] != NULL ||
1839             (info->rti_info[RTAX_IFA] != NULL &&
1840              !sa_equal(info->rti_info[RTAX_IFA], rt->rt_ifa->ifa_addr))) {
1841
1842                 error = rt_getifa_fib(info, fibnum);
1843                 if (info->rti_ifa != NULL)
1844                         free_ifa = 1;
1845
1846                 if (error != 0)
1847                         goto bad;
1848         }
1849
1850         /* Check if outgoing interface has changed */
1851         if (info->rti_ifa != NULL && info->rti_ifa != rt->rt_ifa &&
1852             rt->rt_ifa != NULL && rt->rt_ifa->ifa_rtrequest != NULL) {
1853                 rt->rt_ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1854                 ifa_free(rt->rt_ifa);
1855         }
1856         /* Update gateway address */
1857         if (info->rti_info[RTAX_GATEWAY] != NULL) {
1858                 error = rt_setgate(rt, rt_key(rt), info->rti_info[RTAX_GATEWAY]);
1859                 if (error != 0)
1860                         goto bad;
1861
1862                 rt->rt_flags &= ~RTF_GATEWAY;
1863                 rt->rt_flags |= (RTF_GATEWAY & info->rti_flags);
1864         }
1865
1866         if (info->rti_ifa != NULL && info->rti_ifa != rt->rt_ifa) {
1867                 ifa_ref(info->rti_ifa);
1868                 rt->rt_ifa = info->rti_ifa;
1869                 rt->rt_ifp = info->rti_ifp;
1870         }
1871         /* Allow some flags to be toggled on change. */
1872         rt->rt_flags &= ~RTF_FMASK;
1873         rt->rt_flags |= info->rti_flags & RTF_FMASK;
1874
1875         if (rt->rt_ifa && rt->rt_ifa->ifa_rtrequest != NULL)
1876                rt->rt_ifa->ifa_rtrequest(RTM_ADD, rt, info);
1877
1878         /* Alter route MTU if necessary */
1879         if (rt->rt_ifp != NULL) {
1880                 family = info->rti_info[RTAX_DST]->sa_family;
1881                 mtu = if_getmtu_family(rt->rt_ifp, family);
1882                 /* Set default MTU */
1883                 if (rt->rt_mtu == 0)
1884                         rt->rt_mtu = mtu;
1885                 if (rt->rt_mtu != mtu) {
1886                         /* Check if we really need to update */
1887                         ifmtu.ifp = rt->rt_ifp;
1888                         ifmtu.mtu = mtu;
1889                         if_updatemtu_cb(rt->rt_nodes, &ifmtu);
1890                 }
1891         }
1892
1893         if (ret_nrt) {
1894                 *ret_nrt = rt;
1895                 RT_ADDREF(rt);
1896         }
1897 bad:
1898         RT_UNLOCK(rt);
1899         if (free_ifa != 0)
1900                 ifa_free(info->rti_ifa);
1901         return (error);
1902 }
1903
1904 static void
1905 rt_setmetrics(const struct rt_addrinfo *info, struct rtentry *rt)
1906 {
1907
1908         if (info->rti_mflags & RTV_MTU) {
1909                 if (info->rti_rmx->rmx_mtu != 0) {
1910
1911                         /*
1912                          * MTU was explicitly provided by user.
1913                          * Keep it.
1914                          */
1915                         rt->rt_flags |= RTF_FIXEDMTU;
1916                 } else {
1917
1918                         /*
1919                          * User explicitly sets MTU to 0.
1920                          * Assume rollback to default.
1921                          */
1922                         rt->rt_flags &= ~RTF_FIXEDMTU;
1923                 }
1924                 rt->rt_mtu = info->rti_rmx->rmx_mtu;
1925         }
1926         if (info->rti_mflags & RTV_WEIGHT)
1927                 rt->rt_weight = info->rti_rmx->rmx_weight;
1928         /* Kernel -> userland timebase conversion. */
1929         if (info->rti_mflags & RTV_EXPIRE)
1930                 rt->rt_expire = info->rti_rmx->rmx_expire ?
1931                     info->rti_rmx->rmx_expire - time_second + time_uptime : 0;
1932 }
1933
1934 int
1935 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1936 {
1937         /* XXX dst may be overwritten, can we move this to below */
1938         int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1939
1940         /*
1941          * Prepare to store the gateway in rt->rt_gateway.
1942          * Both dst and gateway are stored one after the other in the same
1943          * malloc'd chunk. If we have room, we can reuse the old buffer,
1944          * rt_gateway already points to the right place.
1945          * Otherwise, malloc a new block and update the 'dst' address.
1946          */
1947         if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1948                 caddr_t new;
1949
1950                 R_Malloc(new, caddr_t, dlen + glen);
1951                 if (new == NULL)
1952                         return ENOBUFS;
1953                 /*
1954                  * XXX note, we copy from *dst and not *rt_key(rt) because
1955                  * rt_setgate() can be called to initialize a newly
1956                  * allocated route entry, in which case rt_key(rt) == NULL
1957                  * (and also rt->rt_gateway == NULL).
1958                  * Free()/free() handle a NULL argument just fine.
1959                  */
1960                 bcopy(dst, new, dlen);
1961                 R_Free(rt_key(rt));     /* free old block, if any */
1962                 rt_key(rt) = (struct sockaddr *)new;
1963                 rt->rt_gateway = (struct sockaddr *)(new + dlen);
1964         }
1965
1966         /*
1967          * Copy the new gateway value into the memory chunk.
1968          */
1969         bcopy(gate, rt->rt_gateway, glen);
1970
1971         return (0);
1972 }
1973
1974 void
1975 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1976 {
1977         u_char *cp1 = (u_char *)src;
1978         u_char *cp2 = (u_char *)dst;
1979         u_char *cp3 = (u_char *)netmask;
1980         u_char *cplim = cp2 + *cp3;
1981         u_char *cplim2 = cp2 + *cp1;
1982
1983         *cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1984         cp3 += 2;
1985         if (cplim > cplim2)
1986                 cplim = cplim2;
1987         while (cp2 < cplim)
1988                 *cp2++ = *cp1++ & *cp3++;
1989         if (cp2 < cplim2)
1990                 bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1991 }
1992
1993 /*
1994  * Set up a routing table entry, normally
1995  * for an interface.
1996  */
1997 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1998 static inline  int
1999 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
2000 {
2001         struct sockaddr *dst;
2002         struct sockaddr *netmask;
2003         struct rtentry *rt = NULL;
2004         struct rt_addrinfo info;
2005         int error = 0;
2006         int startfib, endfib;
2007         char tempbuf[_SOCKADDR_TMPSIZE];
2008         int didwork = 0;
2009         int a_failure = 0;
2010         static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
2011         struct rib_head *rnh;
2012
2013         if (flags & RTF_HOST) {
2014                 dst = ifa->ifa_dstaddr;
2015                 netmask = NULL;
2016         } else {
2017                 dst = ifa->ifa_addr;
2018                 netmask = ifa->ifa_netmask;
2019         }
2020         if (dst->sa_len == 0)
2021                 return(EINVAL);
2022         switch (dst->sa_family) {
2023         case AF_INET6:
2024         case AF_INET:
2025                 /* We support multiple FIBs. */
2026                 break;
2027         default:
2028                 fibnum = RT_DEFAULT_FIB;
2029                 break;
2030         }
2031         if (fibnum == RT_ALL_FIBS) {
2032                 if (V_rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD)
2033                         startfib = endfib = ifa->ifa_ifp->if_fib;
2034                 else {
2035                         startfib = 0;
2036                         endfib = rt_numfibs - 1;
2037                 }
2038         } else {
2039                 KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
2040                 startfib = fibnum;
2041                 endfib = fibnum;
2042         }
2043
2044         /*
2045          * If it's a delete, check that if it exists,
2046          * it's on the correct interface or we might scrub
2047          * a route to another ifa which would
2048          * be confusing at best and possibly worse.
2049          */
2050         if (cmd == RTM_DELETE) {
2051                 /*
2052                  * It's a delete, so it should already exist..
2053                  * If it's a net, mask off the host bits
2054                  * (Assuming we have a mask)
2055                  * XXX this is kinda inet specific..
2056                  */
2057                 if (netmask != NULL) {
2058                         rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
2059                         dst = (struct sockaddr *)tempbuf;
2060                 }
2061         }
2062         /*
2063          * Now go through all the requested tables (fibs) and do the
2064          * requested action. Realistically, this will either be fib 0
2065          * for protocols that don't do multiple tables or all the
2066          * tables for those that do.
2067          */
2068         for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
2069                 if (cmd == RTM_DELETE) {
2070                         struct radix_node *rn;
2071                         /*
2072                          * Look up an rtentry that is in the routing tree and
2073                          * contains the correct info.
2074                          */
2075                         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
2076                         if (rnh == NULL)
2077                                 /* this table doesn't exist but others might */
2078                                 continue;
2079                         RIB_RLOCK(rnh);
2080                         rn = rnh->rnh_lookup(dst, netmask, &rnh->head);
2081 #ifdef RADIX_MPATH
2082                         if (rt_mpath_capable(rnh)) {
2083
2084                                 if (rn == NULL) 
2085                                         error = ESRCH;
2086                                 else {
2087                                         rt = RNTORT(rn);
2088                                         /*
2089                                          * for interface route the
2090                                          * rt->rt_gateway is sockaddr_intf
2091                                          * for cloning ARP entries, so
2092                                          * rt_mpath_matchgate must use the
2093                                          * interface address
2094                                          */
2095                                         rt = rt_mpath_matchgate(rt,
2096                                             ifa->ifa_addr);
2097                                         if (rt == NULL) 
2098                                                 error = ESRCH;
2099                                 }
2100                         }
2101 #endif
2102                         error = (rn == NULL ||
2103                             (rn->rn_flags & RNF_ROOT) ||
2104                             RNTORT(rn)->rt_ifa != ifa);
2105                         RIB_RUNLOCK(rnh);
2106                         if (error) {
2107                                 /* this is only an error if bad on ALL tables */
2108                                 continue;
2109                         }
2110                 }
2111                 /*
2112                  * Do the actual request
2113                  */
2114                 bzero((caddr_t)&info, sizeof(info));
2115                 info.rti_ifa = ifa;
2116                 info.rti_flags = flags |
2117                     (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
2118                 info.rti_info[RTAX_DST] = dst;
2119                 /* 
2120                  * doing this for compatibility reasons
2121                  */
2122                 if (cmd == RTM_ADD)
2123                         info.rti_info[RTAX_GATEWAY] =
2124                             (struct sockaddr *)&null_sdl;
2125                 else
2126                         info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
2127                 info.rti_info[RTAX_NETMASK] = netmask;
2128                 error = rtrequest1_fib(cmd, &info, &rt, fibnum);
2129
2130                 if (error == 0 && rt != NULL) {
2131                         /*
2132                          * notify any listening routing agents of the change
2133                          */
2134                         RT_LOCK(rt);
2135 #ifdef RADIX_MPATH
2136                         /*
2137                          * in case address alias finds the first address
2138                          * e.g. ifconfig bge0 192.0.2.246/24
2139                          * e.g. ifconfig bge0 192.0.2.247/24
2140                          * the address set in the route is 192.0.2.246
2141                          * so we need to replace it with 192.0.2.247
2142                          */
2143                         if (memcmp(rt->rt_ifa->ifa_addr,
2144                             ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
2145                                 ifa_free(rt->rt_ifa);
2146                                 ifa_ref(ifa);
2147                                 rt->rt_ifp = ifa->ifa_ifp;
2148                                 rt->rt_ifa = ifa;
2149                         }
2150 #endif
2151                         /* 
2152                          * doing this for compatibility reasons
2153                          */
2154                         if (cmd == RTM_ADD) {
2155                             ((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
2156                                 rt->rt_ifp->if_type;
2157                             ((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
2158                                 rt->rt_ifp->if_index;
2159                         }
2160                         RT_ADDREF(rt);
2161                         RT_UNLOCK(rt);
2162                         rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
2163                         RT_LOCK(rt);
2164                         RT_REMREF(rt);
2165                         if (cmd == RTM_DELETE) {
2166                                 /*
2167                                  * If we are deleting, and we found an entry,
2168                                  * then it's been removed from the tree..
2169                                  * now throw it away.
2170                                  */
2171                                 RTFREE_LOCKED(rt);
2172                         } else {
2173                                 if (cmd == RTM_ADD) {
2174                                         /*
2175                                          * We just wanted to add it..
2176                                          * we don't actually need a reference.
2177                                          */
2178                                         RT_REMREF(rt);
2179                                 }
2180                                 RT_UNLOCK(rt);
2181                         }
2182                         didwork = 1;
2183                 }
2184                 if (error)
2185                         a_failure = error;
2186         }
2187         if (cmd == RTM_DELETE) {
2188                 if (didwork) {
2189                         error = 0;
2190                 } else {
2191                         /* we only give an error if it wasn't in any table */
2192                         error = ((flags & RTF_HOST) ?
2193                             EHOSTUNREACH : ENETUNREACH);
2194                 }
2195         } else {
2196                 if (a_failure) {
2197                         /* return an error if any of them failed */
2198                         error = a_failure;
2199                 }
2200         }
2201         return (error);
2202 }
2203
2204 /*
2205  * Set up a routing table entry, normally
2206  * for an interface.
2207  */
2208 int
2209 rtinit(struct ifaddr *ifa, int cmd, int flags)
2210 {
2211         struct sockaddr *dst;
2212         int fib = RT_DEFAULT_FIB;
2213
2214         if (flags & RTF_HOST) {
2215                 dst = ifa->ifa_dstaddr;
2216         } else {
2217                 dst = ifa->ifa_addr;
2218         }
2219
2220         switch (dst->sa_family) {
2221         case AF_INET6:
2222         case AF_INET:
2223                 /* We do support multiple FIBs. */
2224                 fib = RT_ALL_FIBS;
2225                 break;
2226         }
2227         return (rtinit1(ifa, cmd, flags, fib));
2228 }
2229
2230 /*
2231  * Announce interface address arrival/withdraw
2232  * Returns 0 on success.
2233  */
2234 int
2235 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
2236 {
2237
2238         KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2239             ("unexpected cmd %d", cmd));
2240         
2241         KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2242             ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2243
2244 #if defined(INET) || defined(INET6)
2245 #ifdef SCTP
2246         /*
2247          * notify the SCTP stack
2248          * this will only get called when an address is added/deleted
2249          * XXX pass the ifaddr struct instead if ifa->ifa_addr...
2250          */
2251         sctp_addr_change(ifa, cmd);
2252 #endif /* SCTP */
2253 #endif
2254         return (rtsock_addrmsg(cmd, ifa, fibnum));
2255 }
2256
2257 /*
2258  * Announce route addition/removal.
2259  * Users of this function MUST validate input data BEFORE calling.
2260  * However we have to be able to handle invalid data:
2261  * if some userland app sends us "invalid" route message (invalid mask,
2262  * no dst, wrong address families, etc...) we need to pass it back
2263  * to app (and any other rtsock consumers) with rtm_errno field set to
2264  * non-zero value.
2265  * Returns 0 on success.
2266  */
2267 int
2268 rt_routemsg(int cmd, struct ifnet *ifp, int error, struct rtentry *rt,
2269     int fibnum)
2270 {
2271
2272         KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2273             ("unexpected cmd %d", cmd));
2274         
2275         KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2276             ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2277
2278         KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
2279
2280         return (rtsock_routemsg(cmd, ifp, error, rt, fibnum));
2281 }
2282
2283 void
2284 rt_newaddrmsg(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt)
2285 {
2286
2287         rt_newaddrmsg_fib(cmd, ifa, error, rt, RT_ALL_FIBS);
2288 }
2289
2290 /*
2291  * This is called to generate messages from the routing socket
2292  * indicating a network interface has had addresses associated with it.
2293  */
2294 void
2295 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt,
2296     int fibnum)
2297 {
2298
2299         KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2300                 ("unexpected cmd %u", cmd));
2301         KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2302             ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2303
2304         if (cmd == RTM_ADD) {
2305                 rt_addrmsg(cmd, ifa, fibnum);
2306                 if (rt != NULL)
2307                         rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
2308         } else {
2309                 if (rt != NULL)
2310                         rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
2311                 rt_addrmsg(cmd, ifa, fibnum);
2312         }
2313 }
2314