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