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