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