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