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