]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/route/route_ctl.c
Add tracking for rib/nhops/nhgrp objects and provide cumulative number accessors.
[FreeBSD/FreeBSD.git] / sys / net / route / route_ctl.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2020 Alexander V. Chernikov
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 #include "opt_inet.h"
31 #include "opt_inet6.h"
32 #include "opt_route.h"
33
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/malloc.h>
37 #include <sys/mbuf.h>
38 #include <sys/socket.h>
39 #include <sys/sysctl.h>
40 #include <sys/syslog.h>
41 #include <sys/kernel.h>
42 #include <sys/lock.h>
43 #include <sys/rmlock.h>
44
45 #include <net/if.h>
46 #include <net/if_var.h>
47 #include <net/if_dl.h>
48 #include <net/vnet.h>
49 #include <net/route.h>
50 #include <net/route/route_ctl.h>
51 #include <net/route/route_var.h>
52 #include <net/route/nhop_utils.h>
53 #include <net/route/nhop.h>
54 #include <net/route/nhop_var.h>
55 #include <netinet/in.h>
56
57 #ifdef RADIX_MPATH
58 #include <net/radix_mpath.h>
59 #endif
60
61 #include <vm/uma.h>
62
63 /*
64  * This file contains control plane routing tables functions.
65  *
66  * All functions assumes they are called in net epoch.
67  */
68
69 struct rib_subscription {
70         CK_STAILQ_ENTRY(rib_subscription)       next;
71         rib_subscription_cb_t                   *func;
72         void                                    *arg;
73         struct rib_head                         *rnh;
74         enum rib_subscription_type              type;
75         struct epoch_context                    epoch_ctx;
76 };
77
78 static int add_route(struct rib_head *rnh, struct rt_addrinfo *info,
79     struct rib_cmd_info *rc);
80 static int add_route_nhop(struct rib_head *rnh, struct rtentry *rt,
81     struct rt_addrinfo *info, struct route_nhop_data *rnd,
82     struct rib_cmd_info *rc);
83 static int del_route(struct rib_head *rnh, struct rt_addrinfo *info,
84     struct rib_cmd_info *rc);
85 static int change_route(struct rib_head *rnh, struct rt_addrinfo *info,
86     struct route_nhop_data *nhd_orig, struct rib_cmd_info *rc);
87
88 static int rt_unlinkrte(struct rib_head *rnh, struct rt_addrinfo *info,
89     struct rib_cmd_info *rc);
90
91 static void rib_notify(struct rib_head *rnh, enum rib_subscription_type type,
92     struct rib_cmd_info *rc);
93
94 static void destroy_subscription_epoch(epoch_context_t ctx);
95 #ifdef ROUTE_MPATH
96 static bool rib_can_multipath(struct rib_head *rh);
97 #endif
98
99 /* Per-vnet multipath routing configuration */
100 SYSCTL_DECL(_net_route);
101 #define V_rib_route_multipath   VNET(rib_route_multipath)
102 #ifdef ROUTE_MPATH
103 #define _MP_FLAGS       CTLFLAG_RW
104 #else
105 #define _MP_FLAGS       CTLFLAG_RD
106 #endif
107 VNET_DEFINE(u_int, rib_route_multipath) = 0;
108 SYSCTL_UINT(_net_route, OID_AUTO, multipath, _MP_FLAGS | CTLFLAG_VNET,
109     &VNET_NAME(rib_route_multipath), 0, "Enable route multipath");
110 #undef _MP_FLAGS
111
112 /* Routing table UMA zone */
113 VNET_DEFINE_STATIC(uma_zone_t, rtzone);
114 #define V_rtzone        VNET(rtzone)
115
116 void
117 vnet_rtzone_init()
118 {
119
120         V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
121                 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
122 }
123
124 #ifdef VIMAGE
125 void
126 vnet_rtzone_destroy()
127 {
128
129         uma_zdestroy(V_rtzone);
130 }
131 #endif
132
133 static void
134 destroy_rtentry(struct rtentry *rt)
135 {
136
137         /*
138          * At this moment rnh, nh_control may be already freed.
139          * nhop interface may have been migrated to a different vnet.
140          * Use vnet stored in the nexthop to delete the entry.
141          */
142         CURVNET_SET(nhop_get_vnet(rt->rt_nhop));
143
144         /* Unreference nexthop */
145         nhop_free_any(rt->rt_nhop);
146
147         uma_zfree(V_rtzone, rt);
148
149         CURVNET_RESTORE();
150 }
151
152 /*
153  * Epoch callback indicating rtentry is safe to destroy
154  */
155 static void
156 destroy_rtentry_epoch(epoch_context_t ctx)
157 {
158         struct rtentry *rt;
159
160         rt = __containerof(ctx, struct rtentry, rt_epoch_ctx);
161
162         destroy_rtentry(rt);
163 }
164
165 /*
166  * Schedule rtentry deletion
167  */
168 static void
169 rtfree(struct rtentry *rt)
170 {
171
172         KASSERT(rt != NULL, ("%s: NULL rt", __func__));
173
174         epoch_call(net_epoch_preempt, destroy_rtentry_epoch,
175             &rt->rt_epoch_ctx);
176 }
177
178 static struct rib_head *
179 get_rnh(uint32_t fibnum, const struct rt_addrinfo *info)
180 {
181         struct rib_head *rnh;
182         struct sockaddr *dst;
183
184         KASSERT((fibnum < rt_numfibs), ("rib_add_route: bad fibnum"));
185
186         dst = info->rti_info[RTAX_DST];
187         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
188
189         return (rnh);
190 }
191
192 #ifdef ROUTE_MPATH
193 static bool
194 rib_can_multipath(struct rib_head *rh)
195 {
196         int result;
197
198         CURVNET_SET(rh->rib_vnet);
199         result = !!V_rib_route_multipath;
200         CURVNET_RESTORE();
201
202         return (result);
203 }
204
205 /*
206  * Check is nhop is multipath-eligible.
207  * Avoid nhops without gateways and redirects.
208  *
209  * Returns 1 for multipath-eligible nexthop,
210  * 0 otherwise.
211  */
212 bool
213 nhop_can_multipath(const struct nhop_object *nh)
214 {
215
216         if ((nh->nh_flags & NHF_MULTIPATH) != 0)
217                 return (1);
218         if ((nh->nh_flags & NHF_GATEWAY) == 0)
219                 return (0);
220         if ((nh->nh_flags & NHF_REDIRECT) != 0)
221                 return (0);
222
223         return (1);
224 }
225 #endif
226
227 static int
228 get_info_weight(const struct rt_addrinfo *info, uint32_t default_weight)
229 {
230         uint32_t weight;
231
232         if (info->rti_mflags & RTV_WEIGHT)
233                 weight = info->rti_rmx->rmx_weight;
234         else
235                 weight = default_weight;
236         /* Keep upper 1 byte for adm distance purposes */
237         if (weight > RT_MAX_WEIGHT)
238                 weight = RT_MAX_WEIGHT;
239
240         return (weight);
241 }
242
243 static void
244 rt_set_expire_info(struct rtentry *rt, const struct rt_addrinfo *info)
245 {
246
247         /* Kernel -> userland timebase conversion. */
248         if (info->rti_mflags & RTV_EXPIRE)
249                 rt->rt_expire = info->rti_rmx->rmx_expire ?
250                     info->rti_rmx->rmx_expire - time_second + time_uptime : 0;
251 }
252
253 /*
254  * Check if specified @gw matches gw data in the nexthop @nh.
255  *
256  * Returns true if matches, false otherwise.
257  */
258 bool
259 match_nhop_gw(const struct nhop_object *nh, const struct sockaddr *gw)
260 {
261
262         if (nh->gw_sa.sa_family != gw->sa_family)
263                 return (false);
264
265         switch (gw->sa_family) {
266         case AF_INET:
267                 return (nh->gw4_sa.sin_addr.s_addr ==
268                     ((const struct sockaddr_in *)gw)->sin_addr.s_addr);
269         case AF_INET6:
270                 {
271                         const struct sockaddr_in6 *gw6;
272                         gw6 = (const struct sockaddr_in6 *)gw;
273
274                         /*
275                          * Currently (2020-09) IPv6 gws in kernel have their
276                          * scope embedded. Once this becomes false, this code
277                          * has to be revisited.
278                          */
279                         if (IN6_ARE_ADDR_EQUAL(&nh->gw6_sa.sin6_addr,
280                             &gw6->sin6_addr))
281                                 return (true);
282                         return (false);
283                 }
284         case AF_LINK:
285                 {
286                         const struct sockaddr_dl *sdl;
287                         sdl = (const struct sockaddr_dl *)gw;
288                         return (nh->gwl_sa.sdl_index == sdl->sdl_index);
289                 }
290         default:
291                 return (memcmp(&nh->gw_sa, gw, nh->gw_sa.sa_len) == 0);
292         }
293
294         /* NOTREACHED */
295         return (false);
296 }
297
298 /*
299  * Checks if data in @info matches nexhop @nh.
300  *
301  * Returns 0 on success,
302  * ESRCH if not matched,
303  * ENOENT if filter function returned false
304  */
305 int
306 check_info_match_nhop(const struct rt_addrinfo *info, const struct rtentry *rt,
307     const struct nhop_object *nh)
308 {
309         const struct sockaddr *gw = info->rti_info[RTAX_GATEWAY];
310
311         if (info->rti_filter != NULL) {
312             if (info->rti_filter(rt, nh, info->rti_filterdata) == 0)
313                     return (ENOENT);
314             else
315                     return (0);
316         }
317         if ((gw != NULL) && !match_nhop_gw(nh, gw))
318                 return (ESRCH);
319
320         return (0);
321 }
322
323 /*
324  * Checks if nexhop @nh can be rewritten by data in @info because
325  *  of higher "priority". Currently the only case for such scenario
326  *  is kernel installing interface routes, marked by RTF_PINNED flag.
327  *
328  * Returns:
329  * 1 if @info data has higher priority
330  * 0 if priority is the same
331  * -1 if priority is lower
332  */
333 int
334 can_override_nhop(const struct rt_addrinfo *info, const struct nhop_object *nh)
335 {
336
337         if (info->rti_flags & RTF_PINNED) {
338                 return (NH_IS_PINNED(nh)) ? 0 : 1;
339         } else {
340                 return (NH_IS_PINNED(nh)) ? -1 : 0;
341         }
342 }
343
344 /*
345  * Runs exact prefix match based on @dst and @netmask.
346  * Returns matched @rtentry if found or NULL.
347  * If rtentry was found, saves nexthop / weight value into @rnd.
348  */
349 static struct rtentry *
350 lookup_prefix_bysa(struct rib_head *rnh, const struct sockaddr *dst,
351     const struct sockaddr *netmask, struct route_nhop_data *rnd)
352 {
353         struct rtentry *rt;
354
355         RIB_LOCK_ASSERT(rnh);
356
357         rt = (struct rtentry *)rnh->rnh_lookup(__DECONST(void *, dst),
358             __DECONST(void *, netmask), &rnh->head);
359         if (rt != NULL) {
360                 rnd->rnd_nhop = rt->rt_nhop;
361                 rnd->rnd_weight = rt->rt_weight;
362         } else {
363                 rnd->rnd_nhop = NULL;
364                 rnd->rnd_weight = 0;
365         }
366
367         return (rt);
368 }
369
370 /*
371  * Runs exact prefix match based on dst/netmask from @info.
372  * Assumes RIB lock is held.
373  * Returns matched @rtentry if found or NULL.
374  * If rtentry was found, saves nexthop / weight value into @rnd.
375  */
376 struct rtentry *
377 lookup_prefix(struct rib_head *rnh, const struct rt_addrinfo *info,
378     struct route_nhop_data *rnd)
379 {
380         struct rtentry *rt;
381
382         rt = lookup_prefix_bysa(rnh, info->rti_info[RTAX_DST],
383             info->rti_info[RTAX_NETMASK], rnd);
384
385         return (rt);
386 }
387
388 /*
389  * Adds route defined by @info into the kernel table specified by @fibnum and
390  * sa_family in @info->rti_info[RTAX_DST].
391  *
392  * Returns 0 on success and fills in operation metadata into @rc.
393  */
394 int
395 rib_add_route(uint32_t fibnum, struct rt_addrinfo *info,
396     struct rib_cmd_info *rc)
397 {
398         struct rib_head *rnh;
399         int error;
400
401         NET_EPOCH_ASSERT();
402
403         rnh = get_rnh(fibnum, info);
404         if (rnh == NULL)
405                 return (EAFNOSUPPORT);
406
407         /*
408          * Check consistency between RTF_HOST flag and netmask
409          * existence.
410          */
411         if (info->rti_flags & RTF_HOST)
412                 info->rti_info[RTAX_NETMASK] = NULL;
413         else if (info->rti_info[RTAX_NETMASK] == NULL)
414                 return (EINVAL);
415
416         bzero(rc, sizeof(struct rib_cmd_info));
417         rc->rc_cmd = RTM_ADD;
418
419         error = add_route(rnh, info, rc);
420         if (error == 0)
421                 rib_notify(rnh, RIB_NOTIFY_DELAYED, rc);
422
423         return (error);
424 }
425
426 /*
427  * Creates rtentry and nexthop based on @info data.
428  * Return 0 and fills in rtentry into @prt on success,
429  * return errno otherwise.
430  */
431 static int
432 create_rtentry(struct rib_head *rnh, struct rt_addrinfo *info,
433     struct rtentry **prt)
434 {
435         struct sockaddr *dst, *ndst, *gateway, *netmask;
436         struct rtentry *rt;
437         struct nhop_object *nh;
438         struct ifaddr *ifa;
439         int error, flags;
440
441         dst = info->rti_info[RTAX_DST];
442         gateway = info->rti_info[RTAX_GATEWAY];
443         netmask = info->rti_info[RTAX_NETMASK];
444         flags = info->rti_flags;
445
446         if ((flags & RTF_GATEWAY) && !gateway)
447                 return (EINVAL);
448         if (dst && gateway && (dst->sa_family != gateway->sa_family) && 
449             (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
450                 return (EINVAL);
451
452         if (dst->sa_len > sizeof(((struct rtentry *)NULL)->rt_dstb))
453                 return (EINVAL);
454
455         if (info->rti_ifa == NULL) {
456                 error = rt_getifa_fib(info, rnh->rib_fibnum);
457                 if (error)
458                         return (error);
459         } else {
460                 ifa_ref(info->rti_ifa);
461         }
462
463         error = nhop_create_from_info(rnh, info, &nh);
464         if (error != 0) {
465                 ifa_free(info->rti_ifa);
466                 return (error);
467         }
468
469         rt = uma_zalloc(V_rtzone, M_NOWAIT | M_ZERO);
470         if (rt == NULL) {
471                 ifa_free(info->rti_ifa);
472                 nhop_free(nh);
473                 return (ENOBUFS);
474         }
475         rt->rte_flags = (RTF_UP | flags) & RTE_RT_FLAG_MASK;
476         rt->rt_nhop = nh;
477
478         /* Fill in dst */
479         memcpy(&rt->rt_dst, dst, dst->sa_len);
480         rt_key(rt) = &rt->rt_dst;
481
482         /*
483          * point to the (possibly newly malloc'd) dest address.
484          */
485         ndst = (struct sockaddr *)rt_key(rt);
486
487         /*
488          * make sure it contains the value we want (masked if needed).
489          */
490         if (netmask) {
491                 rt_maskedcopy(dst, ndst, netmask);
492         } else
493                 bcopy(dst, ndst, dst->sa_len);
494
495         /*
496          * We use the ifa reference returned by rt_getifa_fib().
497          * This moved from below so that rnh->rnh_addaddr() can
498          * examine the ifa and  ifa->ifa_ifp if it so desires.
499          */
500         ifa = info->rti_ifa;
501         rt->rt_weight = get_info_weight(info, RT_DEFAULT_WEIGHT);
502         rt_set_expire_info(rt, info);
503
504         *prt = rt;
505         return (0);
506 }
507
508 static int
509 add_route(struct rib_head *rnh, struct rt_addrinfo *info,
510     struct rib_cmd_info *rc)
511 {
512         struct nhop_object *nh_orig;
513         struct route_nhop_data rnd_orig, rnd_add;
514         struct nhop_object *nh;
515         struct rtentry *rt, *rt_orig;
516         int error;
517
518         error = create_rtentry(rnh, info, &rt);
519         if (error != 0)
520                 return (error);
521
522         rnd_add.rnd_nhop = rt->rt_nhop;
523         rnd_add.rnd_weight = rt->rt_weight;
524         nh = rt->rt_nhop;
525
526         RIB_WLOCK(rnh);
527         error = add_route_nhop(rnh, rt, info, &rnd_add, rc);
528         if (error == 0) {
529                 RIB_WUNLOCK(rnh);
530                 return (0);
531         }
532
533         /* addition failed. Lookup prefix in the rib to determine the cause */
534         rt_orig = lookup_prefix(rnh, info, &rnd_orig);
535         if (rt_orig == NULL) {
536                 /* No prefix -> rnh_addaddr() failed to allocate memory */
537                 RIB_WUNLOCK(rnh);
538                 nhop_free(nh);
539                 uma_zfree(V_rtzone, rt);
540                 return (ENOMEM);
541         }
542
543         /* We have existing route in the RIB. */
544         nh_orig = rnd_orig.rnd_nhop;
545         /* Check if new route has higher preference */
546         if (can_override_nhop(info, nh_orig) > 0) {
547                 /* Update nexthop to the new route */
548                 change_route_nhop(rnh, rt_orig, info, &rnd_add, rc);
549                 RIB_WUNLOCK(rnh);
550                 uma_zfree(V_rtzone, rt);
551                 nhop_free(nh_orig);
552                 return (0);
553         }
554
555         RIB_WUNLOCK(rnh);
556
557 #ifdef ROUTE_MPATH
558         if (rib_can_multipath(rnh) && nhop_can_multipath(rnd_add.rnd_nhop) &&
559             nhop_can_multipath(rnd_orig.rnd_nhop))
560                 error = add_route_mpath(rnh, info, rt, &rnd_add, &rnd_orig, rc);
561         else
562 #endif
563         /* Unable to add - another route with the same preference exists */
564         error = EEXIST;
565
566         /*
567          * ROUTE_MPATH disabled: failed to add route, free both nhop and rt.
568          * ROUTE_MPATH enabled: original nhop reference is unused in any case,
569          *  free rt only if not _adding_ new route to rib (e.g. the case
570          *  when initial lookup returned existing route, but then it got
571          *  deleted prior to multipath group insertion, leading to a simple
572          *  non-multipath add as a result).
573          */
574         nhop_free(nh);
575         if ((error != 0) || rc->rc_cmd != RTM_ADD)
576                 uma_zfree(V_rtzone, rt);
577
578         return (error);
579 }
580
581 /*
582  * Removes route defined by @info from the kernel table specified by @fibnum and
583  * sa_family in @info->rti_info[RTAX_DST].
584  *
585  * Returns 0 on success and fills in operation metadata into @rc.
586  */
587 int
588 rib_del_route(uint32_t fibnum, struct rt_addrinfo *info, struct rib_cmd_info *rc)
589 {
590         struct rib_head *rnh;
591         struct sockaddr *dst_orig, *netmask;
592         struct sockaddr_storage mdst;
593         int error;
594
595         NET_EPOCH_ASSERT();
596
597         rnh = get_rnh(fibnum, info);
598         if (rnh == NULL)
599                 return (EAFNOSUPPORT);
600
601         bzero(rc, sizeof(struct rib_cmd_info));
602         rc->rc_cmd = RTM_DELETE;
603
604         dst_orig = info->rti_info[RTAX_DST];
605         netmask = info->rti_info[RTAX_NETMASK];
606
607         if (netmask != NULL) {
608                 /* Ensure @dst is always properly masked */
609                 if (dst_orig->sa_len > sizeof(mdst))
610                         return (EINVAL);
611                 rt_maskedcopy(dst_orig, (struct sockaddr *)&mdst, netmask);
612                 info->rti_info[RTAX_DST] = (struct sockaddr *)&mdst;
613         }
614         error = del_route(rnh, info, rc);
615         info->rti_info[RTAX_DST] = dst_orig;
616
617         return (error);
618 }
619
620 /*
621  * Conditionally unlinks rtentry matching data inside @info from @rnh.
622  * Returns 0 on success with operation result stored in @rc.
623  * On error, returns:
624  * ESRCH - if prefix was not found,
625  * EADDRINUSE - if trying to delete higher priority route.
626  * ENOENT - if supplied filter function returned 0 (not matched).
627  */
628 static int
629 rt_unlinkrte(struct rib_head *rnh, struct rt_addrinfo *info, struct rib_cmd_info *rc)
630 {
631         struct rtentry *rt;
632         struct nhop_object *nh;
633         struct radix_node *rn;
634         struct route_nhop_data rnd;
635         int error;
636
637         rt = lookup_prefix(rnh, info, &rnd);
638         if (rt == NULL)
639                 return (ESRCH);
640
641         nh = rt->rt_nhop;
642 #ifdef ROUTE_MPATH
643         if (NH_IS_NHGRP(nh)) {
644                 error = del_route_mpath(rnh, info, rt,
645                     (struct nhgrp_object *)nh, rc);
646                 return (error);
647         }
648 #endif
649         error = check_info_match_nhop(info, rt, nh);
650         if (error != 0)
651                 return (error);
652
653         if (can_override_nhop(info, nh) < 0)
654                 return (EADDRINUSE);
655
656         /*
657          * Remove the item from the tree and return it.
658          * Complain if it is not there and do no more processing.
659          */
660         rn = rnh->rnh_deladdr(info->rti_info[RTAX_DST],
661             info->rti_info[RTAX_NETMASK], &rnh->head);
662         if (rn == NULL)
663                 return (ESRCH);
664
665         if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
666                 panic ("rtrequest delete");
667
668         rt = RNTORT(rn);
669         rt->rte_flags &= ~RTF_UP;
670
671         /* Finalize notification */
672         rnh->rnh_gen++;
673         rnh->rnh_prefixes--;
674
675         rc->rc_cmd = RTM_DELETE;
676         rc->rc_rt = rt;
677         rc->rc_nh_old = rt->rt_nhop;
678         rc->rc_nh_weight = rt->rt_weight;
679         rib_notify(rnh, RIB_NOTIFY_IMMEDIATE, rc);
680
681         return (0);
682 }
683
684 static int
685 del_route(struct rib_head *rnh, struct rt_addrinfo *info,
686     struct rib_cmd_info *rc)
687 {
688         int error;
689
690         RIB_WLOCK(rnh);
691         error = rt_unlinkrte(rnh, info, rc);
692         RIB_WUNLOCK(rnh);
693         if (error != 0)
694                 return (error);
695
696         rib_notify(rnh, RIB_NOTIFY_DELAYED, rc);
697
698         /*
699          * If the caller wants it, then it can have it,
700          * the entry will be deleted after the end of the current epoch.
701          */
702         if (rc->rc_cmd == RTM_DELETE)
703                 rtfree(rc->rc_rt);
704 #ifdef ROUTE_MPATH
705         else {
706                 /*
707                  * Deleting 1 path may result in RTM_CHANGE to
708                  * a different mpath group/nhop.
709                  * Free old mpath group.
710                  */
711                 nhop_free_any(rc->rc_nh_old);
712         }
713 #endif
714
715         return (0);
716 }
717
718 int
719 rib_change_route(uint32_t fibnum, struct rt_addrinfo *info,
720     struct rib_cmd_info *rc)
721 {
722         RIB_RLOCK_TRACKER;
723         struct route_nhop_data rnd_orig;
724         struct rib_head *rnh;
725         struct rtentry *rt;
726         int error;
727
728         NET_EPOCH_ASSERT();
729
730         rnh = get_rnh(fibnum, info);
731         if (rnh == NULL)
732                 return (EAFNOSUPPORT);
733
734         bzero(rc, sizeof(struct rib_cmd_info));
735         rc->rc_cmd = RTM_CHANGE;
736
737         /* Check if updated gateway exists */
738         if ((info->rti_flags & RTF_GATEWAY) &&
739             (info->rti_info[RTAX_GATEWAY] == NULL)) {
740
741                 /*
742                  * route(8) adds RTF_GATEWAY flag if -interface is not set.
743                  * Remove RTF_GATEWAY to enforce consistency and maintain
744                  * compatibility..
745                  */
746                 info->rti_flags &= ~RTF_GATEWAY;
747         }
748
749         /*
750          * route change is done in multiple steps, with dropping and
751          * reacquiring lock. In the situations with multiple processes
752          * changes the same route in can lead to the case when route
753          * is changed between the steps. Address it by retrying the operation
754          * multiple times before failing.
755          */
756
757         RIB_RLOCK(rnh);
758         rt = (struct rtentry *)rnh->rnh_lookup(info->rti_info[RTAX_DST],
759             info->rti_info[RTAX_NETMASK], &rnh->head);
760
761         if (rt == NULL) {
762                 RIB_RUNLOCK(rnh);
763                 return (ESRCH);
764         }
765
766         rnd_orig.rnd_nhop = rt->rt_nhop;
767         rnd_orig.rnd_weight = rt->rt_weight;
768
769         RIB_RUNLOCK(rnh);
770
771         for (int i = 0; i < RIB_MAX_RETRIES; i++) {
772                 error = change_route(rnh, info, &rnd_orig, rc);
773                 if (error != EAGAIN)
774                         break;
775         }
776
777         return (error);
778 }
779
780 static int
781 change_nhop(struct rib_head *rnh, struct rt_addrinfo *info,
782     struct nhop_object *nh_orig, struct nhop_object **nh_new)
783 {
784         int free_ifa = 0;
785         int error;
786
787         /*
788          * New gateway could require new ifaddr, ifp;
789          * flags may also be different; ifp may be specified
790          * by ll sockaddr when protocol address is ambiguous
791          */
792         if (((nh_orig->nh_flags & NHF_GATEWAY) &&
793             info->rti_info[RTAX_GATEWAY] != NULL) ||
794             info->rti_info[RTAX_IFP] != NULL ||
795             (info->rti_info[RTAX_IFA] != NULL &&
796              !sa_equal(info->rti_info[RTAX_IFA], nh_orig->nh_ifa->ifa_addr))) {
797                 error = rt_getifa_fib(info, rnh->rib_fibnum);
798                 if (info->rti_ifa != NULL)
799                         free_ifa = 1;
800
801                 if (error != 0) {
802                         if (free_ifa) {
803                                 ifa_free(info->rti_ifa);
804                                 info->rti_ifa = NULL;
805                         }
806
807                         return (error);
808                 }
809         }
810
811         error = nhop_create_from_nhop(rnh, nh_orig, info, nh_new);
812         if (free_ifa) {
813                 ifa_free(info->rti_ifa);
814                 info->rti_ifa = NULL;
815         }
816
817         return (error);
818 }
819
820 #ifdef ROUTE_MPATH
821 static int
822 change_mpath_route(struct rib_head *rnh, struct rt_addrinfo *info,
823     struct route_nhop_data *rnd_orig, struct rib_cmd_info *rc)
824 {
825         int error = 0;
826         struct nhop_object *nh, *nh_orig, *nh_new;
827         struct route_nhop_data rnd_new;
828
829         nh = NULL;
830         nh_orig = rnd_orig->rnd_nhop;
831
832         struct weightened_nhop *wn = NULL, *wn_new;
833         uint32_t num_nhops;
834
835         wn = nhgrp_get_nhops((struct nhgrp_object *)nh_orig, &num_nhops);
836         nh_orig = NULL;
837         for (int i = 0; i < num_nhops; i++) {
838                 if (check_info_match_nhop(info, NULL, wn[i].nh)) {
839                         nh_orig = wn[i].nh;
840                         break;
841                 }
842         }
843
844         if (nh_orig == NULL)
845                 return (ESRCH);
846
847         error = change_nhop(rnh, info, nh_orig, &nh_new);
848         if (error != 0)
849                 return (error);
850
851         wn_new = mallocarray(num_nhops, sizeof(struct weightened_nhop),
852             M_TEMP, M_NOWAIT | M_ZERO);
853         if (wn_new == NULL) {
854                 nhop_free(nh_new);
855                 return (EAGAIN);
856         }
857
858         memcpy(wn_new, wn, num_nhops * sizeof(struct weightened_nhop));
859         for (int i = 0; i < num_nhops; i++) {
860                 if (wn[i].nh == nh_orig) {
861                         wn[i].nh = nh_new;
862                         wn[i].weight = get_info_weight(info, rnd_orig->rnd_weight);
863                         break;
864                 }
865         }
866
867         error = nhgrp_get_group(rnh, wn_new, num_nhops, &rnd_new);
868         nhop_free(nh_new);
869         free(wn_new, M_TEMP);
870
871         if (error != 0)
872                 return (error);
873
874         error = change_route_conditional(rnh, NULL, info, rnd_orig, &rnd_new, rc);
875
876         return (error);
877 }
878 #endif
879
880 static int
881 change_route(struct rib_head *rnh, struct rt_addrinfo *info,
882     struct route_nhop_data *rnd_orig, struct rib_cmd_info *rc)
883 {
884         int error = 0;
885         struct nhop_object *nh, *nh_orig;
886         struct route_nhop_data rnd_new;
887
888         nh = NULL;
889         nh_orig = rnd_orig->rnd_nhop;
890         if (nh_orig == NULL)
891                 return (ESRCH);
892
893 #ifdef ROUTE_MPATH
894         if (NH_IS_NHGRP(nh_orig))
895                 return (change_mpath_route(rnh, info, rnd_orig, rc));
896 #endif
897
898         rnd_new.rnd_weight = get_info_weight(info, rnd_orig->rnd_weight);
899         error = change_nhop(rnh, info, nh_orig, &rnd_new.rnd_nhop);
900         if (error != 0)
901                 return (error);
902         error = change_route_conditional(rnh, NULL, info, rnd_orig, &rnd_new, rc);
903
904         return (error);
905 }
906
907 /*
908  * Insert @rt with nhop data from @rnd_new to @rnh.
909  * Returns 0 on success and stores operation results in @rc.
910  */
911 static int
912 add_route_nhop(struct rib_head *rnh, struct rtentry *rt,
913     struct rt_addrinfo *info, struct route_nhop_data *rnd,
914     struct rib_cmd_info *rc)
915 {
916         struct sockaddr *ndst, *netmask;
917         struct radix_node *rn;
918         int error = 0;
919
920         RIB_WLOCK_ASSERT(rnh);
921
922         ndst = (struct sockaddr *)rt_key(rt);
923         netmask = info->rti_info[RTAX_NETMASK];
924
925         rt->rt_nhop = rnd->rnd_nhop;
926         rt->rt_weight = rnd->rnd_weight;
927         rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head, rt->rt_nodes);
928
929         if (rn != NULL) {
930                 if (rt->rt_expire > 0)
931                         tmproutes_update(rnh, rt);
932
933                 /* Finalize notification */
934                 rnh->rnh_gen++;
935                 rnh->rnh_prefixes++;
936
937                 rc->rc_cmd = RTM_ADD;
938                 rc->rc_rt = rt;
939                 rc->rc_nh_old = NULL;
940                 rc->rc_nh_new = rnd->rnd_nhop;
941                 rc->rc_nh_weight = rnd->rnd_weight;
942
943                 rib_notify(rnh, RIB_NOTIFY_IMMEDIATE, rc);
944         } else {
945                 /* Existing route or memory allocation failure */
946                 error = EEXIST;
947         }
948
949         return (error);
950 }
951
952 /*
953  * Switch @rt nhop/weigh to the ones specified in @rnd.
954  *  Conditionally set rt_expire if set in @info.
955  * Returns 0 on success.
956  */
957 int
958 change_route_nhop(struct rib_head *rnh, struct rtentry *rt,
959     struct rt_addrinfo *info, struct route_nhop_data *rnd,
960     struct rib_cmd_info *rc)
961 {
962         struct nhop_object *nh_orig;
963
964         RIB_WLOCK_ASSERT(rnh);
965
966         nh_orig = rt->rt_nhop;
967
968         if (rnd->rnd_nhop != NULL) {
969                 /* Changing expiration & nexthop & weight to a new one */
970                 rt_set_expire_info(rt, info);
971                 rt->rt_nhop = rnd->rnd_nhop;
972                 rt->rt_weight = rnd->rnd_weight;
973                 if (rt->rt_expire > 0)
974                         tmproutes_update(rnh, rt);
975         } else {
976                 /* Route deletion requested. */
977                 struct sockaddr *ndst, *netmask;
978                 struct radix_node *rn;
979
980                 ndst = (struct sockaddr *)rt_key(rt);
981                 netmask = info->rti_info[RTAX_NETMASK];
982                 rn = rnh->rnh_deladdr(ndst, netmask, &rnh->head);
983                 if (rn == NULL)
984                         return (ESRCH);
985                 rt = RNTORT(rn);
986                 rt->rte_flags &= ~RTF_UP;
987         }
988
989         /* Finalize notification */
990         rnh->rnh_gen++;
991         if (rnd->rnd_nhop == NULL)
992                 rnh->rnh_prefixes--;
993
994         rc->rc_cmd = (rnd->rnd_nhop != NULL) ? RTM_CHANGE : RTM_DELETE;
995         rc->rc_rt = rt;
996         rc->rc_nh_old = nh_orig;
997         rc->rc_nh_new = rnd->rnd_nhop;
998         rc->rc_nh_weight = rnd->rnd_weight;
999
1000         rib_notify(rnh, RIB_NOTIFY_IMMEDIATE, rc);
1001
1002         return (0);
1003 }
1004
1005 /*
1006  * Conditionally update route nhop/weight IFF data in @nhd_orig is
1007  *  consistent with the current route data.
1008  * Nexthop in @nhd_new is consumed.
1009  */
1010 int
1011 change_route_conditional(struct rib_head *rnh, struct rtentry *rt,
1012     struct rt_addrinfo *info, struct route_nhop_data *rnd_orig,
1013     struct route_nhop_data *rnd_new, struct rib_cmd_info *rc)
1014 {
1015         struct rtentry *rt_new;
1016         int error = 0;
1017
1018         RIB_WLOCK(rnh);
1019
1020         rt_new = (struct rtentry *)rnh->rnh_lookup(info->rti_info[RTAX_DST],
1021             info->rti_info[RTAX_NETMASK], &rnh->head);
1022
1023         if (rt_new == NULL) {
1024                 if (rnd_orig->rnd_nhop == NULL)
1025                         error = add_route_nhop(rnh, rt, info, rnd_new, rc);
1026                 else {
1027                         /*
1028                          * Prefix does not exist, which was not our assumption.
1029                          * Update @rnd_orig with the new data and return
1030                          */
1031                         rnd_orig->rnd_nhop = NULL;
1032                         rnd_orig->rnd_weight = 0;
1033                         error = EAGAIN;
1034                 }
1035         } else {
1036                 /* Prefix exists, try to update */
1037                 if (rnd_orig->rnd_nhop == rt_new->rt_nhop) {
1038                         /*
1039                          * Nhop/mpath group hasn't changed. Flip
1040                          * to the new precalculated one and return
1041                          */
1042                         error = change_route_nhop(rnh, rt_new, info, rnd_new, rc);
1043                 } else {
1044                         /* Update and retry */
1045                         rnd_orig->rnd_nhop = rt_new->rt_nhop;
1046                         rnd_orig->rnd_weight = rt_new->rt_weight;
1047                         error = EAGAIN;
1048                 }
1049         }
1050
1051         RIB_WUNLOCK(rnh);
1052
1053         if (error == 0) {
1054                 rib_notify(rnh, RIB_NOTIFY_DELAYED, rc);
1055
1056                 if (rnd_orig->rnd_nhop != NULL)
1057                         nhop_free_any(rnd_orig->rnd_nhop);
1058
1059         } else {
1060                 if (rnd_new->rnd_nhop != NULL)
1061                         nhop_free_any(rnd_new->rnd_nhop);
1062         }
1063
1064         return (error);
1065 }
1066
1067 /*
1068  * Performs modification of routing table specificed by @action.
1069  * Table is specified by @fibnum and sa_family in @info->rti_info[RTAX_DST].
1070  * Needs to be run in network epoch.
1071  *
1072  * Returns 0 on success and fills in @rc with action result.
1073  */
1074 int
1075 rib_action(uint32_t fibnum, int action, struct rt_addrinfo *info,
1076     struct rib_cmd_info *rc)
1077 {
1078         int error;
1079
1080         switch (action) {
1081         case RTM_ADD:
1082                 error = rib_add_route(fibnum, info, rc);
1083                 break;
1084         case RTM_DELETE:
1085                 error = rib_del_route(fibnum, info, rc);
1086                 break;
1087         case RTM_CHANGE:
1088                 error = rib_change_route(fibnum, info, rc);
1089                 break;
1090         default:
1091                 error = ENOTSUP;
1092         }
1093
1094         return (error);
1095 }
1096
1097 struct rt_delinfo
1098 {
1099         struct rt_addrinfo info;
1100         struct rib_head *rnh;
1101         struct rtentry *head;
1102         struct rib_cmd_info rc;
1103 };
1104
1105 /*
1106  * Conditionally unlinks @rn from radix tree based
1107  * on info data passed in @arg.
1108  */
1109 static int
1110 rt_checkdelroute(struct radix_node *rn, void *arg)
1111 {
1112         struct rt_delinfo *di;
1113         struct rt_addrinfo *info;
1114         struct rtentry *rt;
1115         int error;
1116
1117         di = (struct rt_delinfo *)arg;
1118         rt = (struct rtentry *)rn;
1119         info = &di->info;
1120
1121         info->rti_info[RTAX_DST] = rt_key(rt);
1122         info->rti_info[RTAX_NETMASK] = rt_mask(rt);
1123
1124         error = rt_unlinkrte(di->rnh, info, &di->rc);
1125
1126         /*
1127          * Add deleted rtentries to the list to GC them
1128          *  after dropping the lock.
1129          *
1130          * XXX: Delayed notifications not implemented
1131          *  for nexthop updates.
1132          */
1133         if ((error == 0) && (di->rc.rc_cmd == RTM_DELETE)) {
1134                 /* Add to the list and return */
1135                 rt->rt_chain = di->head;
1136                 di->head = rt;
1137         }
1138
1139         return (0);
1140 }
1141
1142 /*
1143  * Iterates over a routing table specified by @fibnum and @family and
1144  *  deletes elements marked by @filter_f.
1145  * @fibnum: rtable id
1146  * @family: AF_ address family
1147  * @filter_f: function returning non-zero value for items to delete
1148  * @arg: data to pass to the @filter_f function
1149  * @report: true if rtsock notification is needed.
1150  */
1151 void
1152 rib_walk_del(u_int fibnum, int family, rib_filter_f_t *filter_f, void *arg, bool report)
1153 {
1154         struct rib_head *rnh;
1155         struct rt_delinfo di;
1156         struct rtentry *rt;
1157         struct nhop_object *nh;
1158         struct epoch_tracker et;
1159
1160         rnh = rt_tables_get_rnh(fibnum, family);
1161         if (rnh == NULL)
1162                 return;
1163
1164         bzero(&di, sizeof(di));
1165         di.info.rti_filter = filter_f;
1166         di.info.rti_filterdata = arg;
1167         di.rnh = rnh;
1168         di.rc.rc_cmd = RTM_DELETE;
1169
1170         NET_EPOCH_ENTER(et);
1171
1172         RIB_WLOCK(rnh);
1173         rnh->rnh_walktree(&rnh->head, rt_checkdelroute, &di);
1174         RIB_WUNLOCK(rnh);
1175
1176         /* We might have something to reclaim. */
1177         bzero(&di.rc, sizeof(di.rc));
1178         di.rc.rc_cmd = RTM_DELETE;
1179         while (di.head != NULL) {
1180                 rt = di.head;
1181                 di.head = rt->rt_chain;
1182                 rt->rt_chain = NULL;
1183                 nh = rt->rt_nhop;
1184
1185                 di.rc.rc_rt = rt;
1186                 di.rc.rc_nh_old = nh;
1187                 rib_notify(rnh, RIB_NOTIFY_DELAYED, &di.rc);
1188
1189                 /* TODO std rt -> rt_addrinfo export */
1190                 di.info.rti_info[RTAX_DST] = rt_key(rt);
1191                 di.info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1192
1193                 if (report) {
1194 #ifdef ROUTE_MPATH
1195                         struct nhgrp_object *nhg;
1196                         struct weightened_nhop *wn;
1197                         uint32_t num_nhops;
1198                         if (NH_IS_NHGRP(nh)) {
1199                                 nhg = (struct nhgrp_object *)nh;
1200                                 wn = nhgrp_get_nhops(nhg, &num_nhops);
1201                                 for (int i = 0; i < num_nhops; i++)
1202                                         rt_routemsg(RTM_DELETE, rt,
1203                                             wn[i].nh->nh_ifp, 0, fibnum);
1204                         } else
1205 #endif
1206                         rt_routemsg(RTM_DELETE, rt, nh->nh_ifp, 0, fibnum);
1207                 }
1208                 rtfree(rt);
1209         }
1210
1211         NET_EPOCH_EXIT(et);
1212 }
1213
1214 static void
1215 rib_notify(struct rib_head *rnh, enum rib_subscription_type type,
1216     struct rib_cmd_info *rc)
1217 {
1218         struct rib_subscription *rs;
1219
1220         CK_STAILQ_FOREACH(rs, &rnh->rnh_subscribers, next) {
1221                 if (rs->type == type)
1222                         rs->func(rnh, rc, rs->arg);
1223         }
1224 }
1225
1226 static struct rib_subscription *
1227 allocate_subscription(rib_subscription_cb_t *f, void *arg,
1228     enum rib_subscription_type type, bool waitok)
1229 {
1230         struct rib_subscription *rs;
1231         int flags = M_ZERO | (waitok ? M_WAITOK : M_NOWAIT);
1232
1233         rs = malloc(sizeof(struct rib_subscription), M_RTABLE, flags);
1234         if (rs == NULL)
1235                 return (NULL);
1236
1237         rs->func = f;
1238         rs->arg = arg;
1239         rs->type = type;
1240
1241         return (rs);
1242 }
1243
1244 /*
1245  * Subscribe for the changes in the routing table specified by @fibnum and
1246  *  @family.
1247  *
1248  * Returns pointer to the subscription structure on success.
1249  */
1250 struct rib_subscription *
1251 rib_subscribe(uint32_t fibnum, int family, rib_subscription_cb_t *f, void *arg,
1252     enum rib_subscription_type type, bool waitok)
1253 {
1254         struct rib_head *rnh;
1255         struct epoch_tracker et;
1256
1257         NET_EPOCH_ENTER(et);
1258         KASSERT((fibnum < rt_numfibs), ("%s: bad fibnum", __func__));
1259         rnh = rt_tables_get_rnh(fibnum, family);
1260         NET_EPOCH_EXIT(et);
1261
1262         return (rib_subscribe_internal(rnh, f, arg, type, waitok));
1263 }
1264
1265 struct rib_subscription *
1266 rib_subscribe_internal(struct rib_head *rnh, rib_subscription_cb_t *f, void *arg,
1267     enum rib_subscription_type type, bool waitok)
1268 {
1269         struct rib_subscription *rs;
1270         struct epoch_tracker et;
1271
1272         if ((rs = allocate_subscription(f, arg, type, waitok)) == NULL)
1273                 return (NULL);
1274         rs->rnh = rnh;
1275
1276         NET_EPOCH_ENTER(et);
1277         RIB_WLOCK(rnh);
1278         CK_STAILQ_INSERT_TAIL(&rnh->rnh_subscribers, rs, next);
1279         RIB_WUNLOCK(rnh);
1280         NET_EPOCH_EXIT(et);
1281
1282         return (rs);
1283 }
1284
1285 /*
1286  * Remove rtable subscription @rs from the routing table.
1287  * Needs to be run in network epoch.
1288  */
1289 void
1290 rib_unsibscribe(struct rib_subscription *rs)
1291 {
1292         struct rib_head *rnh = rs->rnh;
1293
1294         NET_EPOCH_ASSERT();
1295
1296         RIB_WLOCK(rnh);
1297         CK_STAILQ_REMOVE(&rnh->rnh_subscribers, rs, rib_subscription, next);
1298         RIB_WUNLOCK(rnh);
1299
1300         epoch_call(net_epoch_preempt, destroy_subscription_epoch,
1301             &rs->epoch_ctx);
1302 }
1303
1304 /*
1305  * Epoch callback indicating subscription is safe to destroy
1306  */
1307 static void
1308 destroy_subscription_epoch(epoch_context_t ctx)
1309 {
1310         struct rib_subscription *rs;
1311
1312         rs = __containerof(ctx, struct rib_subscription, epoch_ctx);
1313
1314         free(rs, M_RTABLE);
1315 }
1316
1317 void
1318 rib_init_subscriptions(struct rib_head *rnh)
1319 {
1320
1321         CK_STAILQ_INIT(&rnh->rnh_subscribers);
1322 }
1323
1324 void
1325 rib_destroy_subscriptions(struct rib_head *rnh)
1326 {
1327         struct rib_subscription *rs;
1328         struct epoch_tracker et;
1329
1330         NET_EPOCH_ENTER(et);
1331         RIB_WLOCK(rnh);
1332         while ((rs = CK_STAILQ_FIRST(&rnh->rnh_subscribers)) != NULL) {
1333                 CK_STAILQ_REMOVE_HEAD(&rnh->rnh_subscribers, next);
1334                 epoch_call(net_epoch_preempt, destroy_subscription_epoch,
1335                     &rs->epoch_ctx);
1336         }
1337         RIB_WUNLOCK(rnh);
1338         NET_EPOCH_EXIT(et);
1339 }