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