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