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