xref: /freebsd/sys/net/route/nhop_ctl.c (revision dc3509f1aafcd966f3dd9226115cf94b691ff3c7)
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/lock.h>
37 #include <sys/rwlock.h>
38 #include <sys/malloc.h>
39 #include <sys/socket.h>
40 #include <sys/sysctl.h>
41 #include <sys/kernel.h>
42 #include <sys/epoch.h>
43 
44 #include <net/if.h>
45 #include <net/if_var.h>
46 #include <net/if_dl.h>
47 #include <net/route.h>
48 #include <net/route/route_ctl.h>
49 #include <net/route/route_var.h>
50 #include <net/route/nhop_utils.h>
51 #include <net/route/nhop.h>
52 #include <net/route/nhop_var.h>
53 #include <net/vnet.h>
54 
55 #define	DEBUG_MOD_NAME	nhop_ctl
56 #define	DEBUG_MAX_LEVEL	LOG_DEBUG
57 #include <net/route/route_debug.h>
58 _DECLARE_DEBUG(LOG_INFO);
59 
60 /*
61  * This file contains core functionality for the nexthop ("nhop") route subsystem.
62  * The business logic needed to create nexhop objects is implemented here.
63  *
64  * Nexthops in the original sense are the objects containing all the necessary
65  * information to forward the packet to the selected destination.
66  * In particular, nexthop is defined by a combination of
67  *  ifp, ifa, aifp, mtu, gw addr(if set), nh_type, nh_upper_family, mask of rt_flags and
68  *    NHF_DEFAULT
69  *
70  * Additionally, each nexthop gets assigned its unique index (nexthop index).
71  * It serves two purposes: first one is to ease the ability of userland programs to
72  *  reference nexthops by their index. The second one allows lookup algorithms to
73  *  to store index instead of pointer (2 bytes vs 8) as a lookup result.
74  * All nexthops are stored in the resizable hash table.
75  *
76  * Basically, this file revolves around supporting 3 functions:
77  * 1) nhop_create_from_info / nhop_create_from_nhop, which contains all
78  *  business logic on filling the nexthop fields based on the provided request.
79  * 2) nhop_get(), which gets a usable referenced nexthops.
80  *
81  * Conventions:
82  * 1) non-exported functions start with verb
83  * 2) exported function starts with the subsystem prefix: "nhop"
84  */
85 
86 static int dump_nhop_entry(struct rib_head *rh, struct nhop_object *nh, struct sysctl_req *w);
87 
88 static int finalize_nhop(struct nh_control *ctl, struct nhop_object *nh);
89 static struct ifnet *get_aifp(const struct nhop_object *nh);
90 static void fill_sdl_from_ifp(struct sockaddr_dl_short *sdl, const struct ifnet *ifp);
91 
92 static void destroy_nhop_epoch(epoch_context_t ctx);
93 static void destroy_nhop(struct nhop_object *nh);
94 static struct rib_head *nhop_get_rh(const struct nhop_object *nh);
95 
96 _Static_assert(__offsetof(struct nhop_object, nh_ifp) == 32,
97     "nhop_object: wrong nh_ifp offset");
98 _Static_assert(sizeof(struct nhop_object) <= 128,
99     "nhop_object: size exceeds 128 bytes");
100 
101 static uma_zone_t nhops_zone;	/* Global zone for each and every nexthop */
102 
103 #define	NHOP_OBJECT_ALIGNED_SIZE	roundup2(sizeof(struct nhop_object), \
104 							2 * CACHE_LINE_SIZE)
105 #define	NHOP_PRIV_ALIGNED_SIZE		roundup2(sizeof(struct nhop_priv), \
106 							2 * CACHE_LINE_SIZE)
107 void
108 nhops_init(void)
109 {
110 
111 	nhops_zone = uma_zcreate("routing nhops",
112 	    NHOP_OBJECT_ALIGNED_SIZE + NHOP_PRIV_ALIGNED_SIZE,
113 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
114 }
115 
116 /*
117  * Fetches the interface of source address used by the route.
118  * In all cases except interface-address-route it would be the
119  * same as the transmit interfaces.
120  * However, for the interface address this function will return
121  * this interface ifp instead of loopback. This is needed to support
122  * link-local IPv6 loopback communications.
123  *
124  * Returns found ifp.
125  */
126 static struct ifnet *
127 get_aifp(const struct nhop_object *nh)
128 {
129 	struct ifnet *aifp = NULL;
130 
131 	/*
132 	 * Adjust the "outgoing" interface.  If we're going to loop
133 	 * the packet back to ourselves, the ifp would be the loopback
134 	 * interface. However, we'd rather know the interface associated
135 	 * to the destination address (which should probably be one of
136 	 * our own addresses).
137 	 */
138 	if ((nh->nh_ifp->if_flags & IFF_LOOPBACK) &&
139 			nh->gw_sa.sa_family == AF_LINK) {
140 		aifp = ifnet_byindex(nh->gwl_sa.sdl_index);
141 		if (aifp == NULL) {
142 			FIB_NH_LOG(LOG_WARNING, nh, "unable to get aifp for %s index %d",
143 				if_name(nh->nh_ifp), nh->gwl_sa.sdl_index);
144 		}
145 	}
146 
147 	if (aifp == NULL)
148 		aifp = nh->nh_ifp;
149 
150 	return (aifp);
151 }
152 
153 int
154 cmp_priv(const struct nhop_priv *_one, const struct nhop_priv *_two)
155 {
156 
157 	if (memcmp(_one->nh, _two->nh, NHOP_END_CMP) != 0)
158 		return (0);
159 
160 	if (memcmp(_one, _two, NH_PRIV_END_CMP) != 0)
161 		return (0);
162 
163 	return (1);
164 }
165 
166 /*
167  * Conditionally sets @nh mtu data based on the @info data.
168  */
169 static void
170 set_nhop_mtu_from_info(struct nhop_object *nh, const struct rt_addrinfo *info)
171 {
172 	if (info->rti_mflags & RTV_MTU)
173 		nhop_set_mtu(nh, info->rti_rmx->rmx_mtu, true);
174 }
175 
176 /*
177  * Fills in shorted link-level sockadd version suitable to be stored inside the
178  *  nexthop gateway buffer.
179  */
180 static void
181 fill_sdl_from_ifp(struct sockaddr_dl_short *sdl, const struct ifnet *ifp)
182 {
183 
184 	bzero(sdl, sizeof(struct sockaddr_dl_short));
185 	sdl->sdl_family = AF_LINK;
186 	sdl->sdl_len = sizeof(struct sockaddr_dl_short);
187 	sdl->sdl_index = ifp->if_index;
188 	sdl->sdl_type = ifp->if_type;
189 }
190 
191 static int
192 set_nhop_gw_from_info(struct nhop_object *nh, struct rt_addrinfo *info)
193 {
194 	struct sockaddr *gw;
195 
196 	gw = info->rti_info[RTAX_GATEWAY];
197 	MPASS(gw != NULL);
198 	bool is_gw = info->rti_flags & RTF_GATEWAY;
199 
200 	if ((gw->sa_family == AF_LINK) && !is_gw) {
201 
202 		/*
203 		 * Interface route with interface specified by the interface
204 		 * index in sockadd_dl structure. It is used in the IPv6 loopback
205 		 * output code, where we need to preserve the original interface
206 		 * to maintain proper scoping.
207 		 * Despite the fact that nexthop code stores original interface
208 		 * in the separate field (nh_aifp, see below), write AF_LINK
209 		 * compatible sa with shorter total length.
210 		 */
211 		struct sockaddr_dl *sdl = (struct sockaddr_dl *)gw;
212 		struct ifnet *ifp = ifnet_byindex(sdl->sdl_index);
213 		if (ifp == NULL) {
214 			FIB_NH_LOG(LOG_DEBUG, nh, "error: invalid ifindex %d",
215 			    sdl->sdl_index);
216 			return (EINVAL);
217 		}
218 		nhop_set_direct_gw(nh, ifp);
219 	} else {
220 
221 		/*
222 		 * Multiple options here:
223 		 *
224 		 * 1) RTF_GATEWAY with IPv4/IPv6 gateway data
225 		 * 2) Interface route with IPv4/IPv6 address of the
226 		 *   matching interface. Some routing daemons do that
227 		 *   instead of specifying ifindex in AF_LINK.
228 		 *
229 		 * In both cases, save the original nexthop to make the callers
230 		 *   happy.
231 		 */
232 		if (!nhop_set_gw(nh, gw, is_gw))
233 			return (EINVAL);
234 	}
235 	return (0);
236 }
237 
238 static void
239 set_nhop_expire_from_info(struct nhop_object *nh, const struct rt_addrinfo *info)
240 {
241 	uint32_t nh_expire = 0;
242 
243 	/* Kernel -> userland timebase conversion. */
244 	if ((info->rti_mflags & RTV_EXPIRE) && (info->rti_rmx->rmx_expire > 0))
245 		nh_expire = info->rti_rmx->rmx_expire - time_second + time_uptime;
246 	nhop_set_expire(nh, nh_expire);
247 }
248 
249 /*
250  * Creates a new nexthop based on the information in @info.
251  *
252  * Returns:
253  * 0 on success, filling @nh_ret with the desired nexthop object ptr
254  * errno otherwise
255  */
256 int
257 nhop_create_from_info(struct rib_head *rnh, struct rt_addrinfo *info,
258     struct nhop_object **nh_ret)
259 {
260 	int error;
261 
262 	NET_EPOCH_ASSERT();
263 
264 	MPASS(info->rti_ifa != NULL);
265 	MPASS(info->rti_ifp != NULL);
266 
267 	if (info->rti_info[RTAX_GATEWAY] == NULL) {
268 		FIB_RH_LOG(LOG_DEBUG, rnh, "error: empty gateway");
269 		return (EINVAL);
270 	}
271 
272 	struct nhop_object *nh = nhop_alloc(rnh->rib_fibnum, rnh->rib_family);
273 	if (nh == NULL)
274 		return (ENOMEM);
275 
276 	if ((error = set_nhop_gw_from_info(nh, info)) != 0) {
277 		nhop_free(nh);
278 		return (error);
279 	}
280 	nhop_set_transmit_ifp(nh, info->rti_ifp);
281 
282 	nhop_set_blackhole(nh, info->rti_flags & (RTF_BLACKHOLE | RTF_REJECT));
283 
284 	error = rnh->rnh_set_nh_pfxflags(rnh->rib_fibnum, info->rti_info[RTAX_DST],
285 	    info->rti_info[RTAX_NETMASK], nh);
286 
287 	nhop_set_redirect(nh, info->rti_flags & RTF_DYNAMIC);
288 	nhop_set_pinned(nh, info->rti_flags & RTF_PINNED);
289 	set_nhop_expire_from_info(nh, info);
290 	nhop_set_rtflags(nh, info->rti_flags);
291 
292 	set_nhop_mtu_from_info(nh, info);
293 	nhop_set_src(nh, info->rti_ifa);
294 
295 	/*
296 	 * The remaining fields are either set from nh_preadd hook
297 	 * or are computed from the provided data
298 	 */
299 	*nh_ret = nhop_get_nhop(nh, &error);
300 
301 	return (error);
302 }
303 
304 /*
305  * Gets linked nhop using the provided @nh nexhop data.
306  * If linked nhop is found, returns it, freeing the provided one.
307  * If there is no such nexthop, attaches the remaining data to the
308  *  provided nexthop and links it.
309  *
310  * Returns 0 on success, storing referenced nexthop in @pnh.
311  * Otherwise, errno is returned.
312  */
313 struct nhop_object *
314 nhop_get_nhop(struct nhop_object *nh, int *perror)
315 {
316 	struct nhop_priv *tmp_priv;
317 	int error;
318 
319 	nh->nh_aifp = get_aifp(nh);
320 
321 	struct rib_head *rnh = nhop_get_rh(nh);
322 
323 	/* Give the protocols chance to augment nexthop properties */
324 	error = rnh->rnh_augment_nh(rnh->rib_fibnum, nh);
325 	if (error != 0) {
326 		nhop_free(nh);
327 		*perror = error;
328 		return (NULL);
329 	}
330 
331 	tmp_priv = find_nhop(rnh->nh_control, nh->nh_priv);
332 	if (tmp_priv != NULL) {
333 		nhop_free(nh);
334 		*perror = 0;
335 		return (tmp_priv->nh);
336 	}
337 
338 	/*
339 	 * Existing nexthop not found, need to create new one.
340 	 * Note: multiple simultaneous requests
341 	 *  can result in multiple equal nexhops existing in the
342 	 *  nexthop table. This is not a not a problem until the
343 	 *  relative number of such nexthops is significant, which
344 	 *  is extremely unlikely.
345 	 */
346 	*perror = finalize_nhop(rnh->nh_control, nh);
347 	return (*perror == 0 ? nh : NULL);
348 }
349 
350 /*
351  * Update @nh with data supplied in @info.
352  * This is a helper function to support route changes.
353  *
354  * It limits the changes that can be done to the route to the following:
355  * 1) all combination of gateway changes
356  * 2) route flags (FLAG[123],STATIC)
357  * 3) route MTU
358  *
359  * Returns:
360  * 0 on success, errno otherwise
361  */
362 static int
363 alter_nhop_from_info(struct nhop_object *nh, struct rt_addrinfo *info)
364 {
365 	struct sockaddr *info_gw;
366 	int error;
367 
368 	/* Update MTU if set in the request*/
369 	set_nhop_mtu_from_info(nh, info);
370 
371 	/* Only RTF_FLAG[123] and RTF_STATIC */
372 	uint32_t rt_flags = nhop_get_rtflags(nh) & ~RT_CHANGE_RTFLAGS_MASK;
373 	rt_flags |= info->rti_flags & RT_CHANGE_RTFLAGS_MASK;
374 	nhop_set_rtflags(nh, rt_flags);
375 
376 	/* Consider gateway change */
377 	info_gw = info->rti_info[RTAX_GATEWAY];
378 	if (info_gw != NULL) {
379 		error = set_nhop_gw_from_info(nh, info);
380 		if (error != 0)
381 			return (error);
382 	}
383 
384 	if (info->rti_ifa != NULL)
385 		nhop_set_src(nh, info->rti_ifa);
386 	if (info->rti_ifp != NULL)
387 		nhop_set_transmit_ifp(nh, info->rti_ifp);
388 
389 	return (0);
390 }
391 
392 /*
393  * Creates new nexthop based on @nh_orig and augmentation data from @info.
394  * Helper function used in the route changes, please see
395  *   alter_nhop_from_info() comments for more details.
396  *
397  * Returns:
398  * 0 on success, filling @nh_ret with the desired nexthop object
399  * errno otherwise
400  */
401 int
402 nhop_create_from_nhop(struct rib_head *rnh, const struct nhop_object *nh_orig,
403     struct rt_addrinfo *info, struct nhop_object **pnh)
404 {
405 	struct nhop_object *nh;
406 	int error;
407 
408 	NET_EPOCH_ASSERT();
409 
410 	nh = nhop_alloc(rnh->rib_fibnum, rnh->rib_family);
411 	if (nh == NULL)
412 		return (ENOMEM);
413 
414 	nhop_copy(nh, nh_orig);
415 
416 	error = alter_nhop_from_info(nh, info);
417 	if (error != 0) {
418 		nhop_free(nh);
419 		return (error);
420 	}
421 
422 	*pnh = nhop_get_nhop(nh, &error);
423 
424 	return (error);
425 }
426 
427 static bool
428 reference_nhop_deps(struct nhop_object *nh)
429 {
430 	if (!ifa_try_ref(nh->nh_ifa))
431 		return (false);
432 	nh->nh_aifp = get_aifp(nh);
433 	if (!if_try_ref(nh->nh_aifp)) {
434 		ifa_free(nh->nh_ifa);
435 		return (false);
436 	}
437 	FIB_NH_LOG(LOG_DEBUG2, nh, "nh_aifp: %s nh_ifp %s",
438 	    if_name(nh->nh_aifp), if_name(nh->nh_ifp));
439 	if (!if_try_ref(nh->nh_ifp)) {
440 		ifa_free(nh->nh_ifa);
441 		if_rele(nh->nh_aifp);
442 		return (false);
443 	}
444 
445 	return (true);
446 }
447 
448 /*
449  * Alocates/references the remaining bits of nexthop data and links
450  *  it to the hash table.
451  * Returns 0 if successful,
452  *  errno otherwise. @nh_priv is freed in case of error.
453  */
454 static int
455 finalize_nhop(struct nh_control *ctl, struct nhop_object *nh)
456 {
457 
458 	/* Allocate per-cpu packet counter */
459 	nh->nh_pksent = counter_u64_alloc(M_NOWAIT);
460 	if (nh->nh_pksent == NULL) {
461 		nhop_free(nh);
462 		RTSTAT_INC(rts_nh_alloc_failure);
463 		FIB_NH_LOG(LOG_WARNING, nh, "counter_u64_alloc() failed");
464 		return (ENOMEM);
465 	}
466 
467 	if (!reference_nhop_deps(nh)) {
468 		counter_u64_free(nh->nh_pksent);
469 		nhop_free(nh);
470 		RTSTAT_INC(rts_nh_alloc_failure);
471 		FIB_NH_LOG(LOG_WARNING, nh, "interface reference failed");
472 		return (EAGAIN);
473 	}
474 
475 	/* Save vnet to ease destruction */
476 	nh->nh_priv->nh_vnet = curvnet;
477 
478 	/* Please see nhop_free() comments on the initial value */
479 	refcount_init(&nh->nh_priv->nh_linked, 2);
480 
481 	nh->nh_priv->nh_fibnum = ctl->ctl_rh->rib_fibnum;
482 
483 	if (link_nhop(ctl, nh->nh_priv) == 0) {
484 		/*
485 		 * Adding nexthop to the datastructures
486 		 *  failed. Call destructor w/o waiting for
487 		 *  the epoch end, as nexthop is not used
488 		 *  and return.
489 		 */
490 		char nhbuf[NHOP_PRINT_BUFSIZE];
491 		FIB_NH_LOG(LOG_WARNING, nh, "failed to link %s",
492 		    nhop_print_buf(nh, nhbuf, sizeof(nhbuf)));
493 		destroy_nhop(nh);
494 
495 		return (ENOBUFS);
496 	}
497 
498 #if DEBUG_MAX_LEVEL >= LOG_DEBUG
499 	char nhbuf[NHOP_PRINT_BUFSIZE];
500 	FIB_NH_LOG(LOG_DEBUG, nh, "finalized: %s", nhop_print_buf(nh, nhbuf, sizeof(nhbuf)));
501 #endif
502 
503 	return (0);
504 }
505 
506 static void
507 destroy_nhop(struct nhop_object *nh)
508 {
509 	if_rele(nh->nh_ifp);
510 	if_rele(nh->nh_aifp);
511 	ifa_free(nh->nh_ifa);
512 	counter_u64_free(nh->nh_pksent);
513 
514 	uma_zfree(nhops_zone, nh);
515 }
516 
517 /*
518  * Epoch callback indicating nhop is safe to destroy
519  */
520 static void
521 destroy_nhop_epoch(epoch_context_t ctx)
522 {
523 	struct nhop_priv *nh_priv;
524 
525 	nh_priv = __containerof(ctx, struct nhop_priv, nh_epoch_ctx);
526 
527 	destroy_nhop(nh_priv->nh);
528 }
529 
530 void
531 nhop_ref_object(struct nhop_object *nh)
532 {
533 	u_int old __diagused;
534 
535 	old = refcount_acquire(&nh->nh_priv->nh_refcnt);
536 	KASSERT(old > 0, ("%s: nhop object %p has 0 refs", __func__, nh));
537 }
538 
539 int
540 nhop_try_ref_object(struct nhop_object *nh)
541 {
542 
543 	return (refcount_acquire_if_not_zero(&nh->nh_priv->nh_refcnt));
544 }
545 
546 void
547 nhop_free(struct nhop_object *nh)
548 {
549 	struct nh_control *ctl;
550 	struct nhop_priv *nh_priv = nh->nh_priv;
551 	struct epoch_tracker et;
552 
553 	if (!refcount_release(&nh_priv->nh_refcnt))
554 		return;
555 
556 	/* allows to use nhop_free() during nhop init */
557 	if (__predict_false(nh_priv->nh_finalized == 0)) {
558 		uma_zfree(nhops_zone, nh);
559 		return;
560 	}
561 
562 #if DEBUG_MAX_LEVEL >= LOG_DEBUG
563 	char nhbuf[NHOP_PRINT_BUFSIZE];
564 	FIB_NH_LOG(LOG_DEBUG, nh, "deleting %s", nhop_print_buf(nh, nhbuf, sizeof(nhbuf)));
565 #endif
566 
567 	/*
568 	 * There are only 2 places, where nh_linked can be decreased:
569 	 *  rib destroy (nhops_destroy_rib) and this function.
570 	 * nh_link can never be increased.
571 	 *
572 	 * Hence, use initial value of 2 to make use of
573 	 *  refcount_release_if_not_last().
574 	 *
575 	 * There can be two scenarious when calling this function:
576 	 *
577 	 * 1) nh_linked value is 2. This means that either
578 	 *  nhops_destroy_rib() has not been called OR it is running,
579 	 *  but we are guaranteed that nh_control won't be freed in
580 	 *  this epoch. Hence, nexthop can be safely unlinked.
581 	 *
582 	 * 2) nh_linked value is 1. In that case, nhops_destroy_rib()
583 	 *  has been called and nhop unlink can be skipped.
584 	 */
585 
586 	NET_EPOCH_ENTER(et);
587 	if (refcount_release_if_not_last(&nh_priv->nh_linked)) {
588 		ctl = nh_priv->nh_control;
589 		if (unlink_nhop(ctl, nh_priv) == NULL) {
590 			/* Do not try to reclaim */
591 			char nhbuf[NHOP_PRINT_BUFSIZE];
592 			FIB_NH_LOG(LOG_WARNING, nh, "failed to unlink %s",
593 			    nhop_print_buf(nh, nhbuf, sizeof(nhbuf)));
594 			NET_EPOCH_EXIT(et);
595 			return;
596 		}
597 	}
598 	NET_EPOCH_EXIT(et);
599 
600 	epoch_call(net_epoch_preempt, destroy_nhop_epoch,
601 	    &nh_priv->nh_epoch_ctx);
602 }
603 
604 void
605 nhop_ref_any(struct nhop_object *nh)
606 {
607 #ifdef ROUTE_MPATH
608 	if (!NH_IS_NHGRP(nh))
609 		nhop_ref_object(nh);
610 	else
611 		nhgrp_ref_object((struct nhgrp_object *)nh);
612 #else
613 	nhop_ref_object(nh);
614 #endif
615 }
616 
617 void
618 nhop_free_any(struct nhop_object *nh)
619 {
620 
621 #ifdef ROUTE_MPATH
622 	if (!NH_IS_NHGRP(nh))
623 		nhop_free(nh);
624 	else
625 		nhgrp_free((struct nhgrp_object *)nh);
626 #else
627 	nhop_free(nh);
628 #endif
629 }
630 
631 /* Nhop-related methods */
632 
633 /*
634  * Allocates an empty unlinked nhop object.
635  * Returns object pointer or NULL on failure
636  */
637 struct nhop_object *
638 nhop_alloc(uint32_t fibnum, int family)
639 {
640 	struct nhop_object *nh;
641 	struct nhop_priv *nh_priv;
642 
643 	nh = (struct nhop_object *)uma_zalloc(nhops_zone, M_NOWAIT | M_ZERO);
644 	if (__predict_false(nh == NULL))
645 		return (NULL);
646 
647 	nh_priv = (struct nhop_priv *)((char *)nh + NHOP_OBJECT_ALIGNED_SIZE);
648 	nh->nh_priv = nh_priv;
649 	nh_priv->nh = nh;
650 
651 	nh_priv->nh_upper_family = family;
652 	nh_priv->nh_fibnum = fibnum;
653 
654 	/* Setup refcount early to allow nhop_free() to work */
655 	refcount_init(&nh_priv->nh_refcnt, 1);
656 
657 	return (nh);
658 }
659 
660 void
661 nhop_copy(struct nhop_object *nh, const struct nhop_object *nh_orig)
662 {
663 	struct nhop_priv *nh_priv = nh->nh_priv;
664 
665 	nh->nh_flags = nh_orig->nh_flags;
666 	nh->nh_mtu = nh_orig->nh_mtu;
667 	memcpy(&nh->gw_sa, &nh_orig->gw_sa, nh_orig->gw_sa.sa_len);
668 	nh->nh_ifp = nh_orig->nh_ifp;
669 	nh->nh_ifa = nh_orig->nh_ifa;
670 	nh->nh_aifp = nh_orig->nh_aifp;
671 
672 	nh_priv->nh_upper_family = nh_orig->nh_priv->nh_upper_family;
673 	nh_priv->nh_neigh_family = nh_orig->nh_priv->nh_neigh_family;
674 	nh_priv->nh_type = nh_orig->nh_priv->nh_type;
675 	nh_priv->rt_flags = nh_orig->nh_priv->rt_flags;
676 	nh_priv->nh_fibnum = nh_orig->nh_priv->nh_fibnum;
677 }
678 
679 void
680 nhop_set_direct_gw(struct nhop_object *nh, struct ifnet *ifp)
681 {
682 	nh->nh_flags &= ~NHF_GATEWAY;
683 	nh->nh_priv->rt_flags &= ~RTF_GATEWAY;
684 	nh->nh_priv->nh_neigh_family = nh->nh_priv->nh_upper_family;
685 
686 	fill_sdl_from_ifp(&nh->gwl_sa, ifp);
687 	memset(&nh->gw_buf[nh->gw_sa.sa_len], 0, sizeof(nh->gw_buf) - nh->gw_sa.sa_len);
688 }
689 
690 /*
691  * Sets gateway for the nexthop.
692  * It can be "normal" gateway with is_gw set or a special form of
693  * adding interface route, refering to it by specifying local interface
694  * address. In that case is_gw is set to false.
695  */
696 bool
697 nhop_set_gw(struct nhop_object *nh, const struct sockaddr *gw, bool is_gw)
698 {
699 	if (gw->sa_len > sizeof(nh->gw_buf)) {
700 		FIB_NH_LOG(LOG_DEBUG, nh, "nhop SA size too big: AF %d len %u",
701 		    gw->sa_family, gw->sa_len);
702 		return (false);
703 	}
704 	memcpy(&nh->gw_sa, gw, gw->sa_len);
705 	memset(&nh->gw_buf[gw->sa_len], 0, sizeof(nh->gw_buf) - gw->sa_len);
706 
707 	if (is_gw) {
708 		nh->nh_flags |= NHF_GATEWAY;
709 		nh->nh_priv->rt_flags |= RTF_GATEWAY;
710 		nh->nh_priv->nh_neigh_family = gw->sa_family;
711 	} else {
712 		nh->nh_flags &= ~NHF_GATEWAY;
713 		nh->nh_priv->rt_flags &= ~RTF_GATEWAY;
714 		nh->nh_priv->nh_neigh_family = nh->nh_priv->nh_upper_family;
715 	}
716 
717 	return (true);
718 }
719 
720 void
721 nhop_set_broadcast(struct nhop_object *nh, bool is_broadcast)
722 {
723 	if (is_broadcast) {
724 		nh->nh_flags |= NHF_BROADCAST;
725 		nh->nh_priv->rt_flags |= RTF_BROADCAST;
726 	} else {
727 		nh->nh_flags &= ~NHF_BROADCAST;
728 		nh->nh_priv->rt_flags &= ~RTF_BROADCAST;
729 	}
730 }
731 
732 void
733 nhop_set_blackhole(struct nhop_object *nh, int blackhole_rt_flag)
734 {
735 	nh->nh_flags &= ~(NHF_BLACKHOLE | NHF_REJECT);
736 	nh->nh_priv->rt_flags &= ~(RTF_BLACKHOLE | RTF_REJECT);
737 	switch (blackhole_rt_flag) {
738 	case RTF_BLACKHOLE:
739 		nh->nh_flags |= NHF_BLACKHOLE;
740 		nh->nh_priv->rt_flags |= RTF_BLACKHOLE;
741 		break;
742 	case RTF_REJECT:
743 		nh->nh_flags |= NHF_REJECT;
744 		nh->nh_priv->rt_flags |= RTF_REJECT;
745 		break;
746 	}
747 }
748 
749 void
750 nhop_set_redirect(struct nhop_object *nh, bool is_redirect)
751 {
752 	if (is_redirect) {
753 		nh->nh_priv->rt_flags |= RTF_DYNAMIC;
754 		nh->nh_flags |= NHF_REDIRECT;
755 	} else {
756 		nh->nh_priv->rt_flags &= ~RTF_DYNAMIC;
757 		nh->nh_flags &= ~NHF_REDIRECT;
758 	}
759 }
760 
761 void
762 nhop_set_pinned(struct nhop_object *nh, bool is_pinned)
763 {
764 	if (is_pinned)
765 		nh->nh_priv->rt_flags |= RTF_PINNED;
766 	else
767 		nh->nh_priv->rt_flags &= ~RTF_PINNED;
768 }
769 
770 uint32_t
771 nhop_get_idx(const struct nhop_object *nh)
772 {
773 
774 	return (nh->nh_priv->nh_idx);
775 }
776 
777 enum nhop_type
778 nhop_get_type(const struct nhop_object *nh)
779 {
780 
781 	return (nh->nh_priv->nh_type);
782 }
783 
784 void
785 nhop_set_type(struct nhop_object *nh, enum nhop_type nh_type)
786 {
787 
788 	nh->nh_priv->nh_type = nh_type;
789 }
790 
791 int
792 nhop_get_rtflags(const struct nhop_object *nh)
793 {
794 
795 	return (nh->nh_priv->rt_flags);
796 }
797 
798 /*
799  * Sets generic rtflags that are not covered by other functions.
800  */
801 void
802 nhop_set_rtflags(struct nhop_object *nh, int rt_flags)
803 {
804 	nh->nh_priv->rt_flags &= ~RT_SET_RTFLAGS_MASK;
805 	nh->nh_priv->rt_flags |= (rt_flags & RT_SET_RTFLAGS_MASK);
806 }
807 
808 /*
809  * Sets flags that are specific to the prefix (NHF_HOST or NHF_DEFAULT).
810  */
811 void
812 nhop_set_pxtype_flag(struct nhop_object *nh, int nh_flag)
813 {
814 	if (nh_flag == NHF_HOST) {
815 		nh->nh_flags |= NHF_HOST;
816 		nh->nh_flags &= ~NHF_DEFAULT;
817 		nh->nh_priv->rt_flags |= RTF_HOST;
818 	} else if (nh_flag == NHF_DEFAULT) {
819 		nh->nh_flags |= NHF_DEFAULT;
820 		nh->nh_flags &= ~NHF_HOST;
821 		nh->nh_priv->rt_flags &= ~RTF_HOST;
822 	} else {
823 		nh->nh_flags &= ~(NHF_HOST | NHF_DEFAULT);
824 		nh->nh_priv->rt_flags &= ~RTF_HOST;
825 	}
826 }
827 
828 /*
829  * Sets nhop MTU. Sets RTF_FIXEDMTU if mtu is explicitly
830  * specified by userland.
831  */
832 void
833 nhop_set_mtu(struct nhop_object *nh, uint32_t mtu, bool from_user)
834 {
835 	if (from_user) {
836 		if (mtu != 0)
837 			nh->nh_priv->rt_flags |= RTF_FIXEDMTU;
838 		else
839 			nh->nh_priv->rt_flags &= ~RTF_FIXEDMTU;
840 	}
841 	nh->nh_mtu = mtu;
842 }
843 
844 void
845 nhop_set_src(struct nhop_object *nh, struct ifaddr *ifa)
846 {
847 	nh->nh_ifa = ifa;
848 }
849 
850 void
851 nhop_set_transmit_ifp(struct nhop_object *nh, struct ifnet *ifp)
852 {
853 	nh->nh_ifp = ifp;
854 }
855 
856 
857 struct vnet *
858 nhop_get_vnet(const struct nhop_object *nh)
859 {
860 
861 	return (nh->nh_priv->nh_vnet);
862 }
863 
864 struct nhop_object *
865 nhop_select_func(struct nhop_object *nh, uint32_t flowid)
866 {
867 
868 	return (nhop_select(nh, flowid));
869 }
870 
871 /*
872  * Returns address family of the traffic uses the nexthop.
873  */
874 int
875 nhop_get_upper_family(const struct nhop_object *nh)
876 {
877 	return (nh->nh_priv->nh_upper_family);
878 }
879 
880 /*
881  * Returns address family of the LLE or gateway that is used
882  * to forward the traffic to.
883  */
884 int
885 nhop_get_neigh_family(const struct nhop_object *nh)
886 {
887 	return (nh->nh_priv->nh_neigh_family);
888 }
889 
890 uint32_t
891 nhop_get_fibnum(const struct nhop_object *nh)
892 {
893 	return (nh->nh_priv->nh_fibnum);
894 }
895 
896 uint32_t
897 nhop_get_expire(const struct nhop_object *nh)
898 {
899 	return (nh->nh_priv->nh_expire);
900 }
901 
902 void
903 nhop_set_expire(struct nhop_object *nh, uint32_t expire)
904 {
905 	MPASS(!NH_IS_LINKED(nh));
906 	nh->nh_priv->nh_expire = expire;
907 }
908 
909 static struct rib_head *
910 nhop_get_rh(const struct nhop_object *nh)
911 {
912 	uint32_t fibnum = nhop_get_fibnum(nh);
913 	int family = nhop_get_neigh_family(nh);
914 
915 	return (rt_tables_get_rnh(fibnum, family));
916 }
917 
918 void
919 nhops_update_ifmtu(struct rib_head *rh, struct ifnet *ifp, uint32_t mtu)
920 {
921 	struct nh_control *ctl;
922 	struct nhop_priv *nh_priv;
923 	struct nhop_object *nh;
924 
925 	ctl = rh->nh_control;
926 
927 	NHOPS_WLOCK(ctl);
928 	CHT_SLIST_FOREACH(&ctl->nh_head, nhops, nh_priv) {
929 		nh = nh_priv->nh;
930 		if (nh->nh_ifp == ifp) {
931 			if ((nh_priv->rt_flags & RTF_FIXEDMTU) == 0 ||
932 			    nh->nh_mtu > mtu) {
933 				/* Update MTU directly */
934 				nh->nh_mtu = mtu;
935 			}
936 		}
937 	} CHT_SLIST_FOREACH_END;
938 	NHOPS_WUNLOCK(ctl);
939 
940 }
941 
942 /*
943  * Prints nexthop @nh data in the provided @buf.
944  * Example: nh#33/inet/em0/192.168.0.1
945  */
946 char *
947 nhop_print_buf(const struct nhop_object *nh, char *buf, size_t bufsize)
948 {
949 #if defined(INET) || defined(INET6)
950 	char abuf[INET6_ADDRSTRLEN];
951 #endif
952 	struct nhop_priv *nh_priv = nh->nh_priv;
953 	const char *upper_str = rib_print_family(nh->nh_priv->nh_upper_family);
954 
955 	switch (nh->gw_sa.sa_family) {
956 #ifdef INET
957 	case AF_INET:
958 		inet_ntop(AF_INET, &nh->gw4_sa.sin_addr, abuf, sizeof(abuf));
959 		snprintf(buf, bufsize, "nh#%d/%s/%s/%s", nh_priv->nh_idx, upper_str,
960 		    if_name(nh->nh_ifp), abuf);
961 		break;
962 #endif
963 #ifdef INET6
964 	case AF_INET6:
965 		inet_ntop(AF_INET6, &nh->gw6_sa.sin6_addr, abuf, sizeof(abuf));
966 		snprintf(buf, bufsize, "nh#%d/%s/%s/%s", nh_priv->nh_idx, upper_str,
967 		    if_name(nh->nh_ifp), abuf);
968 		break;
969 #endif
970 	case AF_LINK:
971 		snprintf(buf, bufsize, "nh#%d/%s/%s/resolve", nh_priv->nh_idx, upper_str,
972 		    if_name(nh->nh_ifp));
973 		break;
974 	default:
975 		snprintf(buf, bufsize, "nh#%d/%s/%s/????", nh_priv->nh_idx, upper_str,
976 		    if_name(nh->nh_ifp));
977 		break;
978 	}
979 
980 	return (buf);
981 }
982 
983 char *
984 nhop_print_buf_any(const struct nhop_object *nh, char *buf, size_t bufsize)
985 {
986 #ifdef ROUTE_MPATH
987 	if (NH_IS_NHGRP(nh))
988 		return (nhgrp_print_buf((const struct nhgrp_object *)nh, buf, bufsize));
989 	else
990 #endif
991 		return (nhop_print_buf(nh, buf, bufsize));
992 }
993 
994 /*
995  * Dumps a single entry to sysctl buffer.
996  *
997  * Layout:
998  *  rt_msghdr - generic RTM header to allow users to skip non-understood messages
999  *  nhop_external - nexhop description structure (with length)
1000  *  nhop_addrs - structure encapsulating GW/SRC sockaddrs
1001  */
1002 static int
1003 dump_nhop_entry(struct rib_head *rh, struct nhop_object *nh, struct sysctl_req *w)
1004 {
1005 	struct {
1006 		struct rt_msghdr	rtm;
1007 		struct nhop_external	nhe;
1008 		struct nhop_addrs	na;
1009 	} arpc;
1010 	struct nhop_external *pnhe;
1011 	struct sockaddr *gw_sa, *src_sa;
1012 	struct sockaddr_storage ss;
1013 	size_t addrs_len;
1014 	int error;
1015 
1016 	memset(&arpc, 0, sizeof(arpc));
1017 
1018 	arpc.rtm.rtm_msglen = sizeof(arpc);
1019 	arpc.rtm.rtm_version = RTM_VERSION;
1020 	arpc.rtm.rtm_type = RTM_GET;
1021 	//arpc.rtm.rtm_flags = RTF_UP;
1022 	arpc.rtm.rtm_flags = nh->nh_priv->rt_flags;
1023 
1024 	/* nhop_external */
1025 	pnhe = &arpc.nhe;
1026 	pnhe->nh_len = sizeof(struct nhop_external);
1027 	pnhe->nh_idx = nh->nh_priv->nh_idx;
1028 	pnhe->nh_fib = rh->rib_fibnum;
1029 	pnhe->ifindex = nh->nh_ifp->if_index;
1030 	pnhe->aifindex = nh->nh_aifp->if_index;
1031 	pnhe->nh_family = nh->nh_priv->nh_upper_family;
1032 	pnhe->nh_type = nh->nh_priv->nh_type;
1033 	pnhe->nh_mtu = nh->nh_mtu;
1034 	pnhe->nh_flags = nh->nh_flags;
1035 
1036 	memcpy(pnhe->nh_prepend, nh->nh_prepend, sizeof(nh->nh_prepend));
1037 	pnhe->prepend_len = nh->nh_prepend_len;
1038 	pnhe->nh_refcount = nh->nh_priv->nh_refcnt;
1039 	pnhe->nh_pksent = counter_u64_fetch(nh->nh_pksent);
1040 
1041 	/* sockaddr container */
1042 	addrs_len = sizeof(struct nhop_addrs);
1043 	arpc.na.gw_sa_off = addrs_len;
1044 	gw_sa = (struct sockaddr *)&nh->gw4_sa;
1045 	addrs_len += gw_sa->sa_len;
1046 
1047 	src_sa = nh->nh_ifa->ifa_addr;
1048 	if (src_sa->sa_family == AF_LINK) {
1049 		/* Shorten structure */
1050 		memset(&ss, 0, sizeof(struct sockaddr_storage));
1051 		fill_sdl_from_ifp((struct sockaddr_dl_short *)&ss,
1052 		    nh->nh_ifa->ifa_ifp);
1053 		src_sa = (struct sockaddr *)&ss;
1054 	}
1055 	arpc.na.src_sa_off = addrs_len;
1056 	addrs_len += src_sa->sa_len;
1057 
1058 	/* Write total container length */
1059 	arpc.na.na_len = addrs_len;
1060 
1061 	arpc.rtm.rtm_msglen += arpc.na.na_len - sizeof(struct nhop_addrs);
1062 
1063 	error = SYSCTL_OUT(w, &arpc, sizeof(arpc));
1064 	if (error == 0)
1065 		error = SYSCTL_OUT(w, gw_sa, gw_sa->sa_len);
1066 	if (error == 0)
1067 		error = SYSCTL_OUT(w, src_sa, src_sa->sa_len);
1068 
1069 	return (error);
1070 }
1071 
1072 uint32_t
1073 nhops_get_count(struct rib_head *rh)
1074 {
1075 	struct nh_control *ctl;
1076 	uint32_t count;
1077 
1078 	ctl = rh->nh_control;
1079 
1080 	NHOPS_RLOCK(ctl);
1081 	count = ctl->nh_head.items_count;
1082 	NHOPS_RUNLOCK(ctl);
1083 
1084 	return (count);
1085 }
1086 
1087 int
1088 nhops_dump_sysctl(struct rib_head *rh, struct sysctl_req *w)
1089 {
1090 	struct nh_control *ctl;
1091 	struct nhop_priv *nh_priv;
1092 	int error;
1093 
1094 	ctl = rh->nh_control;
1095 
1096 	NHOPS_RLOCK(ctl);
1097 #if DEBUG_MAX_LEVEL >= LOG_DEBUG
1098 	FIB_LOG(LOG_DEBUG, rh->rib_fibnum, rh->rib_family, "dump %u items",
1099 	    ctl->nh_head.items_count);
1100 #endif
1101 	CHT_SLIST_FOREACH(&ctl->nh_head, nhops, nh_priv) {
1102 		error = dump_nhop_entry(rh, nh_priv->nh, w);
1103 		if (error != 0) {
1104 			NHOPS_RUNLOCK(ctl);
1105 			return (error);
1106 		}
1107 	} CHT_SLIST_FOREACH_END;
1108 	NHOPS_RUNLOCK(ctl);
1109 
1110 	return (0);
1111 }
1112